Synchronous asynchronous download using Nsurlconnection in Swift (instance resolution)

Source: Internet
Author: User



Original blog, reproduced please indicate the source



Http://blog.csdn.net/hello_hwc



One, synchronous asynchronous two concepts


Simply put, synchronization is the function or closure (block in Objective C) that is performed before it can be returned. The asynchronous is returned immediately, and then the callback is performed after the asynchronous execution of the action ends.

second, synchronous download
Sync Download:
class func sendSynchronousRequest(_ request: NSURLRequest,
returningResponse response:AutoreleasingUnsafeMutablePointer<NSURLresponse>
error error:NSErrorPointer)->NSdata?
Parameters:
Request The URLRequest to request
Reponse Callback parameter, the URL returned by the server response
Error Callback parameter to determine if there is an error generating
Here is an example of a picture below
It can be found that when the view appears, the photo already exists, but the view load is slow because it waits for the synchronization download to 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
Parameters:
Request The URLRequest to request
Queue When a request is completed or an error occurs, the closure is executed on this queue and the UI is changed to execute on the main thread.
Handler When a request is completed or an error occurs, the execution of the closure
Several parameters of closures
Reponse Callback parameter, the URL returned by the server response
Error Callback parameter to determine if there is an error generating
NSData Data downloaded to
Also take a picture as an example
you can see that the view is loaded immediately, but the picture does not appear immediately, and the UI is updated when the picture is downloaded. As you can see, an asynchronous download does not block the UI, causing 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






Synchronous asynchronous download using Nsurlconnection in Swift (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.