LoginSignup
17
17

More than 5 years have passed since last update.

UIWebViewにBASIC認証サポート用のUIを追加する

Last updated at Posted at 2013-08-20

UIWebViewは標準ではBASIC認証に対応していませんが、URLProtocolの仕組みを使うことで認証が要求されたタイミングで任意の処理フックできます。

そこで、モバイルSafariと同様にUIAlertViewでユーザー名・パスワードを入力するダイアログをポップアップ表示するライブラリを作成しました。

1.png2.png

ソースコードはMITライセンスで公開しています
https://github.com/synapsesoft/UIWebViewAuthentication

インストール

Cocoapodsで行います。

Podfile
platform :ios, '5.0'

pod 'UIWebViewAuthentication', :podspec => 'https://raw.github.com/synapsesoft/UIWebViewAuthentication/master/UIWebViewAuthentication.podspec'

使い方

本ライブラリはUIWebViewを継承したUWAWebViewクラスを提供します。
典型的な使い方としては、ViewControllerに追加するUIWebViewをUWAWebViewに置き換えます。

RootViewController.m
// #import <UIWebViewAuthentication/UWAWebView.h>
- (void)viewDidLoad
{
  [super viewDidLoad];

  self.webView = [[UWAWebView alloc] initWithFrame:self.view.frame];
  [self.view addSubview:self.webView];

  NSString* url = @"http://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx";
  NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  [self.webView loadRequest:request];
}

一度入力したパスワードはiOSが管理の認証情報に登録されます。これを一時的に保存しないように変更する場合 authentication.persistence プロパティへ NSURLCredentialPersistenceForSessionを設定します。

RootViewController.m
self.webView.authentication.persistence = NSURLCredentialPersistenceForSession;

アラート内のメッセージについてはiOSアプリの国際化の機構を使って変更できます。Example アプリソース https://github.com/synapsesoft/UIWebViewAuthentication/tree/master/Example などを参照してください。

Localizable.strings
"Authentication Required" = "認証が必要です";
"Cancel" = "キャンセル";
"Log In" = "ログイン";

本ライブラリは株式会社シナプスソフトの実プロジェクトのアプリで使用していますが、現実の様々なパターンのアプリに組込むテストは不十分だと思われます。使い方や挙動について質問ありましたらお気軽に https://github.com/synapsesoft/UIWebViewAuthentication/issues へ投稿ください。

17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17