Switch from NSURLConnection to NSURLSession in Objective-C

I have this code in Objective-C that works with a class initWithRequestclass NSURLConnection, and Xcode gives me the following warning:

initWithRequest deprecated: deprecated first in iOS9 - use NSURLSession

My ViewController.mcode is as follows:

NSString url = "my url"; 
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
conexion = [[NSURLConnection alloc]initWithRequest:req delegate:self];

Conexion NSURLConnectionin ViewController.h, so I was wondering how to switch from NSURLConnectionto NSURLSession.

+4
source share
3 answers

If you want to continue to use the delegate-based API, for example your current implementation, this is:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURL *URL = [NSURL URLWithString:string];

NSURLSessionTask *task = [session dataTaskWithURL:URL];
[task resume];

, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLConnectionDataDelegate NSURLConnectionDelegate.

, dataTaskWithURL , NSURLRequest (, POST ), dataTaskWithRequest.

, , :

NSURLSession *session = [NSURLSession sharedSession];

NSURL *URL = [NSURL URLWithString:string];

NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // process response here
}];
[task resume];

, - . NSURLConnection sendAsynchronousRequest, , .

, dataTaskWithURL, , downloadTaskWithURL uploadTaskWithRequest.

. NSURLSession URL-.

+5
    NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {
                                  // ...
                              }];

[task resume];
+1

, , - API . NSURLSession iOS 7 , OS X 10.9 . - , , NSURLConnection.

, NSURLConnection, , , - , Apple tvOS, .

To be rude honest, if you have no particular reason to use the new functions in NSURLSession, the best way is probably to use pragmas to disable the compiler warning for this bit of code and use NSURLSession for new code (if you should not be compatible with more older operating systems that do not support NSURLSession).

0
source

Source: https://habr.com/ru/post/1617158/


All Articles