從網絡下載的圖像或MP3文件到iPhone文件目錄大家下載圖片或MP3文件到iPhone文件目錄
嗨
我使用這個代碼從我的網站下載文件網站
首先,我檢查,如果文件中存在
- (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");
}
}
日誌打印「成功」,但不將文件複製到文檔目錄!
簡單易用的方式,以這種使用AFNetworking HTTPS ://github.com/AFNetworking/AFNetworking –