同/异&步请求
同步:
// MARK: - 同步请求 func httpSynchronousRequest() { //创建NSURL对象 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") //创建请求对象 var urlRequest : NSURLRequest = NSURLRequest(URL: url) //响应对象 var response:NSURLResponse? //错误对象 var error:NSError? //发出请求 var data:NSData? = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &response, error: &error) if (error != nil) { println(error?.code) println(error?.description) }else { var jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding) println(jsonString) } }
异步:、
// MARK: - 异步请求 func httpAsynchronousRequest() { //创建NSURL对象 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") //创建请求对象 var urlRequest : NSURLRequest = NSURLRequest(URL: url) //网络连接对象 // var conn : NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self)? //2015年5月2后修改 var conn : NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self) conn?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) //执行 conn?.start() }