Magna Boss
Magna Boss

Reputation: 289

Objective-C - 'sendSynchronousRequest:returningResponse:error:' is deprecated: first deprecated in iOS 9.0

-(NSArray *)deviceCheck:(NSString *)device
    {
        NSString *deviceRequestString = [NSString stringWithFormat:@"%@?device=%@",webservice,device];
        NSURL *JSONURL = [NSURL URLWithString:deviceRequestString];
        NSURLResponse* response = nil;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];

        NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        if(data == nil)
            return nil;
        NSError *myError;
        NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
        return tableArray;
    }

but I keep getting this warning:

sendSynchronousRequest:returningResponse:error:' is deprecated: first deprecated in iOS 9.0 - Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h

on this line:

NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

I tried changing to to the following:

NSData* data = [NSURLSession dataTaskWithRequest:request];

and

NSData* data = [NSURLSession dataTaskWithRequest:request returningResponse:&response error:nil];

both gave me errors saying:

No known class method

PLEASE HELP

Upvotes: 3

Views: 4798

Answers (2)

Leo
Leo

Reputation: 24714

With NSURLSession,your code may like this

-(void)deviceCheck:(NSString *)device Completetion:(void (^) (NSArray * result,NSError * error))completion{
NSString *deviceRequestString = [NSString stringWithFormat:@"%@?device=%@",webservice,device];
NSURL *JSONURL = [NSURL URLWithString:deviceRequestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSessionDataTask * dataTask = [
      [NSURLSession sharedSession]
      dataTaskWithRequest:request
      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          if(data == nil) {
              completion(nil,error);
              return;
          }
          NSError *myError;
          NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
          completion(tableArray,myError);
      }
];
[dataTask resume];
}

Then when you use it

[self deviceCheck:@"123" Completetion:^(NSArray *result, NSError *error) {
   //Here use result,and check the error
}];

Note,this method is async

Upvotes: 4

Yedidya Reiss
Yedidya Reiss

Reputation: 5326

If you really need synch request (and you probably shouldn't have that), you can use :

+ (instancetype)dataWithContentsOfURL:(NSURL *)aURL
                          options:(NSDataReadingOptions)mask
                            error:(NSError * _Nullable *)errorPtr

Upvotes: 0

Related Questions