标签:
原版的blog。转载请注明出处
http://blog.csdn.net/hello_hwc
一、同步异步两个概念
简单来讲。同步就是函数或者闭包(objective c中的block)运行完成才干返回。异步是立马返回,然后异步运行的动作结束后。再进行回调。
二、同步下载
同步下载:
class func sendSynchronousRequest(_ request: NSURLRequest, returningResponse response:AutoreleasingUnsafeMutablePointer<NSURLresponse> error error:NSErrorPointer)->NSdata?參数:
class ViewController: UIViewController{ var imageview = UIImageView(frame: CGRectMake(40,40,200,200)) override func viewDidLoad(){ super.viewDidLoad() imageview.contentMode = UIViewContentMode.ScaleAspectFit self.view.addSubview(imageview) let url = "http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60191d32308fb1cb1348547760.jpg" let imageURL = NSURL(string:url) let urlRequest = NSURLRequest(URL: imageURL!) var response:NSURLResponse? var error:NSError?var data = NSURLConnection.sendSynchronousRequest(urlRequest,returningResponse:&response,error:&error) as NSData? if error == nil && data?.length > 0{ var image:UIImage = UIImage(data:data!)! imageview.image = image } } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() } }
class func sendAsynchronousRequest(_ request: NSURLRequest, queue:NSOperationQueue! completionHandler handler:(NSURLResponse!,NSData!,NSError!))->Void參数:
能够看到,异步下载不会堵塞UI,造成用户体验不好。
class ViewController: UIViewController{ var imageview = UIImageView(frame: CGRectMake(40,40,200,200)) override func viewDidLoad(){ super.viewDidLoad() imageview.contentMode = UIViewContentMode.ScaleAspectFit self.view.addSubview(imageview) let url = "http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60191d32308fb1cb1348547760.jpg" let imageURL = NSURL(string:url) let urlRequest = NSURLRequest(URL: imageURL!) NSURLConnection.sendAsynchronousRequest(urlRequest,queue:NSOperationQueue.mainQueue(),completionHandler:{ (response: NSURLResponse!,data:NSData!,error:NSError!)-> Void in if error == nil && data?.length > 0{ var image:UIImage = UIImage(data:data!)! self.imageview.image = image } }) } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() } }
下载的图片原图
Swift正在使用NSURLConnection异步下载同步(实例解析)
标签:
原文地址:http://www.cnblogs.com/yxwkf/p/5038400.html