サーバ側プログラム("http://example.co.jp/test")
適当に実装
xamppでもHerokuでも何でも
<html>
<head>
<title>Hello WKWebView</title>
</head>
<body>
<h1>Hello WKWebView</h1>
<form action="/hello" name="form1" method="POST">
<input type="text" name="name">
<input type="password" name="password" size="30" maxlength="30">
<input type="submit">
</form>
</body>
</html>
iOSプログラム
上記画面へアクセスするようにWKWebViewでiOSアプリを実装する
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webview: WKWebView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
// viewの置き換え addsubviewの方がいい?
self.view = self.webview
webview.navigationDelegate = self
let url = URL(string:"http://example.co.jp/test")!
let req = URLRequest(url:url)
self.webview.load(req)
}
/// Post時に呼ばれるイベント
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// リクエスト内容確認 ただしこの中にpost値は入っていない
let request = navigationAction.request
print( request )
// nameフィールドの値を取得
webView.evaluateJavaScript("document.form1.name.value",
completionHandler: { (html, error) -> Void in
print(html as? String)
})
// passwordフィールドの値を取得
webView.evaluateJavaScript("document.form1.password.value",
completionHandler: { (html, error) -> Void in
print(html as? String)
})
decisionHandler(WKNavigationActionPolicy.allow)
}
}
http://d.hatena.ne.jp/rokugen/20110207 あたりを参考にした。
WebViewは即値が返ってきたけどWKWebViewはハンドラに登録しないといけないらしい。
以下実行確認
iOSからpostしてみる
post時に以下が表示される。
Optional("てすと")
Optional("pass")
この値を保持して画面遷移時に表示すれば要件は満たせる。Optional("pass")
ただしwebのデザインが変わると動かなくなるのはかなりきついのでjsを読み込む形にした方がいいかもしれない。