Swift uses NSURLConnection for Synchronous asynchronous download (instance parsing) and swiftnsurl

Source: Internet
Author: User

Swift uses NSURLConnection for Synchronous asynchronous download (instance parsing) and swiftnsurl

Original blog, reprinted, please indicate the source

Http://blog.csdn.net/hello_hwc

I. synchronous and asynchronous

In short, synchronization means that the function or closure (the block in objective c) can be returned only after execution. Asynchronous is to return immediately, and then call back after the asynchronous action is completed.

Ii. synchronous download
Synchronous download:
class func sendSynchronousRequest(_ request: NSURLRequest,returningResponse response:AutoreleasingUnsafeMutablePointer<NSURLresponse>error error:NSErrorPointer)->NSdata?
Parameters:
URLRequest to be requested
The reponse callback parameter, the URL response returned by the server
Error callback parameter to determine whether an error is generated
The following uses downloading an image as an example.
It can be found that when the view appears, the picture already exists, but the view loading is slow, because you have to wait for the synchronization download to complete.
Complete code:
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()    }}

Iii. asynchronous download
class func sendAsynchronousRequest(_ request: NSURLRequest,queue:NSOperationQueue!completionHandler handler:(NSURLResponse!,NSData!,NSError!))->Void
Parameters:
URLRequest to be requested
When a request is completed or an error occurs, the closure is executed on this queue. To change the UI, it must be executed on the main thread.
Handler: the closure that is executed when the request is completed or an error occurs.
Closure Parameters
The reponse callback parameter, the URL response returned by the server
Error callback parameter to determine whether an error is generated
Data downloaded from NSData
Take an image as an example.
You can find that the view is loaded immediately, but the image does not appear immediately. After the image is downloaded, the UI is updated. As you can see, asynchronous download does not block the UI, resulting in poor user experience.
Complete code
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()    }}

Source image downloaded

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.