Swift is using nsurlconnection asynchronous download synchronization (instance resolution)

Source: Internet
Author: User
Tags closure

The original blog. Reprint please indicate the source

Http://blog.csdn.net/hello_hwc

One, synchronous asynchronous two concepts

In simple terms. Synchronization is the function or closure (block in Objective C) that completes the ability to return.

Async is returned immediately, and then asynchronously runs after the end of the action. The callback is then performed.

Second, synchronous download
Sync Download:

Class Func Sendsynchronousrequest (_ Request:nsurlrequest,returningresponse response: Autoreleasingunsafemutablepointer<nsurlresponse>error error:nserrorpointer)->NSdata?

Number of references:
Request The URLRequest to request
Reponse Callback parameters, the URL returned by the server response
Error Callback parameters. Infer whether there is an error generating
Here is an example of a picture below
can find. When the view appears. The photo already exists, but the view load is slow. Due to wait for synchronization to download complete
The 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 () }}


third, asynchronous download
Class Func Sendasynchronousrequest (_ Request:nsurlrequest,queue:nsoperationqueue!completionhandler Handler: ( nsurlresponse!,nsdata!,nserror!)) ->void
Number of references:
Request The URLRequest to request
Queue The closure runs on this queue when the request is complete or when an error occurs. Changing the UI to run on the main thread
Handler When a request is complete or an error occurs, the closed packet that is run
Several parameters of closures
Reponse Callback parameters, the URL returned by the server response
Error Callback parameters to infer if an error occurred
NSData Data downloaded to
Same as an example of a picture
Be able to discover that view is loaded instantly. But the picture does not appear immediately. Wait until the picture is finished downloading. The UI is updated.

Can see that the asynchronous download does not clog the UI, resulting in a bad user experience.
The 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 ()    }}

Download the original picture

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvsgvsbg9fshdj/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "width=" "height=" >

Swift is using nsurlconnection asynchronous download synchronization (instance resolution)

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.