NSURLSession + server with self signed cert

前端 未结 2 660
南旧
南旧 2020-12-23 20:30

I have an app that is production along with a development server that has a self signed certificate.

I am attempting to test NSURLSession

2条回答
  •  既然无缘
    2020-12-23 21:18

    For me your first example is working fine. I have tested with the following code without problems (it is of course very insecure since it allows any server certificate).

    @implementation SessionTest
    
    - (void) startSession
    {
        NSURL *url = [NSURL URLWithString:@"https://self-signed.server.url"];
    
        NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
    
        NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url
                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                        if(error == nil)
                                                        {
                                                            NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                            NSLog(@"Data: %@",text);
                                                        }
                                                        else
                                                        {
                                                            NSLog(@"Error: %@", error);
                                                        }
                                                    }];
    
        [dataTask resume];
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
    {
        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
    }
    
    @end
    

    Update: This is the class interface, the SessionTest class is the NSURLSessionDataDelegate, to start the data download you create a SessionTest object and call the startSession method.

    @interface SessionTest : NSObject 
    
    - (void) startSession;
    
    @end
    

提交回复
热议问题