サーバ側プログラム("http://example.co.jp/test")
適当に実装
xamppでもHerokuでも何でも
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < 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アプリを実装する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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 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を読み込む形にした方がいいかもしれない。