Download image or mp3 files from Web to iPhone document directory
Hi everyone
I am using this code to download files from my Web site
First, i check if file exist
- (void)checkFile
{
image_path = @"background2.jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *myFilePath = [libraryDirectory stringByAppendingPathComponent:image_path];
BOOL fileExists = [fileManager fileExistsAtPath:myFilePath];
if (fileExists) {
NSLog(@"file exist");
self.myImage.image = [UIImage imageWithContentsOfFile:myFilePath];
} else {
NSLog(@"file not exist");
[self downloadImageFile:@"http://www.alhikmeh.org/images/background2.jpg" newFileName:image_path];
}
This code for download:
- (void)downloadImageFile:(NSString *)path newFileName:(NSString *)newFileName
{
NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSData *data = [NSData dataWithContentsOfURL:URL];
if (data == nil) {
NSLog(@"error");
}
NSString *appDocDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [appDocDir stringByAppendingPathComponent:newFileName];
BOOL success = [data writeToFile:storePath atomically:YES];
if (success) {
NSLog(@"success");
} else {
NSLog(@"not copied");
}
}
The log print 'success' but not copy the file to document Directory!!
Let's try: (see my comment)
- (void)downloadImageFile:(NSString *)path newFileName:(NSString *)newFileName
{
NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSData *data = [NSData dataWithContentsOfURL:URL];
if (data == nil) {
NSLog(@"error");
}
NSString *appDocDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [appDocDir stringByAppendingPathComponent:newFileName];
// My comment : make sure that you check whether this file exists at above path???
// I run this code, and it can save data.
NSlog(@"%@",storePath);
BOOL success = [data writeToFile:storePath atomically:YES];
if (success) {
NSLog(@"success");
} else {
NSLog(@"not copied");
}
}
我使用您的代码成功,请检查您的文档目录。路径为
/Users/userName/Library/Application Support/iPhone Simulator/7.1/Applications/your project/Documents/background2.jpg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.