Objective-C - 'sendSynchronousRequest:returningResponse:error:'已被弃用:自iOS 9.0起首次弃用。

3
-(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个回答

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

请注意,此方法是异步的。


我尝试这样调用它 `[self deviceCheck:[[UIDevice currentDevice] name] Completetion:^(NSArray *result, NSError *error) { if(error == nil){ NSLog(@"Here"); }else{ NSLog(@"Here 2"); } }];` 但是没有起作用。 - Magna Boss

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接