HTTP请求GET JSON和读取数据

时间:2017-07-21 14:42:12

标签: json swift

我有一个快速的代码问题。我通过httpMethod POST向webserver请求。这个要求没问题。我在数据值中得到响应和数据。数据看起来像JSON

{"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}

然后我将根据响应数据加载此响应数据以设置按钮。但我没有写这段代码。有谁可以帮助我吗? :)

错误代码 Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)' //我测试了其他选项,但我总是失败: - (

我在代码中评论错误....

let url = "https://URL.php"
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
let bodyData = "token=" + (dts)
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) {
    (response, data, error) in

    // here i get the result of
    // {"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}
    var str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    var names = [String]()
    // here i will get each value of pushValues to add to the array names
    do {
        if let data = str,
        // ... and here is the error code by xcode ::: ==> Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)'
        // i tested with other options but i always fail :-(
        let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
        let blogs = json["pushValues"] as? [[String: Any]] {
            for blog in blogs {
                if let name = blog["devicePushGlobal"] as? String {
                    print(name)
                    names.append(name)
                }
            }
        }
    } catch {
        print("Error deserializing JSON: \(error)")
    }
    // names array is empty
    print(names)
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您不应使用NSString将JSON响应解码为var str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)JSONSerialization.jsonObject()期望Data对象作为输入参数,因此只需安全地解包可选的data变量并将其用作输入参数:

if let responesData = data, let json = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let blogs = json["pushValues"] as? [String: Any]

使用原生Swift类型的完整代码:

...
let request = URLRequest(url: URL(string: url)!)
...
URLSession.shared.dataTask(with: request, completionHandler: {
    (response, data, error) in
    var names = [String]()
    do {
        if let responseData = data, let json = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let blogs = json["pushValues"] as? [String: Any]{
            if let name = blog["devicePushGlobal"] as? Int {
                print(name)
                names.append(name)
            }
            if let newProducts = blog["devicePushNewProducts"] as? Int{}
            if let newOffers = blog["devicePushNewOffers"] as? Int{}
        }
    } catch {
        print("Error deserializing JSON: \(error)")
    }
    // names array is empty
    print(names)
}).resume()