我想從一個服務器使用API下載文件,因爲我發送一個請求時,該鏈接上的內容進入到iphone/ipod touch中的我的文檔目錄中,下載後可以將它們從文檔目錄中刪除。有沒有辦法做這樣的事情。我們怎樣才能從服務器下載文件到我們的iPhone文檔目錄?
感謝 Balraj
我想從一個服務器使用API下載文件,因爲我發送一個請求時,該鏈接上的內容進入到iphone/ipod touch中的我的文檔目錄中,下載後可以將它們從文檔目錄中刪除。有沒有辦法做這樣的事情。我們怎樣才能從服務器下載文件到我們的iPhone文檔目錄?
感謝 Balraj
最簡單的方法是使用ASIHTTPRequest做:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDownloadDestinationPath:@"{path to file in documents folder}"]];
[request startAsynchronous];
...
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Downloaded file is ready for use
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
// Download failed. This is why.
NSError *error = [request error];
}
NSData *data = [NSData dataWithContentsOfURL:@"http://site.com/filename"];
NSArray *docList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [docList objectAtIndex:0];
NSString *documentPath = [historicDocumentDir stringByAppendingPathComponent:@"filename"];
[data writeToFile:documentPath atomically:NO];
添加錯誤檢查。
要從文件夾使用刪除文件:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
這是iPhone API,如果是它它是框架? – Ballu 2009-10-06 22:14:48
ASIHTTPRequest。鏈接位於代碼上方的文本中。 – Ramin 2009-10-06 23:25:07