Magna Boss Magna Boss - 6 months ago 231
iOS Question

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

Leo Leo
Answer

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

Comments