I am trying to throw a custom exception in one of the delegate methods of NSURLSessionDateTask.
-(void)loginWithEmail:(NSString*)email Password:(NSString*)password
{
@try {
NSURL *Url = [NSURL URLWithString:@"Http://..."];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// preparing the request object
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:@"POST"];
[Request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[Request setHTTPBody:PostData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.TLSMinimumSupportedProtocol = kTLSProtocol11;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:Request];
[dataTask resume];
}
@catch (NSException *exception) {
NSLog(@"%@", [exception description]);
@throw exception;
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSData *response1 = data;
// NSError *requestError = NULL; // captures the returned error (if exists)
// NSURLResponse *urlResponse = NULL; // captures the response returned by the service
NSMutableDictionary *parsedData = NULL; // holds the data after it is parsed
NSError *err = NULL;
if(!response1)
{
// If response is nil, connection timeout.
loginSuccessful = NO;
@throw [NSException exceptionWithName:@"Connection Timeout" reason:@"No Connectivity" userInfo:NULL];
}
else
{
NSString *formattedData = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
if([formattedData rangeOfString:@"<!DOCTYPE"].location != NSNotFound || [formattedData rangeOfString:@"<html"].location != NSNotFound)
{
loginSuccessful = NO;
@throw [NSException exceptionWithName:@"Server Issue" reason:@"Could not connect to server" userInfo:NULL];
}
else
{
parsedData = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingAllowFragments error:&err];
NSMutableDictionary *dict = [parsedData objectForKey:@"User"];
loginSuccessful = YES;
}
}
//handle data here
}
However, when a custom exception is thrown, the catch block in "loginWithEmail" method does not catch the exception, and my application crashes. Where is the exception propagated when it is generated inside a delegate method? How should I handle it?