IPhoneApplication Development in progressCached filesIs the content to be introduced in this article, inIPhoneIn applications, we often need to download someFileSuch as xml and images! However, we often need to read this part of data repeatedly, or we need to write someFileIn the sandbox, we need to use it for the next time we open the program.Cached filesRead/writeFile), Today I will share with you a DemoCacheImages and xml downloaded from the internet;
Project Background:
Download the image from the network and write it in the temp directory. The files in the temp directory will be cleared when the program exits, so it is appropriate for me to write the cached content to be used this time ).
1. Download an image from a url
- NSURL *url = [NSURL URLWithString:@"http://*****.png"];
- NSData *data = [NSData dataWithContentsOfURL:url];
- UIImage *img = [UIImage imageWithData:data];
Note: This is the most common and common method for downloading images. This method is not very good. I will share with you some other methods later.
2. Get the temp directory
- -(NSString *)GetTempPath:(NSString*)filename{
- NSString *tempPath = NSTemporaryDirectory();
- return [tempPath stringByAppendingPathComponent:filename];
- }
The image name to be cached is passed in to obtain the complete temp path.
3. Write Data to the change path
- [data writeToFile:[self GetTempPath:@"test.png"] atomically:NO];
The writeToFile method of NSData is used here. You can find more detailed explanations in the API.
The first parameter is the path to write data.
The second parameter: whether to overwrite the original file. If YES, if NO is overwritten, the opposite is true.
Method returns a value of the BOOL type. YES indicates that the write is successful.
4. Determine whether the file in the path already exists
- -(BOOL)isExistsFile:(NSString *)filepath{
- NSFileManager *filemanage = [NSFileManager defaultManager];
- return [filemanage fileExistsAtPath:filepath];
- }
- BOOL exist = [self isExistsFile:[self GetTempPath:@"test.png"]];
Exist = YES indicates that the file already exists.
NO indicates NO
At this point, we can solve similar problems. Of course, you can not only save images to the temp directory, but also other files. Of course, it can also be stored in the document directory, so that we can hold it for a long time. We will share with you the SAVE and read operations in the document directory later!
Summary: DetailsIPhoneApplication Development in progressCached filesI hope this article will help you!