Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NSURLConnection + Basic Auth
@implementation WhateverClass
+ (NSString *)getBasicAuth
{
NSData *encodeData = [[NSString stringWithFormat:@"%@:%@", username, password]
dataUsingEncoding:NSUTF8StringEncoding];
// from NSData+Base64.m by Matt Gallagher
NSString *credentials = [encodeData base64EncodedString];
NSString *header = [NSString stringWithFormat:@"Basic %@", credentials];
return header;
}
- (void)someConnectionMethod
{
NSRunLoop *defaultRunLoop = [NSRunLoop currentRunLoop];
NSString *defaultMode = NSDefaultRunLoopMode;
URLConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
[URLConnection scheduleInRunLoop:defaultRunLoop
forMode:defaultMode];
[URLConnection start];
}
@end
@implementation WhateverClass (NSURLConnectionDelegate)
#pragma mark - NSURLConnectionDelegate
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response
{
NSMutableURLRequest *updatedRequest = [[request mutableCopy] autorelease];
[updatedRequest setValue:[self getBasicAuth] forHTTPHeaderField:@"Authorization"];
BOOL isRedirect = !!response;
if (isRedirect) {
// reset the responseData to clear it between redirect requests
}
return updatedRequest;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.