Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The secret to HTTP basic authentication using cocoa is knowing NSURL and the related classes.</p> <ul> <li>NSURL</li> <li>NSURLRequest/NSMutableURLRequest</li> <li>NSURLConnection</li> <li>NSURLCredential</li> <li>NSURLCredentialStorage</li> <li>NSURLProtectionSpace</li> <li>UIWebView/WebView/NIWebController etc.</li> </ul> <p>The real magic comes from NSURLConnection. In the words of the devDocs, "An NSURLConnection object provides support to perform the loading of a URL request." If you want to load some a URL in the background without displaying it you would use NSURLConnection. The real power of the NSURLConnection is in the method</p> <pre><code>+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id &lt; NSURLConnectionDelegate &gt;)delegate </code></pre> <p>The NSURLConnectionDelegate protocol has methods for responding to successful connections, fatal errors, and authentication challenges. If you are trying to access data Protected by HTTP basic authentication this is how Cocoa does it. At this point an example should bring some clarity.</p> <pre><code>//basic HTTP authentication NSURL *url = [NSURL URLWithString: urlString]; NSMutableURLRequest *request; request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:12]; [self.webView openRequest:request]; (void)[NSURLConnection connectionWithRequest:request delegate:self]; </code></pre> <p>This creates a URL. From the URL a URLRequest is created. The URLRequest is then loaded in the web view. The Request is also used to make a URLConnection. We don't really use the connection, but we need to receive notifications about authentication so we set the delegate. There are only two methods we need from the delegate.</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; { NSURLCredential * cred = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [[NSURLCredentialStorage sharedCredentialStorage]setCredential:cred forProtectionSpace:[challenge protectionSpace]]; } - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection; { return YES; } </code></pre> <p>Whenever there is an authentication challenge a credential is added to the credential storage. You also tell the connection to use the credential storage.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload