5
我的遠程服務器上有一個文件夾,裏面有幾個.png文件。我想從我的應用程序中下載這些內容並將它們存儲在應用程序的「文檔」文件夾中。我怎樣才能做到這一點?如何從互聯網下載文件並保存在iPhone上的「文檔」中?
我的遠程服務器上有一個文件夾,裏面有幾個.png文件。我想從我的應用程序中下載這些內容並將它們存儲在應用程序的「文檔」文件夾中。我怎樣才能做到這一點?如何從互聯網下載文件並保存在iPhone上的「文檔」中?
簡單的方法是使用NSData的便捷方法initWithContentOfURL:
和writeToFile:atomically:
分別獲取數據和寫出數據。請記住,這是同步的,並會阻止您執行它的任何線程,直到抓取和寫入完成。
例如:
// Create and escape the URL for the fetch
NSString *URLString = @"http://example.com/example.png";
NSURL *URL = [NSURL URLWithString:
[URLString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding]];
// Do the fetch - blocks!
NSData *imageData = [NSData dataWithContentsOfURL:URL];
if(imageData == nil) {
// Error - handle appropriately
}
// Do the write
NSString *filePath = [[self documentsDirectory]
stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];
凡documentsDirectory
方法是無恥地從this question被盜:
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
但是,除非你打算線程它自己這個會停止,而文件的下載用戶界面活動。你可以改爲查看NSURLConnection及其委託 - 它在後臺下載並通知委託有關異步下載的數據,所以你可以建立一個NSMutableData實例,然後在連接完成時寫出它。你代表可能包含如下方法:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the data to some preexisting @property NSMutableData *dataAccumulator;
[self.dataAccumulator appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do the write
NSString *filePath = [[self documentsDirectory]
stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];
}
的小細節,像聲明dataAccumulator
和處理錯誤,都留給讀者:)
的重要文件:
謝謝!嗯...同步?這是否意味着我在工作完成時最好使用「進度輪/酒吧」? – RexOnRoids 2009-08-26 03:09:58
同步意味着程序中的所有活動(以及主線程)將完全停止,直到下載完成。這意味着用戶界面將顯示爲凍結狀態,並且直到下載完成後,旋轉器纔會啓動動畫製作(使其非常無用)。第二種方法是異步下載,讓您的程序在後臺下載時在前臺繼續工作。無論哪種方式,是的,你應該使用某種進度指示器。 – Tim 2009-08-26 03:13:06