iOS9 中弃用了 NSURLConnection

NSURLConnection deprecated in iOS9

我想下载一个带 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 中已被弃用,但这不起作用我希望有人能帮助我

现在你必须使用 NSURLSession

示例(获取):

-(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 调用 return 时执行的块来调用该方法。

[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

So with the use of NSURLSession, you don't need to manage or to check your internet connection because OS does it for you.