Swift 系统学习 32 dataTask 解析JSON 打印当前线程

 // Swift3.0将Foundation中的NS前缀去掉
    func parseJSONData() {
        // 1.config对象
        let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default
        // 自定义设置属性
        // 指定客户端接受的数据类型
        sessionConfig.httpAdditionalHeaders = ["Accept": "application/json"]
        // 设置请求/响应timeout(单位: 秒)
        sessionConfig.timeoutIntervalForRequest = 10.0
        sessionConfig.timeoutIntervalForResource = 20.0
        // 2.创建session
        let session = URLSession(configuration: sessionConfig)
        // 3.创建request
        let request = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=Barcelona,es&appid=ac02dc102cc17b974cd84206048d97d8")!)
        // 4.创建dataTask任务
        let dataTask = session.dataTask(with: request) { (data, response, error) in
            // data, response, error都是可选型
            if let error = error {
                print("服务器返回失败: \(error.localizedDescription)")
            } else {
               // 没有错误
                if let data = data {
                    // dictionary是Any?
                    // 解包+转成字典类型
                    if let dictionary = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) {
                        // dictionary是Any类型
                        let dic = (dictionary as? NSDictionary)!
                        // "name":"Barcelona",
                        let cityName = dic["name"] as! String
                        let temp = (dic["main"] as! NSDictionary)["temp"] as! Double
                        print("City name is \(cityName) and temp is \(temp)")
                        // 课堂练习:
                        
                        // 回到主线程: why?(主线程负责: 用户事件+UI Kit所有控件)
                        // Swift3.0对GCD的api更改
//                        DispatchQueue.main.async(execute: { 
//                            // 更新控件
//                        })
//                        dispatch_asyn(dispatch_get_main_queue, ^(){
//                            
//                            })
                        
                    }
             
                }
               
            }
        }
        // 5.执行任务
        dataTask.resume()
        
    }

猜你喜欢

转载自blog.csdn.net/clarence20170301/article/details/59109316
今日推荐