如何在NSObject类中编写一个用NSURLConnection解析json url的方法,并在UIViewController中获取返回值?我知道可以通过操作块完成,但不知道确切的方法。
目前我正在使用NSURLSession执行相同的操作,但我希望使用NSURLConnection的相同代码,以下是我当前的代码。
-(void)jsonParseWithPostMethod:(void(^)(NSDictionary* result))handler andString:(NSString*) yourString andParam:(NSString *)param {
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:yourString];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params =param;
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
handler(json) ;
});
}
}];
[dataTask resume];
}
并像这样调用此方法
[[Singelton getInstance] jsonParseWithPostMethod:^(NSDictionary* json){
} andString:urlString andParam:pramString];