NSURLSessionDelegate connectionDidFinishLoading方法不会被调用
问题描述:
我正在使用NSURLSession
进行JSON解析。我正在编写这样的代码,但是当我运行应用程序时,不会调用委托方法。即connectionDidFinishLoading
和didReceiveData
方法。如何调用NSURLSessionDelegate
方法?NSURLSessionDelegate connectionDidFinishLoading方法不会被调用
-(void)viewDidLoad {
[super viewDidLoad];
menuArr = [[NSMutableArray alloc]init];
self.view.backgroundColor = [UIColor whiteColor];
NSURL *url =[NSURL URLWithString:@"http://url"];
dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
{
if(error == nil)
{
NSError *JSONError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError];
NSLog(@"Dictionary is:%@",dictionary);
}
}];
[dataTask resume];
}
#pragma mark - NSURLSession delegate methods
- (BOOL)URLSession:(NSURLSession *)session dataTask:(NSURLSessionTask *)dataTask canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace
{
BOOL isvalue = [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
return isvalue;
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,NSURLCredential *credential))completionHandler
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse
{
receivedData = [[NSMutableData alloc]init];
[receivedData setLength:0];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionTask *)dataTask connectionDidFinishLoading:(NSURLConnection *)conn
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSString *str=[dict objectForKey:@"Status"];
NSLog(@"Status Response is:%@",str);
NSDictionary *jsonDict = [dict valueForKey:@"data"];
NSLog(@"Json Dictionary is:%@",jsonDict);
menuArr = [jsonDict valueForKey:@"Text"];
NSLog(@"Item Name is:%@",menuArr);
}
答
您使用的共享会话。这是一个没有委托的预先存在的会话。如果你希望你的任务调用委托方法,你必须:
- 创建您自己的会话
- 指定要当你创建一个会话
- 创建内的任务,作为委托使用对象会话,而不是共享会话。
答
-
添加这两种代表NSURLSessionDelegate,NSURLSessionDataDelegate
-(void)viewDidLoad { [super viewDidLoad]; [self sendHTTPPost]; } -(void) sendHTTPPost { NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]]; NSURL * url = [NSURL URLWithString:@"http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo"]; NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"POST"]; NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest]; [dataTask resume]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { NSLog(@"### handler 1"); completionHandler(NSURLSessionResponseAllow); } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSError *error; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSLog(@" dict=>> %@",dict); } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if(error == nil) { NSLog(@"Download is Succesfull"); } else NSLog(@"Error %@",[error userInfo]); }
添加一个格式化代码,这样每个人都可以阅读你的代码 – Rajat
http://stackoverflow.com/ a/39203067/3400991可能重复 –