LoginSignup
13
8

More than 5 years have passed since last update.

WKWebViewでのPOST Request

Last updated at Posted at 2018-02-20

※追記:2018.05.17 詳細はソース参照
いろんなサイトの情報を片っ端から試してやっと出来たのでメモ

やりたいこと:
フォームデータ付きのPOST Requestを飛ばしWKWebViewで表示する。
その際にユーザ認証に必要なフォームデータを追加する。

環境:
-Swift 4
-Xcode 9.2
-Deployment Target 10.0
※11以上からStoryboard上でWKWebView置けるようになったのでもっと簡単になるはず

ViewController.swift
import UIKit
import WebKit

class ViewController: UIViewController , WKNavigationDelegate, WKUIDelegate {
    var webView: WKWebView!

    override func loadView() {
        // 追記:2018.05.17 webViewをsub view化した際に親メソッドを呼ばないと実行時エラーとなったため
        super.loadView()

        let webConfiguration = WKWebViewConfiguration()
        // アプリからのアクセスとサーバ側に伝えるためuseragentのアプリケーション名を書き換え
        webConfiguration.applicationNameForUserAgent = "test-app"

        self.webView = WKWebView(frame: .zero, configuration: webConfiguration)
        self.webView.navigationDelegate = self
        self.webView.uiDelegate         = self

        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var request = URLRequest(url: URL(string: "https://www.google.co.jp/")!)
        request.httpMethod = "POST"

        // パラメータのように2つ目以降は&でつなぐ
        var bodyData = "terminal_id=" + UIDevice.current.identifierForVendor!.uuidString
        request.httpBody = bodyData.data(using: .utf8)!
        self.webView.load(request)
    }
}

出来てみたら
だから、どうした
って事もないプログラムですが

13
8
1

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
13
8