iOS HTTPS request

August 7, 2015

iOS HTTPS request

When you try to make iOS HTTPS request to a secured web service, you will usually need to provide credentials in order to get proper web service answer for your request. Here is how to make such request.

First of all, you need to configure your session configuration:

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

Afterwards you configure your request:

NSString *requestString = @"URL here";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];

__weak typeof(self)weakSelf = self;
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    __strong typeof(weakSelf)strongSelf = weakSelf;

    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    strongSelf.ourArray = jsonObject[@"your_json_key"];

    NSLog(@"%@", strongSelf.ourArray);

    dispatch_async(dispatch_get_main_queue(), ^{
        [strongSelf.tableView reloadData]; // in case we need to.
    });
}];
[dataTask resume];

Then update the class extension to conform to the NSURLSessionDataDelegate protocol and finally you add the delegate method where you provide your credentials:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
    NSURLCredential *cred = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession];
    completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
}

And there you go, you are all set. In case you want me to show you how to make HTTPS requests with AFNetworking or SDWebImage frameworks - let me know in the comments and I will write tutorials on this matter.

Comments

comments powered by Disqus