我在使用dataTaskWithRequest时遇到问题,我在调用使用dataTaskWithRequest的方法时尝试填充变量。但它似乎没有填充,因为当我稍后调用此变量时,它的nil
以下是方法:
-(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:@"testunitid" Completetion:^(NSArray *result, NSError *error) {
if([result count] == 0){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Message" message:@"Device is not valid." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}else{
scanner=[DTDevices sharedDevice];
[scanner addDelegate:self];
[scanner connect];
Name = [[result objectAtIndex:0] objectForKey:@"name"];
Name = [Name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Name = [Name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}
}];
我正在尝试填充变量名称当我在任何地方放置断点时我可以看到它被填充,与结果相同,但是当我尝试在此处调用它时:
[self getLocationInfo:Name Completetion:^(NSArray *result, NSError *error) {
if([result count] == 0){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Message" message:@"There is an issue with the location tag." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
ScannerMessage.text = @"READY TO SCAN";
ScannerMessage.backgroundColor = [UIColor greenColor];
}else{
[self performSegueWithIdentifier: @"SegueIdentifier" sender: self];
}
}];
其零
有没有更好的方法来使用dataTaskWithRequest?当我有多个电话时,我发现这种方式有点慢。或者之后是否使用变量Name?我很迷茫。我真的很想念sendSynchronousRequest,我发现它越来越好。
答案 0 :(得分:0)
要避免nil,请确保在if else块中初始化变量:
if([result count] == 0){
Name = @"[result count] == 0";
}else{
//populate names
}
如果[result count] == 0
那么你必须在那个方向进行调试。