ios - Objective-C - 'sendSynchronousRequest:returningResponse:error:' 已弃用 : first deprecated in iOS 9. 0

标签 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];

都给了我错误说:

没有已知的类方法

请帮忙

最佳答案

有了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
}];

注意,这个方法是异步的

关于ios - Objective-C - 'sendSynchronousRequest:returningResponse:error:' 已弃用 : first deprecated in iOS 9. 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803922/

相关文章:

iOS 11 共享扩展被破坏

python - 从 iOS 切换 python bool 值

ios - UITableViewCell 上的 AutoLayout 问题

iphone - 在实例变量自动释放的控制台 (po) 中打印值

ios - 使用 Restkit 0.20 映射此类不符合 key 的键值编码

objective-c - 目前是否有适用于 iOS4 和 Xcode4 的 BDD 解决方案?

objective-c - 错误 : hex escape sequence out of range

c# - 如何在 MonoTouch 上将指定图像添加到用户的相机胶卷相册

ios - 如何防止 SKSpriteNode 的子节点与其父节点一起旋转?

ios - 如何使用 xib 文件正确创建自定义单元格、注册并加载它?