2016-02-23 77 views
0

我需要使用swift2.0中的nsurl會話將json請求參數發送到服務器。我不知道如何創建json請求params.i創建了像這樣的參數如何使用swift 2.0發佈json請求參數

let jsonObj = [「Username」:「Admin」,「Password」:「123」,「DeviceId」:「87878」 ]

// print("Params are \(jsonObj)") 

    //request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonObj, options: []) 

    // or if you think the conversion might actually fail (which is unlikely if you built `params` yourself) 

    do { 
     request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonObj, options:.PrettyPrinted) 
    } catch { 
     print(error) 
    } 

,但它不是平的方法體,所以我得到的失敗響應

回答

2

嘗試下面的代碼。

let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String> 
    let request = NSMutableURLRequest(URL: NSURL(string:YOURURL)!) 

    let session = NSURLSession.sharedSession() 
    request.HTTPMethod = "POST" 

    //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json. 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: []) 

    let task = session.dataTaskWithRequest(request) { data, response, error in 
     guard data != nil else { 
      print("no data found: \(error)") 
      return 
     } 

     do { 
      if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { 
       print("Response: \(json)") 
      } else { 
       let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary 
       print("Error could not parse JSON: \(jsonStr)") 
      } 
     } catch let parseError { 
      print(parseError)// Log the error thrown by `JSONObjectWithData` 
      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("Error could not parse JSON: '\(jsonStr)'") 
     } 
    } 

    task.resume() 

希望它適合你!

+0

謝謝:)其有用的 –