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()
}
}
http://stackoverflow.com/a/41328809/6656894参考此答案@SwiftUser –
@HimanshuMoradiya我没试过你的脚本,但还是我通过它得到。我感觉Xcode正在发送空包。 – SwiftUser
兄弟给我你的项目,我会检查它。 –