IOS image download

Source: Internet
Author: User

Recently, I made a function for IOS program. If the image is displayed locally, I downloaded it online and stored it. After finding the information on the Internet, I realized the function based on my own understanding. The following describes the concept.

Implements a class that inherits imageView. The main function of this class is to determine whether the image exists locally based on the sent image name. If the image does not exist, it is downloaded and displayed directly if it exists.


-(Void) drawRect :( CGRect) rect {

NSString * docDir = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];

NSString * picPath = [docDir stringByAppendingPathComponent: self. picName]; // obtain the path

If ([[NSFileManager defaultManager] fileExistsAtPath: picPath]) {

// Read images directly when they exist

NSData * data = [NSData dataWithContentsOfFile: picPath];

Self. thumbnail. image = [UIImage imageWithData: data];

}

Else {// open the thread to download and store

[NSThread detachNewThreadSelector: @ selector (loadImage) toTarget: self withObject: nil];

}

}

 


-(Void) loadImage {

// Download the image

NSURL * url = [NSURL URLWithString: @ "http://www.baidu.com/img/baidu_sylogo1.gif"];

UIImage * img = [[UIImage alloc] initWithData: [NSData dataWithContentsOfURL: url];

Self. thumbnail. image = img;

// Store images

NSString * docDir = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];

NSString * picPath = [docDir stringByAppendingPathComponent: self. picName];

// Write the image to the Documents file

[UIImagePNGRepresentation (self. thumbnail. image) writeToFile: picPath atomically: YES];

 


// Exit the thread

[NSThread exit];

}
 

 

 

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.