-(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/