i want to download a file from a server using API as i send a request the content on that link comes to my document d开发者_JS百科irectory in iphone/ipod touch, and after downloading is it possible to remove them from the document directory. is there any way to do the things like that .
Thanks Balraj
Easiest way is to use ASIHTTPRequest and do:
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];
}
To remove a file from your documents folder use:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
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];
Add error checking.
精彩评论