Skip to content

Instantly share code, notes, and snippets.

@rodrigo-lima
Created May 8, 2012 01:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigo-lima/2631940 to your computer and use it in GitHub Desktop.
Save rodrigo-lima/2631940 to your computer and use it in GitHub Desktop.
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