前提・実現したいこと
iosアプリからWebページに任意のCookieを渡したいのですがうまくいきません。。。
なぜ、Cookieが登録できないのか、どのような処理(または前提知識?)が足りていないのか
助言できる方が居ましたらお願いします。
wkWebViewを使用前提です。
試したコード
override func viewDidLoad() { let configuration = WKWebViewConfiguration() let processPool = WKProcessPool() configuration.processPool = processPool let userContentController = WKUserContentController() let script = "document.cookie = 'username=test'; expires=2037-06-02 20:00:00 GMT; path=/; domain=.mpw.jp';" let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false) userContentController.addUserScript(cookieScript) configuration.userContentController = userContentController let wkWebView = WKWebView(frame: view.frame, configuration: configuration) wkWebView.navigationDelegate = self self.view.addSubview(wkWebView) guard let url = URL(string: self.targetUrl) else { return } let request = URLRequest(url: url) wkWebView.load(request) }
iOS11以降なら。。。
以下のコードでCookieを登録し送れることは確認しました。
let webView = WKWebView() let configuration = WKWebViewConfiguration() let processPool = WKProcessPool() configuration.processPool = processPool let cookieStore = configuration.websiteDataStore.httpCookieStore; let cookie = HTTPCookie(properties: [ HTTPCookiePropertyKey.domain: ".mpw.jp", HTTPCookiePropertyKey.path: "/", HTTPCookiePropertyKey.name: "username", HTTPCookiePropertyKey.value: "test"]) cookieStore.setCookie(cookie!) { webView.load(request) }
また、他のCookieに影響を与えたくないため以下の方法は使えません。
urlRequest.addValue("user=test;", forHTTPHeaderField: "Cookie") urlRequest.setValue("user=test;", forHTTPHeaderField: "Cookie")
教えていただきたい点
Cookieが飛んでるかどうかは飛ばし先を以下のサイトにして確認しています。
http://mpw.jp/requestheader/
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。