Skip to content

Commit

Permalink
Merge pull request #31 from cheekiatng/timob-19154-3
Browse files Browse the repository at this point in the history
[TIMOB-19154] Deprecate NSURLConnection and replace with NSURLSession
  • Loading branch information
hansemannn committed Sep 27, 2015
2 parents 6cf0b26 + b0259ae commit 38d0c6c
Showing 1 changed file with 94 additions and 66 deletions.
160 changes: 94 additions & 66 deletions APSHTTPClient/APSHTTPRequest.m
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ typedef NS_ENUM(NSInteger, APSHTTPCallbackState) {
APSHTTPCallbackStateRedirect = 5
};

@interface APSHTTPRequest () <NSURLConnectionDataDelegate,NSURLSessionDataDelegate>
@interface APSHTTPRequest () <NSURLConnectionDataDelegate,NSURLSessionDataDelegate, NSURLSessionTaskDelegate, NSURLSessionDelegate>

@property(nonatomic, strong, readwrite ) NSMutableURLRequest *request;
@property(nonatomic, assign, readwrite) long long expectedDownloadResponseLength;
Expand Down Expand Up @@ -50,7 +50,7 @@ - (id)init
-(void)abort
{
self.cancelled = YES;
/* if ([self isIOS7OrGreater]) {
if ([self isIOS7OrGreater]) {
if (self.session != nil) {
[self.session invalidateAndCancel];
[self URLSession:self.session didBecomeInvalidWithError:
Expand All @@ -60,7 +60,7 @@ -(void)abort
];
}
return;
}*/
}
if(self.connection != nil) {
[self.connection cancel];
[self connection:self.connection didFailWithError:
Expand Down Expand Up @@ -136,41 +136,41 @@ -(void)send
NSURLResponse *response;
NSError *error = nil;
NSData *responseData = nil;
/* if ([self isIOS7OrGreater]) {
if ([self isIOS7OrGreater]) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
self.session = [NSURLSession sharedSession];
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:self.theQueue];
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {
[self.response appendData:data];
[self.response updateResponseParamaters:response];
[self.response setError:error];
[self.response updateRequestParamaters:self.request];
[self.response setReadyState:APSHTTPResponseStateDone];
[self.response setConnected:NO];
dispatch_semaphore_signal(semaphore);
}];
[self.response appendData:data];
[self.response updateResponseParamaters:response];
[self.response setError:error];
[self.response updateRequestParamaters:self.request];
[self.response setReadyState:APSHTTPResponseStateDone];
[self.response setConnected:NO];
dispatch_semaphore_signal(semaphore);
}];
[task resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
else {*/
else {
responseData = [NSURLConnection sendSynchronousRequest:self.request returningResponse:&response error:&error];
[self.response appendData:responseData];
[self.response updateResponseParamaters:response];
[self.response setError:error];
[self.response updateRequestParamaters:self.request];
[self.response setReadyState:APSHTTPResponseStateDone];
[self.response setConnected:NO];
// }
}
} else {
[self.response updateRequestParamaters:self.request];
[self.response setReadyState:APSHTTPResponseStateOpened];
[self invokeCallbackWithState:APSHTTPCallbackStateReadyState];

/* if ([self isIOS7OrGreater]) {
self.session = [NSURLSession sharedSession];
if ([self isIOS7OrGreater]) {
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.request];
[task resume];
return;
}*/
}
self.connection = [[NSURLConnection alloc] initWithRequest: self.request
delegate: self
startImmediately: NO
Expand Down Expand Up @@ -311,42 +311,57 @@ -(void)connection:(NSURLConnection *)connection willSendRequestForAuthentication
}
}

-(void)URLSession:(nonnull NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * __nullable))completionHandler
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
DebugLog(@"%s", __PRETTY_FUNCTION__);

BOOL useSubDelegate = (self.connectionDelegate != nil && [self.connectionDelegate respondsToSelector:@selector(URLSession:task:didReceiveChallenge:completionHandler:)]);
if (challenge.previousFailureCount) {
[challenge.sender cancelAuthenticationChallenge:challenge];
}

if(useSubDelegate) {
@try {
[self.connectionDelegate URLSession:session didReceiveChallenge:challenge completionHandler:completionHandler];
NSString* authMethod = challenge.protectionSpace.authenticationMethod;
BOOL handled = NO;
if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ( ([challenge.protectionSpace.host isEqualToString:self.url.host]) && (!self.validatesSecureCertificate) ){
handled = YES;
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
//NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, credential);
}
@catch (NSException *exception) {
if (self.session != nil) {
[self.session invalidateAndCancel];

NSMutableDictionary *dictionary = nil;
if (exception.userInfo) {
dictionary = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
} else {
dictionary = [NSMutableDictionary dictionary];
}
if (exception.reason != nil) {
[dictionary setObject:exception.reason forKey:NSLocalizedDescriptionKey];
}

NSError* error = [NSError errorWithDomain:@"APSHTTPErrorDomain"
code:APSRequestErrorConnectionDelegateFailed
userInfo:dictionary];
[self URLSession:self.session didBecomeInvalidWithError:error];
}
} else if ( [authMethod isEqualToString:NSURLAuthenticationMethodDefault] || [authMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
|| [authMethod isEqualToString:NSURLAuthenticationMethodNTLM] || [authMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
if(self.requestPassword != nil && self.requestUsername != nil) {
handled = YES;
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.requestUsername
password:self.requestPassword
persistence:NSURLCredentialPersistenceForSession];

[challenge.sender useCredential: credential forAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, credential);
}
@finally {
//Do nothing
}

if (!handled) {
if ([challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) {
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
completionHandler(disposition, nil);
} else {
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, nil);
}
return;
}

}

-(void)URLSession:(nonnull NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * __nullable))completionHandler
{
DebugLog(@"%s", __PRETTY_FUNCTION__);

if (challenge.previousFailureCount) {
[challenge.sender cancelAuthenticationChallenge:challenge];
}
Expand All @@ -356,30 +371,39 @@ -(void)URLSession:(nonnull NSURLSession *)session didReceiveChallenge:(nonnull N
if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ( ([challenge.protectionSpace.host isEqualToString:self.url.host]) && (!self.validatesSecureCertificate) ){
handled = YES;
[challenge.sender useCredential:
[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
//NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, credential);
}
} else if ( [authMethod isEqualToString:NSURLAuthenticationMethodDefault] || [authMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
|| [authMethod isEqualToString:NSURLAuthenticationMethodNTLM] || [authMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
if(self.requestPassword != nil && self.requestUsername != nil) {
handled = YES;
[challenge.sender useCredential:
[NSURLCredential credentialWithUser:self.requestUsername
password:self.requestPassword
persistence:NSURLCredentialPersistenceForSession]
forAuthenticationChallenge:challenge];
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.requestUsername
password:self.requestPassword
persistence:NSURLCredentialPersistenceForSession];

[challenge.sender useCredential: credential forAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, credential);
}
}

if (!handled) {
if ([challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) {
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
completionHandler(disposition, nil);
} else {
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeUseCredential;
completionHandler(disposition, nil);
}
}
}

-(NSURLRequest*)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
DebugLog(@"Code %li Redirecting from: %@ to: %@",(long)[(NSHTTPURLResponse*)response statusCode], [self.request URL] ,[request URL]);
Expand All @@ -406,16 +430,21 @@ -(void)URLSession:(nonnull NSURLSession *)session task:(nonnull NSURLSessionTask
DebugLog(@"Code %li Redirecting from: %@ to: %@",(long)[(NSHTTPURLResponse*)response statusCode], [self.request URL] ,[request URL]);
self.response.connected = YES;
[self.response updateResponseParamaters:response];
if (!self.redirects && self.response.status != 0) {
completionHandler(nil);
return;
}
[self.response updateRequestParamaters:request];
[self invokeCallbackWithState:APSHTTPCallbackStateRedirect];
// if (response) {
// NSMutableURLRequest *r = [self.request mutableCopy];
// r.URL = request.URL;
// self.request = r;
// } else {
// self.request = [request mutableCopy];
// }
if (response) {
NSMutableURLRequest *r = [self.request mutableCopy];
r.URL = request.URL;
self.request = r;
} else {
self.request = [request mutableCopy];
}
completionHandler(self.request);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
DebugLog(@"%s", __PRETTY_FUNCTION__);
Expand Down Expand Up @@ -447,11 +476,13 @@ - (void) URLSession:(nonnull NSURLSession *)session dataTask:(nonnull NSURLSessi
[NSError errorWithDomain:self.response.location
code:self.response.status
userInfo:@{NSLocalizedDescriptionKey: [NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]}
]];
]];
return;
}
self.expectedDownloadResponseLength = response.expectedContentLength;
[self invokeCallbackWithState:APSHTTPCallbackStateReadyState];
NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
completionHandler(disposition);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
Expand Down Expand Up @@ -565,17 +596,14 @@ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)err

- (void)URLSession:(nonnull NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
{
if(self.connectionDelegate != nil && [self.connectionDelegate respondsToSelector:@selector(URLSession:didBecomeInvalidWithError:)]) {
[self.connectionDelegate URLSession:session didBecomeInvalidWithError:error];
}
DebugLog(@"%s", __PRETTY_FUNCTION__);
self.response.readyState = APSHTTPResponseStateDone;
[self invokeCallbackWithState:APSHTTPCallbackStateReadyState];

self.response.connected = NO;
self.response.error = error;
[self invokeCallbackWithState:APSHTTPCallbackStateError];

}

-(void)invokeCallbackWithState:(APSHTTPCallbackState)state
Expand Down

0 comments on commit 38d0c6c

Please sign in to comment.