2014-02-07 148 views
4

我需要從URL和地方複製的文本文件/我的應用程序的文件夾覆蓋它,然後讀回數據變量。 我有以下代碼:如何將文件從URL複製到文檔文件夾?

NSData *data; 

//get docsDir 
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsDir=[paths objectAtIndex:0]; 

//get path to text.txt 
NSString *filePath=[docsDir stringByAppendingPathComponent:@"text.txt"]; 

//copy file 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 

if([fileManager fileExistsAtPath:filePath]==YES){ 
    [fileManager removeItemAtPath:filePath error:&error]; 
} 

NSString *urlText = @"http://www.abc.com/text.txt"; 

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{ 
    NSFileManager *fileManager=[NSFileManager defaultManager]; 
    [fileManager copyItemAtPath:urlText toPath:filePath error:NULL]; 
} 

//Load from file 
NSString *myString=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; 

//convert string to data 
data=[myString dataUsingEncoding:NSUTF8StringEncoding]; 

它建立在好辦法的規定,但我不能在我的文檔文件夾中創建的text.txt文件,然後通過什麼我的數據變量。 我既IOS和Xcode中,任何線索將不勝感激一個新手。謝謝!!

回答

2

的NSFileManager只能處理本地路徑。如果你給它一個URL,它將不會起任何作用。

copyItemAtPath:toPath:error:需要一個誤差參數。使用它,就像這樣:

NSError *error; 
if (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) { 
    NSLog(@"Error %@", error); 
} 

你會再得到這個錯誤:

Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be 
completed. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt, 
NSUnderlyingError=0x9a83b80 "The operation couldn’t be completed. 
No such file or directory"} 

它不能在http://www.abc.com/text.txt讀取這個文件,因爲它不是一個有效的路徑。


晴天沙阿沒有任何解釋說明你的URL首先獲取對象:

NSString *urlText = @"http://www.abc.com/text.txt"; 

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{ 
    NSURL *url = [NSURL URLWithString:urlText]; 
    NSError *error; 
    NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error]; 
    if (!data) { // check if download has failed 
     NSLog(@"Error fetching file %@", error); 
    } 
    else { 
     // successful download 
     if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed 
      NSLog(@"Error writing file %@", error); 
     } 
     else { 
      NSLog(@"File saved."); 
     } 
    } 
} 

務必檢查錯誤!

+0

它運作良好,感謝Matthias和Sunny!我已經工作了幾天了! 此外,我的Xcode調試控制檯不顯示任何內容。我不知道爲什麼.. –

1

你應該從URL獲取數據,並使用將writeToFile

NSData *urlData = [NSData dataWithContentsOfURL: [NSURL URLWithString:urlText]]; 
    [urlData writeToFile:filePath atomically:YES]; 
+0

感謝您的意見。我曾經試過,但「urlText」與此不兼容,因爲它需要與dataWithContentsOfURL使用NSURL類型......我改變爲如下,但仍然不能正常工作: 的NSData * urlData = [NSData的dataWithContentsOfFile:urlText]。 [urlData將writeToFile:文件路徑原子:YES]; –

+0

你應該將urlText(string)轉換爲url。請檢查答案 –

相關問題