Objective-C (iOS): WebView と Basic 認証

BasicAuthViewController

Objective-C: BasicAuthViewController.h

#import <UIKit/UIKit.h>

@interface BasicAuthViewController : UIViewController <UIWebViewDelegate>
{
    UIWebView *webView_;
}
@end

Objective-C: BasicAuthViewController.m

#import "BasicAuthViewController.h"

#define USER @"USER_NAME"
#define PASSWORD @"PASSWORD"
#define DEFAULT_URL @"URL"

@implementation BasicAuthViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    webView_ = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView_.delegate = self;
    [self.view addSubview:webView_];
    [self registerMyCredential];
}

- (void)registerMyCredential
{
    NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:DEFAULT_URL]] delegate:self];
    [conn start];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredential* creds = [NSURLCredential credentialWithUser:USER password:PASSWORD persistence:NSURLCredentialPersistencePermanent];
    [[challenge sender] useCredential:creds forAuthenticationChallenge:challenge];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self configureView];
}

- (void)configureView
{
    NSString* url = DEFAULT_URL;
    [webView_ loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

- (void)webView:(id)webView resource:(id)resource didReceiveAuthenticationChallenge:(id)challenge fromDataSource:(id)dataSource {
    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user" password:@"password" persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *URL = [request URL];
    if ([[URL scheme] isEqualToString:@"webview"]) {
        return NO;
    }
    return YES;
}

@end