2014-04-21 61 views
0

從網絡下載的圖像或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"); 
    } 


} 

日誌打印「成功」,但不將文件複製到文檔目錄!

+0

簡單易用的方式,以這種使用AFNetworking HTTPS ://github.com/AFNetworking/AFNetworking –

回答

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"); 
} 
} 
+0

它是我的錯,從'NSLibraryDirectory'加載文件並保存到'NSDocumentDirectory',謝謝 –

+0

我可以做一個進度條到這個下載嗎? –

+0

當然,你應該在後臺線程中下載。在下載時,您將計算顯示在進度條中的大小。 http://stackoverflow.com/questions/16453655/objective-c-downloading-file-with-progress-bar – nmh

1

我被利用的代碼sucessed,檢查文檔directory.The路徑是

/Users/userName/Library/Application Support/iPhone Simulator/7.1/Applications/your project/Documents/background2.jpg