同/异&步请求
同步:
1 // MARK: - 同步请求 2 func httpSynchronousRequest() 3 { 4 //创建NSURL对象 5 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") 6 7 //创建请求对象 8 var urlRequest : NSURLRequest = NSURLRequest(URL: url) 9 10 //响应对象 11 var response:NSURLResponse? 12 13 //错误对象 14 var error:NSError? 15 16 //发出请求 17 var data:NSData? = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &response, error: &error) 18 19 if (error != nil) 20 { 21 println(error?.code) 22 println(error?.description) 23 }else 24 { 25 var jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding) 26 27 println(jsonString) 28 } 29 }
异步:、
1 // MARK: - 异步请求 2 func httpAsynchronousRequest() 3 { 4 //创建NSURL对象 5 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") 6 7 //创建请求对象 8 var urlRequest : NSURLRequest = NSURLRequest(URL: url) 9 10 //网络连接对象 11 // var conn : NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self)? 12 13 //2015年5月2后修改 14 var conn : NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) 15 16 conn?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) 17 18 //执行 19 conn?.start() 20 }
时间: 2024-10-12 00:36:53