16

I am adopting the Gmail API in iOS and I am getting the warning:

initWithRequest is deprecated

in the following line:

connection_ = [[connectionClass alloc] initWithRequest:request_ delegate:self startImmediately:NO];

The line is in the source file GTMHTTPFetcher.m of the API library.

What is the substitute for the deprecated -initWithRequest: method?

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
Aditya Borde
  • 1,227
  • 2
  • 12
  • 31
  • Doesn't the error mention the replacement? What do the official docs (class reference) for `NSURLConnection` say? – Nicolas Miari Sep 18 '15 at 08:24
  • The error is as follows: google-api-objective-client/Source/HTTPFetcher/GTMHTTPFetcher.m:459:46: 'initWithRequest:delegate:startImmediately:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSession (see NSURLSession.h) and the official docs have not mentioned anything about what to use instead of initWithRequest @NicolasMiari – Aditya Borde Sep 18 '15 at 08:28
  • I see... (slightly) Bad news, then. see my answer. – Nicolas Miari Sep 18 '15 at 08:36
  • Please flag correct answer! Thx – Raphael Feb 25 '16 at 07:33

3 Answers3

41

NSURLConnection is deprecated in iOS 9. You can use NSURLSession instead which exists since iOS 7.

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
        {
            // do something with the data 
        }];
[dataTask resume];
Raphael
  • 3,846
  • 1
  • 28
  • 28
7

If you don't care about the completionHandler : here's an one liner.

[[[NSURLSession sharedSession] dataTaskWithRequest:request] resume];
Randel S
  • 362
  • 4
  • 9
5

It seems that the whole NSURLConnection API has been deprecated in iOS 9. Existing apps will continue to work, but new builds (linked against iOS SDK) must use the newer NSURLSession API.

Ray Wenderlich has a good tutorial here. Also, of course, check the official documentation.

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189