LoginSignup
0
0

More than 5 years have passed since last update.

WKWebViewで特定のリンクからアプリ側の処理を実行してみる with Codableを使う奴

Posted at

若干変態的実装にもなっているので、マサカリ飛んでくるかなとおもって書いておく

今回やりたいこと

  • WKWebViewで表示しているサイト上で、特定のリンクを踏んだ場合アプリ内での処理を実行したい。
  • リンクはとりあえずqueryでパラメータやり取り
  • どうせだからCodableあたりでも使って構造体にしてぇな?

若干手抜き気味の実装

一応やっていることの簡単な説明

  • やりたいことに書いてある内容
  • +αとしてこんなの
    • 指定したURLは内部処理へ
    • 別の指定したURLはWebViewで遷移
    • 指定したURL以外のアクセスはSafariで開く
    • それ以外は取りあえずキャンセル
WebViewController.swift
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        if let url = navigationAction.request.url,
            url.absoluteString.hasPrefix(WebViewConfig.openConciergeUrlScheme) {
            let params: [String: String] = url.queryParams()
            let jsonData = try! JSONSerialization.data(withJSONObject: params, options: [])
            let decoder = JSONDecoder()
            let hoge = try? decoder.decode(Hoge.self, from: jsonData)
            decisionHandler(.cancel)
        } else if let url = navigationAction.request.url,
            url.absoluteString.hasPrefix(WebViewConfig.baseUrl) {
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
            decisionHandler(.allow)
        } else if let url = navigationAction.request.url {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.cancel)
        }
    }

url.queryParams()の部分は、こちらを使わせて頂きました。
https://qiita.com/roba4coding/items/9783625f7b2b469e17b8

Hoge.swift
struct Hoge: Codable {
    let tab: String
    let room: String
    let message: String
}

以上、dump結果がこちらです。

  - tab: "2"
  - room: "default"
  - message: "あああああ"

割とスマートな形にはなっているが、変換が多すぎてなんかうーんってなる。
なお、暫定手抜き実装のソースなのでその辺はご了承ください。
他に良い方法があればご教示ください。

ではでは。

0
0
0

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
0
0