NSURLConnectionでBasic認証する。ついでにUIAlertViewに入力フォームも載せる。
UIWebViewでBasic認証しようとすると、なんも入力フォームが現れず認証することが出来ずに終わります。
昔はBasic認証しようとすると呼ばれるUIWebViewnのDelegateがあったみたいだけど、最近は使えないみたい。
なのでNSURLConnectionでやる。
それを行うには、
– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
を使います。
これは、Basic認証が発生したときに呼ばれるNSURLConnectionのDelegateメソッド。
この中に、以下のようにすると、認証アラートを出せます。
id_,pass_はNSStringのインスタンス変数、
textField_1,2はUItextFieldのインスタンス変数です。
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSLog(@"didReceiveAuthenticationChallenge"); if ([challenge proposedCredential]) { //IDパスワードが違うときこっちに来る [connection cancel]; id_ = nil; pass_ = nil; } else { if ([id_ length] && [pass_ length]) { NSLog(@"id pass あり"); NSURLCredential *credential = [NSURLCredential credentialWithUser:id_ password:pass_ persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; }else{ NSLog(@"id pass なし"); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"認証が必要です" message:@"\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK!", nil]; textField_1 = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)]; textField_2 = [[UITextField alloc] initWithFrame:CGRectMake(12, 80, 260, 25)]; [textField_1 setBorderStyle:UITextBorderStyleRoundedRect]; [textField_2 setBorderStyle:UITextBorderStyleRoundedRect]; textField_1.placeholder = @"ID"; textField_2.placeholder = @"Password"; textField_1.text = @""; textField_2.text = @""; textField_2.secureTextEntry = YES; CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 0); [alert setTransform:myTransform]; [textField_1 setBackgroundColor:[UIColor whiteColor]]; [textField_2 setBackgroundColor:[UIColor whiteColor]]; [alert addSubview:textField_1]; [alert addSubview:textField_2]; [alert show]; [alert release]; } } }
あとはアラートのデリゲートに
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { id_ = [[NSString alloc] initWithFormat:@"%@",textField_1.text]; pass_ = [[NSString alloc] initWithFormat:@"%@",textField_2.text]; [self postAction:nil]; } }
てな感じで、OKが押された時のアクション書けばOK。
アラートビューは、CGrectとかでサイズが指定できないっぽいので、message部分に改行を入れてスペースを確保してます。
コメントする