Skip to content

Instantly share code, notes, and snippets.

@kdbdallas
Created October 7, 2015 18:00
Show Gist options
  • Save kdbdallas/730ec17a1cd37fa65f50 to your computer and use it in GitHub Desktop.
Save kdbdallas/730ec17a1cd37fa65f50 to your computer and use it in GitHub Desktop.
NSURLSession with Basic HTTP Auth
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:LYKAPIUsername password:LYKAPIKey persistence:NSURLCredentialPersistencePermanent];
NSURL *APIURL = [NSURL URLWithString:LYKAPIURLRegister];
NSString *host = [APIURL host];
NSInteger port = [[APIURL port] integerValue];
NSString *protocol = [APIURL scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
[sessionConfiguration setURLCredentialStorage:credentials];
//sessionConfiguration.HTTPAdditionalHeaders = @{@"Authorization": [NSString stringWithFormat:@"Basic %@=%@", LYKAPIUsername, LYKAPIKey]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:LYKAPIURLRegister];
NSString *firstName = [extraData objectForKey:@"first_name"];
NSString *lastName = [extraData objectForKey:@"last_name"];
NSString *facebookID = [extraData objectForKey:@"id"];
NSString *twitterID = [extraData objectForKey:@"twitterID"];
NSString *instagramID = [extraData objectForKey:@"instagramID"];
NSString *dataString = [NSString stringWithFormat:@"email=%@&password=%@&firstName=%@&lastName=%@&facebook_id=%@&twitter_id=%@&instagram_id=%@", email, password, firstName, lastName, facebookID, twitterID, instagramID];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [dataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!data)
{
NSLog(@"error: %@", [error localizedDescription]);
}
else
{
NSLog(@"Data: %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
NSLog(@"Response: %@", response);
NSError *JSONError;
NSDictionary *returnData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&JSONError];
completion(returnData, JSONError);
}
}];
[postDataTask resume];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment