2012-02-28 25 views
3

我使用下面顯示的代碼下載了該文件。然後,我試圖將NSMutableData變量保存到文件,但是,該文件未創建。我究竟做錯了什麼?我是否需要將NSMutableData轉換爲NSString?NSMutableData保存到文件

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response { 
    response = [_response retain]; 
    if([response expectedContentLength] < 1) { 
     data = [[NSMutableData alloc] init]; 
    } 
    else { 
     data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain]; 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data { 
    [data appendData:_data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"]; 

    NSLog(@"saved: %@", filePath); 
    [data writeToFile:filePath atomically:YES]; 
    NSLog(@"downloaded file: %@", data); //all i see in log is some encoded data here 
} 
+0

這肯定會幫助,如果你傳遞了一個NSError變量將writeToFile的地址,並測試了函數的返回值。 – 2012-02-28 21:43:07

回答

10

你不能在你的應用程序包中寫入。你需要將它保存在其他地方,比如你的應用程序的文件目錄:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"]; 
[data writeToFile:filePath atomically:YES]; 
+0

感謝這工作..文件保存在模擬器/ USER /蘋果/圖書館/應用程序.../iPhone模擬器/ 5.0/App_key /文件。我無法從文件夾瀏覽中找到圖書館文件夾。但是,使用命令行我能夠找到這個保存的文件。謝謝諾亞的意見。 – user914425 2012-02-29 15:53:45