Created
May 8, 2012 01:52
-
-
Save rodrigo-lima/2631940 to your computer and use it in GitHub Desktop.
NSURLConnection + Basic Auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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