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];
}