如何使用目标C在iOS上本地下载和保存文件?

bog*_*dan 41 wget objective-c download local-storage ios

我是Objective-C的新手,我想从网上下载一个文件(如果在网络服务器上进行了更改)并将其保存在本地,以便我的应用程序可以使用它.

主要是我想实现什么wget --timestamp <url>.

Hen*_*ing 147

我不确定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];
}
Run Code Online (Sandbox Code Playgroud)

  • @schystz如果阻止你意味着同步,那么是的. (6认同)
  • 只是想知道,这是阻止与否?我会假设这一块. (3认同)

ban*_*isa 15

iOS 7中引入的NSURLSession是推荐的下载文件的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];
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用NSURLSessionDownloadDelegate委托方法来监视错误,下载完成,下载进度等...如果您愿意,也可以使用内联块完成处理程序回调方法.苹果文档说明何时需要使用其中一个.

阅读这些文章:

objc.io NSURLConnection to NSURLSession

URL加载系统编程指南


Tib*_*abo 14

我将使用完成块使用异步访问.

此示例将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);
    }
}];
Run Code Online (Sandbox Code Playgroud)


pix*_*eak 6

我认为更简单的方法是使用ASIHTTPRequest.三行代码可以实现这一目标:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
Run Code Online (Sandbox Code Playgroud)

链接到参考

更新:我应该提到不再维护ASIHTTPRequest.作者特别建议人们使用其他框架,如AFNetworking