Search code examples
asp.netiosvb.netios6nsurl

iOS: How can I add credentials to my code for my NSURL?


I'm trying to access a page that has xml I'm trying to parse. I'm using the following code which works as long as I do not need credentials. How can I add credentials to this code?

NSURL *url = [[NSURL alloc] initWithString:URLPath];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

[xmlParser setDelegate: self];
success = [xmlParser parse];

Above my "URLPath" is my url string. I've tried using the following url path format but it doesn't work for me. http://username:[email protected]/path/to/file.aspx?Function=Update

Thanks!


Solution

  • Use the NSURLConnectionDelegates

    - (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");
        }
    }
    

    See NSURLConnection and Basic HTTP Authentication in iOS for more information