从Web到iPhone文档目录下载图像或mp3文件
大家好
我正在使用此代码从我的网站下载文件
首先,我检查文件是否存在
- (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];
}
此代码下载:
- (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");
}
}
日志打印'成功'但不将文件复制到文档目录!!
答案 0 :(得分:2)
我们试试:(参见我的评论)
- (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");
}
}
答案 1 :(得分:1)
我通过使用您的代码获得了成功,检查了您的文档目录。路径是
/Users/userName/Library/Application Support/iPhone Simulator/7.1/Applications/your project/Documents/background2.jpg