标签:swift nsurlconnecttion 同步 异步
原创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参数:
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进行同步异步下载(实例解析)
标签:swift nsurlconnecttion 同步 异步
原文地址:http://blog.csdn.net/hello_hwc/article/details/41006531