3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOSのネイティブでユーザ名とパスワードを入力し、認証を行った後、そのセッションを維持したままWebViewへ飛ばす方法

Posted at

iOSアプリを作っているときに、認証情報を次のWebViewへ持たせるときに詰まったので、その対処法を書きます。

認証を行った段階で、サーバから返答されるCookieを保存し、WebViewに渡します。

通信にはAlamofireを使っています

Alamofire.request("<url>",parameters: params)
	.responseString { response in
	let cookies = HTTPCookie.cookies(withResponseHeaderFields: response.response?.allHeaderFields as! [String : String], for: (response.response?.url!)!)

	for i in 0 ..< cookies.count {
		let cookie = cookies[i]
		HTTPCookieStorage.shared.setCookie(cookie)
	}	

}

let authUrl = URL(string: "認証URL")
let url = URL(string: "ロードしたいURL")

var request = URLRequest(url: url)
let cookies = HTTPCookieStorage.shared.cookies(for: authUrl! as URL)
let header = HTTPCookie.requestHeaderFields(with: cookies!)
// Cookieをセットする
request.allHTTPHeaderFields = header
// webViewをロードする
webView.loadRequest(request as URLRequest)
3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?