iOS9中不推荐使用NSURLConnection

时间:2015-09-07 14:41:41

标签: ios nsurlconnection nsurlsession 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"因为{9}在iOS 9中已被弃用但是我不希望有人可以帮助我

1 个答案:

答案 0 :(得分:33)

现在你必须使用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打开连接并且系统中断我们的应用程序,当我们的应用程序进入后台模式时,我们收到或发送的所有内容都将丢失。 Process diagram for NSURLConnection

  • NSURLSession:解决了这个问题,也让我们没有进程下载。即使我们无法访问,它也会管理连接过程。您需要在AppDelegate中使用application:handleEventsForBackgroundURLSession:completionHandler Process diagram for NSURLSession

  

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

相关问题