swift 3中的POST方法对JSONSerialization.jsonObject的响应为nil [英] Response of JSONSerialization.jsonObject is nil with the method POST in swift 3

查看:172
本文介绍了swift 3中的POST方法对JSONSerialization.jsonObject的响应为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要执行的操作的示例,但行if let json = try JSONSerialization.jsonObject(with: data) as? [String: String]false,因为JSONSerialization.jsonObject的返回是nil

this is an example for something i want to do but the line if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] is false because the return of JSONSerialization.jsonObject is nil

func parser(lbl: UILabel){
    let postString = "xxx=xxx&xxxx=xxxx==&xxxxx=xxxxx&xxxxxx=xxxxxx&xx=xx"

    let url = URL(string: "http://xxxxxxxxxx.com/xxxxxx/xxxxx/xxxxxx.php")!
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            lbl.text = "error";

            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
                DispatchQueue.main.async {

                    let error = Int(json["success"]!)

                    let message = json["message"]
                    lbl.text = message
                }
            } 
        } catch let parseError {
            print("error to parse: \(parseError)")

            let responseString = String(data: data, encoding: .utf8)
            print("response`enter code here` : \(responseString!)")
        }
    }
    task.resume()
}

推荐答案

尝试一下:

var resultFromServer: Any?
resultFromServer = try JSONSerialization.jsonObject(with: data!, options: [])

这应该为您提供resultFromServer类型的Any?,只需根据获得的响应的基础(数组或字典)进行检查和类型转换即可.

This should give you resultFromServer as type of Any?, simply check and typecast depending on the basis of the response you are getting, an array or a dictionary.

if let respdict = resultFromServer as? [String : Any] {
//respone in dictionary format
}

else if let respArr = resultFromServer as? [Any]{
//response is array type
}

else if let stringRespt = String(data: data, encoding: .utf8){
//resp is string                                
}

只需根据您的JSON进行更改

Just make changes as per your JSON

这篇关于swift 3中的POST方法对JSONSerialization.jsonObject的响应为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆