【问题标题】:NSURLSessionDelegate connectionDidFinishLoading method does not get calledNSURLSessionDelegate connectionDidFinishLoading 方法没有被调用
【发布时间】:2016-12-14 06:49:05
【问题描述】:

我正在使用NSURLSession 进行 JSON 解析。我正在编写这样的代码,但是当我运行应用程序时没有调用委托方法。即connectionDidFinishLoadingdidReceiveData 方法。如何调用NSURLSessionDelegate方法?

-(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);
}

【问题讨论】:

标签: ios objective-c cocoa-touch nsurlsession


【解决方案1】:
  • 添加这两个委托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]);
    }
    

【讨论】:

    【解决方案2】:

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

    • 创建您自己的会话
    • 在创建会话时指定要用作委托的对象
    • 在该会话中创建任务,而不是在共享会话中。

    【讨论】:

      【解决方案3】:

      您必须在类定义附近编写委托方法; 样品:
      @interface MyControllerClass : UIViewController UIAlertViewDelegate in

      【讨论】:

      • 是的,我是这样写的。但是遇到了同样的问题。
      • 你在h文件中定义了委托吗?
      猜你喜欢
      • 2019-01-02
      • 2012-03-13
      • 1970-01-01
      • 2014-06-02
      • 2011-08-28
      • 2017-02-24
      • 2015-02-23
      • 2013-12-19
      相关资源
      最近更新 更多