Swift explanation 14: swift explanation

Source: Internet
Author: User

Swift explanation 14: swift explanation
NSThread asynchronous download of images

There are three solutions for processing multithreading in IOS: NSThread, NSOperation, and GCD. Of course, GCD should be the most convenient. We should learn it one by one. First understand the underlying layer, and finally use the most convenient.

NSThread:
Advantage: NSThread is lighter than the other two
Disadvantage: You need to manage the thread lifecycle and synchronize the thread. Thread Synchronization locks data with a certain amount of system overhead

First, we will study how to useNSThreadAsynchronously load network images:

NSThread can be created in either of the following ways. One is through the class method.

let thread = NSThread(target: self, selector: "doSomeThing", object: nil); NSThread.detachNewThreadSelector("doSomeThing1", toTarget: self, withObject: nil);

This function is automatically enabled when a class method is created. Manual calls are required when an instance method is created.start()Method to enable

 let  picAddress = "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png"    let  picAddress1 = "https://avatars2.githubusercontent.com/u/8502419?v=3&s=400"

Here we first define two diagrams from the network

@IBOutlet weak var activity: UIActivityIndicatorView!@IBOutlet weak var imageView: UIImageView!

Then two controls are added to the interface, oneUIImageViewUsed to display images.UIActivityIndicatorViewDisplays the circled information during loading.

Then, create two buttons. No. The source code is attached.
In the viewDidLoad method, Setactivity.hidden = trueHide the activity control by default.

Code for clicking the event on the first button

 activity.hidden = false activity.startAnimating()      NSThread.detachNewThreadSelector("downLoadImage", toTarget: self, withObject: nil);

Display Control, enable animation, and enable a thread

Selector: the method of thread execution. This selector can have only one parameter and cannot return values. Target: the object sent by the selector message withObject: the unique parameter transmitted to the target. It can also be nil.

This is an explanation of the three parameters.

Func downLoadImage () {print ("I want to download an image") if let url = NSURL (string: picAddress) {if let data = NSData (contentsOfURL: url) {let img = UIImage (data: data) if (img! = Nil) {// This method is not available in swift. Then use the gcd method to dispatch_async (dispatch_get_main_queue () {self. imageView. image = img !; Self. activity. hidden = true print ("image downloaded")} else {print ("baidu")} else {print ("image not retrieved from url ")}} else {print ("No url available ")}}

This is the method implemented by the thread. After the data is downloaded, the UI is updated through the main thread.
Another button Method

   activity.hidden = false        activity.startAnimating()        let thread = NSThread(target: self, selector: "downLoadImage1:", object: picAddress1);        thread.start();

A parameter is passed here. In fact, two methods can be used. You can just upload different addresses. Here we will learn more. Two methods are used for testing.

Func downLoadImage1 (str: String) {print ("I want to download an image") if let url = NSURL (string: str) {if let data = NSData (contentsOfURL: url) {let img = UIImage (data: data) if (img! = Nil) {// This method is not available in swift. Then use the gcd method to dispatch_async (dispatch_get_main_queue () {self. imageView. image = img !; Self. activity. hidden = true print ("image downloaded")} else {print ("baidu")} else {print ("image not retrieved from url ")}} else {print ("No url available ")}}

This is the second button method.

The effect is to click a button and wait in a circle. Then, the image is displayed, and the image is displayed after you click the other button.
Xcode 6 and NSData can obtain most network images. Many images cannot be obtained in XCode 7 beta. This is probably a security issue. No good solutions have been found yet.
I am using xcode 7 beta code.
: Swift asynchronously retrieves network images

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.