2017-01-16 78 views
1

我想通過JSON格式將用戶名&密碼作爲NSDictionary發佈。我得到這個以下錯誤:Swift JSON解析用戶名和密碼

域= NSCocoaErrorDomain代碼= 3840「
JSON文字不與數組或對象和選項,允許片段不設置啓動。」
的UserInfo = {NSDebugDescription = JSON文字不與數組或對象,並選擇允許片段不設置啓動。}

我的代碼如下:

@IBAction func loginAuthentication(_ sender: UIButton) { 
    let username : NSString = NameTextField.text! as NSString 
    let password : NSString = passwordTextField.text! as NSString 

    let parameters = [ 
     "username": "\(username)", 
     "password": "\(password)" 
    ] 
    print(parameters) 

    let headers = [ 
     "content-type": "application/json", 
     "cache-control": "no-cache", 
     "postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0" 
    ] 

     if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) { 

     let request = NSMutableURLRequest(url: URL(string: "http://..")!, 
              cachePolicy: .useProtocolCachePolicy, 
              timeoutInterval: 10.0) 
     request.httpMethod = "POST" 
     request.allHTTPHeaderFields = headers 
     request.httpBody = postData 

     print(request.httpBody) 

     // let session = URLSession.shared 

     let task = URLSession.shared.dataTask(with: request as URLRequest) { 
      (data, response, error) -> Void in 
        if (error != nil) { 
             print("Error message \(error)") 

             } else { 
        DispatchQueue.main.async(execute: { 

             if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary 
             { 
              let success = json["error"] as? Bool 

              print("Error from php\(success)") 

              let message = json["message"] as? String 
               // here you check your success code. 
               if (success == false) 
                 { 
                 print("Result1 \(message)") 
                 self.performSegue(withIdentifier: "", sender: self) 
                 } 
               else 
                 { 
                  self.dismiss(animated: true, completion: nil) 
                  print("Result2 \(message)") 
                 } 

             } 

             }) 
           } 
     } 

     task.resume() 
} 
} 
+0

http://stackoverflow.com/a/41328809/6656894參考此答案@SwiftUser –

+0

@HimanshuMoradiya我沒試過你的腳本,但還是我通過它得到。我感覺Xcode正在發送空包。 – SwiftUser

+0

兄弟給我你的項目,我會檢查它。 –

回答

0

的問題在我看來像你字符串未正確序列化。不要使用當前的json序列化方法,只需將swift字典轉換爲數據即可。

//Start with a dictionary 
let body = [ 
    "username": "bob", 
    "password": "admin" 
] 
//Serialize it.... you might want to put this in a do try catch block instead 
let jsonBody = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) 
//Add it to the request 
request.httpBody = jsonBody 

//make the request, etc. 
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response, error in