swift 3.0 get请求(同步)

来源:互联网 发布:淘宝网 卖家中心 编辑:程序博客网 时间:2024/05/29 17:55
func synchronousGet(){                // 1、创建URL对象;        let url:URL! = URL(string:"http://samples.openweathermap.org/data/2.5/weather?lat=47&lon=144&appid=b1b15e88fa797225412429c1c50c");                // 2、创建Request对象        // url: 请求路径        // cachePolicy: 缓存协议        // timeoutInterval: 网络请求超时时间(单位:秒)        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 20)                // 3、响应对象        var response:URLResponse?                // 4、发出请求        do {                        let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary //(必须写as! NSDictionary 不然会出错)            print("@@@@@@@@@@@@@\(dic)")                                            } catch let error{            print(error.localizedDescription);        }    }

原创粉丝点击