我是Objective-C的新手,我想从网上下载一个文件(如果它已在网络服务器上更改)并将其保存在本地,以便我的应用程序可以使用它。如何使用目标C在iOS上本地下载和保存文件?
主要我想实现什么wget --timestamp <url>
。
我是Objective-C的新手,我想从网上下载一个文件(如果它已在网络服务器上更改)并将其保存在本地,以便我的应用程序可以使用它。如何使用目标C在iOS上本地下载和保存文件?
主要我想实现什么wget --timestamp <url>
。
我不知道什么是wget的,但要获得从Web文件并将其存储在本地,你可以使用NSData的:
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
我想更简单的方法是使用ASIHTTPRequest。三行代码可以做到这一点:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
更新:我应该指出,ASIHTTPRequest不再维持。作者特别建议人们改用其他框架,比如AFNetworking
我将使用结束块使用异步访问。
本示例将Google徽标保存到设备的文档目录中。 (iOS 5以上,OSX 10.7+)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
NSURLSession在IOS 7引入,是下载文件的推荐的SDK方式。无需导入第三方库。
NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];
然后,您可以使用NSURLSessionDownloadDelegate委托方法来监视错误,请下载完成,下载进度等等......有内嵌块完成处理程序回调方法太多,如果你喜欢。苹果文档解释您何时需要使用另一个。
有这些文章的读:
这是否异步工作 – 2016-04-06 05:24:17
Network API不能异步工作会很奇怪。所以是的,NSURLSession API是高度异步的:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html – bandejapaisa 2016-05-12 16:07:42
处理委托部分很烦人。 – 2017-11-01 02:14:53
只是想知道,这是阻塞或不?我会假设这个块。 – schystz 2013-02-08 15:34:28
@schystz如果通过阻止你的意思是同步的,那么是的。 – carlossless 2013-02-19 13:45:53
同样,也有人可能对'+ [NSString stringWithContentsOfURL:encoding:error:]' – Zmaster 2013-10-20 13:17:08