使用URLSession解析Json无法正常工作

时间:2018-01-03 17:45:51

标签: ios swift3 urlsession

当我尝试在swift 3中发送POST请求时出现错误。任何人请建议我在swift 3中使用URLSession.shared方法的正确语法。这就是我尝试过的。我是新来的。

let task = URLSession.shared.dataTask(with: request, completionHandler: { 
            (data, response, error) in 

            if error != nil{
                print("error");
                return
            }

            do{
                let myjson = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                if let parsejson = myjson{
                    var msg: String!
                    msg = parsejson["message"] as! String?
                    print(msg)
                }catch error  {
                print ("")

                }
            }
            })
        task.resume().   

1 个答案:

答案 0 :(得分:0)

这里有URLSession.shared代码。我没有你的网址,所以我使用了一个在线,免费的,并生成JSON:

let someURL = URL(string:"https://jsonplaceholder.typicode.com/posts/2")!
let request = URLRequest(url: someURL)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if error != nil {
        print("error")
        return
    }
    guard let data = data else {
        print("No data")
        return
    }

    do {
        if let myjson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Dictionary<String,Any> {
            if let title = myjson["title"] {
                print("Title was \"\(title)\"")
            }
        }
    } catch {
        print("Error parsing JSON: \(error)")
    }

}
task.resume()

这为我输出Title was "qui est esse"