将代码从NSURLConnection迁移到NSURLSession

时间:2018-01-18 09:16:54

标签: ios objective-c nsurlconnection nsurlsession xcode9.2

我的项目中有以下方法和NSURLConnection委托,目前用于所有请求并且工作正常。现在我正在尝试将其迁移到NSURLSession但有问题。以下是代码

使用NSURLConnection的原始代码

-(void)startAsynchronousRequestWithoutTLSHandshakeWithComplitionHandler:(MyCompletitionBlock)complitionBlock  {
    if (self.postData != nil) {
        [self injectChallengeBytesIfNeeded:self.postData];
    }

    [NSURLConnection sendAsynchronousRequest:[self createRequest] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        complitionBlock(response,data,connectionError);
    }];
}


-(void)startAsynchronousRequestWithoutTLSHandshake {
    if (self.postData != nil) {
        [self injectChallengeBytesIfNeeded:self.postData];
    }

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:[self createRequest] delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [receivedData appendData:data];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveError:)]) {
        [delegate myWebServiceManager:self didRecieveError:error];
    }
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received

    LogInfo(@"Response: %@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);

    if ([self checkChallengeBytesIfNeeded:receivedData]) {
        if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveData:)]) {
            [delegate myWebServiceManager:self didRecieveData:receivedData];
        }
    }
    else {
        NSError *error = [NSError errorWithDomain:@"Server Error" code:-1 userInfo:@{@"Error":@"Security Failure"}];
        if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveError:)]) {
            [delegate myWebServiceManager:self didRecieveError:error];
        }
    }
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *cred = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
    }
    else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
}

以下是我尝试迁移到NSURLSession

的那个
-(void)startAsynchronousRequestWithoutTLSHandshakeWithComplitionHandler:(MyCompletitionBlock)complitionBlock  {

    [self createSession];

    if (self.postData != nil) {
        [self injectChallengeBytesIfNeeded:self.postData];
    }

    NSURLSessionDataTask *task = [session dataTaskWithRequest:[self createRequest]
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *connectionError) {
                                      complitionBlock(response,data,connectionError);
                                  }];

    [task resume];

}


-(void)startAsynchronousRequestWithoutTLSHandshake {

    [self createSession];

    if (self.postData != nil) {
        [self injectChallengeBytesIfNeeded:self.postData];
    }

    NSURLSessionDataTask *task = [session dataTaskWithRequest:[self createRequest]];

    [task resume];
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    receivedData = [[NSMutableData alloc] init];
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error)
    {
        if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveError:)]) {
            [delegate myWebServiceManager:self didRecieveError:error];
        }
    }
    else
    {
        // The request is complete and data has been received

        LogInfo(@"Response: %@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);

        if ([self checkChallengeBytesIfNeeded:receivedData]) {
            if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveData:)]) {
                [delegate myWebServiceManager:self didRecieveData:receivedData];
            }
        }
        else {
            NSError *error = [NSError errorWithDomain:@"Server Error" code:-1 userInfo:@{@"Error":@"Security Failure"}];
            if ([delegate respondsToSelector:@selector(myWebServiceManager:didRecieveError:)]) {
                [delegate myWebServiceManager:self didRecieveError:error];
            }
        }
    }
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse * _Nullable))completionHandler
{
    // Return nil 

}


-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *cred = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
    }
    else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
}

现在问题是NSURLSession似乎没有调用它的委托,不知道我需要修改什么。任何帮助表示赞赏

0 个答案:

没有答案