Objective-C - 'sendSynchronousRequest:returningResponse:error:'已弃用:首先在iOS 9.0中弃用

时间:2015-09-27 02:19:38

标签: ios objective-c

-(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;
    }

但我一直收到这个警告:

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

在这一行:

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

我尝试更改为以下内容:

NSData* data = [NSURLSession dataTaskWithRequest:request];

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

两个都给我错误说:

没有已知的类方法

请帮助

2 个答案:

答案 0 :(得分:4)

使用NSURLSession,您的代码可能会喜欢这个

-(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];
}

然后当你使用它时

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

注意,此方法是异步

答案 1 :(得分:0)

如果你真的需要同步请求(你可能不应该这样做),你可以使用:

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