【问题标题】:NSURLConnection deprecated in iOS9iOS9 中不推荐使用 NSURLConnection
【发布时间】:2015-12-03 03:51:16
【问题描述】:

我想下载一个带有NSURLRequest 的文件并保存它,但要符合

NSData * data = ... 发生错误。

NSURL *Urlstring = [NSURL URLWithString:@"http://yourdomain.com/yourfile.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL: Urlstring];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
documentsURL = [documentsURL URLByAppendingPathComponent:@"localFile.pdf"];

[data writeToURL:documentsURL atomically:YES];

警告消息是我应该使用NSURLSession dataTaskwithrequest"因为sendSynchronousRequest 在iOS 9 中已被弃用,但这不起作用我希望有人可以帮助我

【问题讨论】:

  • “已弃用”不是错误。这是一个警告,表明将来某些事情会消失。如果您有实际错误,可能是由于不同的原因。

标签: ios nsurlconnection nsurlsession ios9


【解决方案1】:

现在你必须使用NSURLSession

示例 (GET):

-(void)placeGetRequest:(NSString *)action withHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))ourBlock {

    NSString *urlString = [NSString stringWithFormat:@"%@/%@", URL_API, action];


    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
}

现在您需要使用一个操作(或您的完整 URL,如果您愿意)调用该方法,并在 API 调用返回时执行该块。

[self placeGetRequest:@"action" withHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // your code
}];

在该块内,您将收到带有响应数据的 NSData 和带有 HTTP 响应的 NSURLResponse。所以现在,你可以把你的代码放在那里:

NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
documentsURL = [documentsURL URLByAppendingPathComponent:@"localFile.pdf"];

[data writeToURL:documentsURL atomically:YES];

NSURLSession 和 NSURLConnection 的主要区别

  • NSURLConnection:如果我们与 NSURLConnection 有一个打开的连接并且系统中断了我们的应用程序,当我们的应用程序进入后台模式时,我们接收或发送的所有内容都会丢失。

  • NSURLSession:解决这个问题,也给我们进程外的下载。即使我们无权访问,它也会管理连接过程。您需要在 AppDelegate 中使用 application:handleEventsForBackgroundURLSession:completionHandler

所以使用 NSURLSession,你不需要管理或检查 您的互联网连接,因为操作系统会为您完成。

【讨论】:

  • 好的,谢谢,但是我们的块是什么,它说未声明的标识符
  • 哦,是的! ourBlock 是您必须定义的块。它应该包括您要在 api 调用完成时执行的源代码。我将编辑我的答案给你完整的例子
  • @Maximilian,现在检查我更新的答案并在你的项目中测试它
  • @EnriMR,看起来dataTaskWithRequest 缺少resume,不是吗? [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
  • 是的,缺少简历。没有它,执行似乎永远不会进入 ourBlock。
猜你喜欢
  • 2015-08-25
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 2012-11-14
  • 2019-05-13
  • 1970-01-01
相关资源
最近更新 更多