2016-12-14 116 views
1

我正在使用NSURLSession进行JSON解析。我正在编写这样的代码,但是当我运行应用程序时,不会调用委托方法。即connectionDidFinishLoadingdidReceiveData方法。如何调用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); 
} 
+0

添加一个格式化代码,这样每个人都可以阅读你的代码 – Rajat

+0

http://stackoverflow.com/ a/39203067/3400991可能重复 –

回答

-1

你必须写下附近的类定义的委托方法; 样品:
@interface MyControllerClass:UIViewController中UIAlertViewDelegate在<>

+0

是的,我正在写这样的..但得到同样的问题。 – Surya

+0

您是否在h文件中定义委托? –

+0

是的,我在.h文件中定义 – Surya

0

您使用的共享会话。这是一个没有委托的预先存在的会话。如果你希望你的任务调用委托方法,你必须:

  • 创建您自己的会话
  • 指定要当你创建一个会话
  • 创建内的任务,作为委托使用对象会话,而不是共享会话。
0
  • 添加这两种代表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]); 
    }