Skip to content

Instantly share code, notes, and snippets.

@laiso
Created September 12, 2011 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laiso/1211980 to your computer and use it in GitHub Desktop.
Save laiso/1211980 to your computer and use it in GitHub Desktop.
UIWebView を使って BASIC認証のあるページにアクセスする
// NOTE: 望んだように動かない……
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIWebView* webView = [[[UIWebView alloc] initWithFrame:self.window.frame] autorelease];
webView.delegate = self;
NSString* url = @"http://example.com/authorization";
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
[self.window addSubview:webView];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSDictionary *headers = [request allHTTPHeaderFields];
if(![[headers allKeys] containsObject:@"Authorization"]) {
NSMutableURLRequest *newRequest = [request mutableCopy];
[newRequest addValue:@"Basic ${USER:PASSWORD_BASE64}"
forHTTPHeaderField:@"Authorization"];
[webView loadRequest:newRequest];
[newRequest release];
return NO;
}
return YES;
}
// NOTE: 望んだように動かない……
// → https://github.com/oscardelben/UIWebViewBasicAuth/blob/master/NSMutableURLRequest+BasicAuth.m
// だとうまくいった
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIWebView* webView = [[[UIWebView alloc] initWithFrame:self.window.frame] autorelease];
webView.delegate = self;
NSString* url = @"http://example.com/authorization";
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
[self.window addSubview:webView];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSDictionary *headers = [request allHTTPHeaderFields];
if(![[headers allKeys] containsObject:@"Authorization"]) {
NSMutableURLRequest *newRequest = [request mutableCopy];
[newRequest addValue:@"Basic ${USER:PASSWORD_BASE64}"
forHTTPHeaderField:@"Authorization"];
[webView loadRequest:newRequest];
[newRequest release];
return NO;
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment