我最近从sendSynchronousRequest切换到dataTaskWithRequest
使用sendSynchronousRequest我的方法工作正常,但当我切换到dataTaskWithRequest时,我收到以下错误:
error NSURLError * domain: @"NSURLErrorDomain" - code: 4294966096 0x15ee96c0
和
myError NSError * domain: nil - code: 1684370017 0x26cce125
我不明白为什么。
这是旧代码(已注释掉)和新代码:
/*-(NSDictionary *)GetProductionScheduleData:(NSString *)areaDescription
{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *requestString = [NSString stringWithFormat:@"%@?areaDescription=%@",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSDictionary *productionSchedule = [[NSDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return productionSchedule;
}*/
-(void)GetProductionScheduleData:(NSString *)areaDescription Completetion:(void (^) (NSMutableDictionary * result,NSError * error))completion{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *requestString = [NSString stringWithFormat:@"%@?areaDescription=%@",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
[dataTask resume];
}
请帮忙!这与sendSynchronousRequest一起工作我开始不喜欢dataTaskWithRequest。
答案 0 :(得分:0)
您拥有的NSURLSession代码是正确的,我使用有效的网址确认。
在尝试JSON解析数据之前,您已停止检查数据是否为nil。如果你加回检查,我打赌你会发现有错误,数据实际上是零。
更改为:
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle request error
if (error) {
completion(nil, error);
return;
}
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
我建议在尝试将myError设置为productionSchedule之前检查myError(这也可能导致崩溃)。