Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
NSURLConnection + Basic Auth
@implementation WhateverClass
+ (NSString *)getBasicAuth
NSData *encodeData = [[NSString stringWithFormat:@"%@:%@", username, password]
// 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
[URLConnection scheduleInRunLoop:defaultRunLoop
[URLConnection start];
@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;
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.