开发者

how can we download a file from a server to our document directory in iphone?

开发者 https://www.devze.com 2022-12-08 01:03 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消