-(void) conn:(NSString *)method{
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block NSDictionary *resultBlock = nil;
dispatch_sync(concurrentQueue, ^{
/* Download the json here */
//Create webservice address
NSString *webService = [_baseURL stringByAppendingString:_webService];
//NSLog(@"%@", webService);
//Create error object
NSError *downloadError = nil;
//Create the request
NSMutableURLRequest *req = [self initRequest:webService method:method];
if(req != nil){
//Request the json data from the server
NSData *jsonData = [NSURLConnection
sendSynchronousRequest:req
returningResponse:nil
error:&downloadError];
if(downloadError!=nil){
NSLog(@"DOWNLOAD ERROR %@", downloadError);
}
NSError *error = nil;
id jsonObject = nil;
if(jsonData !=nil){
/* Now try to deserialize the JSON object into a dictionary */
jsonObject = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error: &error];
}
//Handel the deserialized object data
if (jsonObject != nil && error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
resultBlock = (NSDictionary *)jsonObject;
//NSLog(@"Deserialized JSON Dictionary = %@", resultBlock);
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Deserialized JSON Array = %@", deserializedArray);
} else {
/* Some other object was returned. We don't know how to deal
with this situation, as the deserializer returns only dictionaries
or arrays */
}
}
else if (error != nil){
NSLog(@"An error happened while deserializing the JSON data. %@", error);
}else{
NSLog(@"No data could get downloaded from the URL.");
//[self conn:method];
}
}
});
dispatch_sync(dispatch_get_main_queue(), ^{
/* Check if the resultBlock is not nil*/
if(resultBlock != nil){
/*Set the value of result. This will notify the observer*/
[self setResult:resultBlock];
}
});
});
}
为什么我会收到以下错误?
反序列化 JSON 数据时发生错误。错误域 = NSCocoaErrorDomain 代码 = 3840 “操作无法完成。(可可错误 3840。)”(JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。) UserInfo = 0x20839f80 {NSDebugDescription = JSON 文本没有以数组或对象和允许未设置片段的选项开头。}
当我将其更改为
/* Now try to deserialize the JSON object into a dictionary */
jsonObject = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error: &error];
}
我收到以下错误:
反序列化 JSON 数据时发生错误。错误域 = NSCocoaErrorDomain 代码 = 3840 “操作无法完成。(可可错误 3840。)”(字符 0 周围的值无效。) UserInfo = 0x20888760 {NSDebugDescription = 字符 0 周围的值无效。}
我将连接从 LTE 更改为 wifi,现在出现 504 错误和 NSLog(@"无法从 URL 下载数据。");