Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?
@ktr17

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

More than 3 years have passed since last update.

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)
4
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ktr17

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
4
Help us understand the problem. What is going on with this article?