Reputation: 198
Currently I am loading an image from URL in my iPhone app, which is working fine. But now i want to access a protected URL. Please guide me with a piece of code that how can i access URL with credentials(username/password).
The simple code through which my app loaded the image from URL is given Below
NSURL *url = [NSURL URLWithString: @"http://www.somedirectory.com"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[Pic setImage:image];
Upvotes: 0
Views: 2227
Reputation: 1062
Look For these two callbacks
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
// IF to handle NTLM authentication.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodNTLM])
return YES;
// Mostly sent by IIS.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
return YES;
return NO;
}
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodNTLM])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodServerTrust])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else
{
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
Upvotes: 1
Reputation: 15213
You can use some third party library like ASIHTTPRequest, which makes it very easy.
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:@"username"];
[request setPassword:@"password"];
Or you can use NSURLConnection
class, but authentication implementation is a bit tricky.
Upvotes: 0