【问题标题】:Swift JSON parsing username and passwordSwift JSON 解析用户名和密码
【发布时间】:2017-05-31 19:02:27
【问题描述】:

我正在尝试通过 JSON 格式将用户名和密码作为 NSDictionary 发布。我收到以下错误:

域=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()
}
}

【问题讨论】:

  • stackoverflow.com/a/41328809/6656894 参考这个答案@SwiftUser
  • @HimanshuMoradiya 我确实尝试了你的脚本,但我仍然通过它。我觉得 Xcode 正在发送空包。
  • 哥把你的项目发给我,我会检查的。
  • 兄弟,我对 php 的了解不够,所以如果您在 ios 中遇到问题,我无法在 php 方面为您提供帮助,那么我可以帮助您并且已经建议您回答

标签: ios json swift


【解决方案1】:

在我看来,您的字符串没有正确序列化。而不是您当前的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多