19
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WebKit ViewでURLを取得する

Last updated at Posted at 2017-12-07

ちょっと手間取ったのでメモ

WKNavigationDelegateとKOVを使った例をそれぞれ紹介します。

開発環境

・Xcode9
・Swift4

実装(WKNavigationDelegate)

import UIKit
import WebKit // Webkitを読み込む

// WKNavigationDelegateを追加
class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    let homeUrl = "https://qiita.com/trend"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        openUrl(urlString: homeUrl)
        // webViewにデリゲートを設定
        webView.navigationDelegate = self

    }
    
    func openUrl(urlString: String){
        let url = URL(string: urlString)
        let urlRequest = URLRequest(url: url!)
        webView.load(urlRequest)
    }
    
    // ページが表示されたら下記の関数を実行
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let activeUrl: URL? = self.webView.url
        let url = activeUrl?.absoluteString
        
        // 特定のURLで分岐処理
        if url! == "https://qiita.com/trend" {
            print(url!)
        }       
    }
   
}

didFinish関数はアプリを立ち上げた時に一回だけ呼ばれます。
毎回ページURLを判定して何か処理を行いたい時はKOVを使います。

実装(KOV)

import UIKit
import WebKit // Webkitを読み込む

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!

    let homeUrl = "https://qiita.com/trend"

    override func viewDidLoad() {
        super.viewDidLoad()

        // オブサーバーの設定
        self.webView?.addObserver(self, forKeyPath:"URL", options:.new, context:nil)
        openUrl(urlString: homeUrl)
    }

    func openUrl(urlString: String){
        let url = URL(string: urlString)
        let urlRequest = URLRequest(url: url!)
        webView.load(urlRequest)
    }

    deinit {
        self.webView?.removeObserver(self, forKeyPath: "URL")
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        switch keyPath {
            case "URL"?:
                if let url = change![NSKeyValueChangeKey.newKey] as? URL {
                    let urlString: String = url.absoluteString
                    // ページアクセスするたびにURLを取得
                    print(url)
                    
                }
            
        default:
            break
        
        }
    
    }


}

参考サイト

WKWebView リファレンス
mixi-inc/iOSTraining
[Swift4]Webkit View(WKWebView)の使い方
SwiftでWKWebViewとKey-Value Observingを使ってWebページの読込み状況を取得する
[SwiftでKVO(Key-Value Observing)を行う]
(https://qiita.com/Kei-Kamikawa/items/9d6d661bff2d15ceac51)

19
24
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
19
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?