Skip to content

Instantly share code, notes, and snippets.

@CoryFoy
Created February 2, 2015 00:17
Show Gist options
  • Save CoryFoy/3f77bcada9d6b9824ae2 to your computer and use it in GitHub Desktop.
Save CoryFoy/3f77bcada9d6b9824ae2 to your computer and use it in GitHub Desktop.

Revisions

  1. CoryFoy created this gist Feb 2, 2015.
    50 changes: 50 additions & 0 deletions gistfile1.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    @implementation ViewController

    // NSURLConnection Delegates
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
    NSLog(@"received authentication challenge");
    NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
    password:@"PASSWORD"
    persistence:NSURLCredentialPersistenceForSession];
    NSLog(@"credential created");
    [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    NSLog(@"responded to authentication challenge");
    }
    else {
    NSLog(@"previous authentication failure");
    }
    }

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData");
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    }

    - (void)viewDidLoad {
    [super viewDidLoad];

    NSString *username = @"hello";
    NSString *password = @"world";

    NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authenticationValue = [authenticationData base64Encoding];

    // Setup NSURLConnection
    NSURL *URL = [NSURL URLWithString:@"http://localhost:3000"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    [request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    }

    @end