这是我的工作代码NSURLConnection sendSynchronousRequest
:
+ (Inc*)getData:(NSString*)inUUID {
NSString* urlString = [NSString stringWithFormat:@"/inc/%@", incUUID];
NSURLRequest* request = [[HttpRequest requestWithRelativePath:urlString] toNSMutableURLRequest];
NSDictionary* json = [self getJSONForRequest:request];
return [Inc incFromDictionary:json];
}
+ (NSDictionary*)getJSONForRequest:(NSURLRequest*)request {
NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
return [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
}
但是,sendSynchronousRequest:request
已弃用。
所以,我用NSURLSessionDataTask
而不是sendSynchronousRequest
. 这是我实现的代码:
+ (Inc*)getData1:(NSString*)inUUID {
NSString* urlString = [NSString stringWithFormat:@"/in/%@", inUUID];
NSURLRequest* request = [[HttpRequest requestWithRelativePath:urlString] toNSMutableURLRequest];
//NSDictionary* json = [self getJSONForRequest1:request];
__block NSDictionary* json;
dispatch_async(dispatch_get_main_queue(), ^{
[self getJsonResponse1:request success:^(NSDictionary *responseDict) {
json = [responseDict valueForKeyPath:@"detail"];;
//return [Inc incFromDictionary:json];
} failure:^(NSError *error) {
// error handling here ...
}];
});
return [Inc incFromDictionary:json];
}
+ (void)getJsonResponse1:(NSURLRequest *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
NSURLSessionDataTask *dataTask1 = [[NSURLSession sharedSession] dataTaskWithRequest:urlStr completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(@"%@",data);
if (error)
failure(error);
else {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",json);
success(json);
}
}];
[dataTask1 resume]; // Executed First
}
getData1
问题是在完成 api 调用之前 调用 return 语句。
提前致谢。