[英]Download image or mp3 files from Web to iPhone document directory
從Web將圖像或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");
}
}
日志打印“成功”,但未將文件復制到文檔目錄中!!
讓我們嘗試:(請參閱我的評論)
- (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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.