LoginSignup
65
54

More than 5 years have passed since last update.

WKWebViewを使ってみた。Swift

Last updated at Posted at 2015-12-30

基本

生成

インポート

import WebKit

継承

class ViewController: UIViewController, WKNavigationDelegate{
//省略
}

参考:WKWebViewに関する調査メモ

配置

Swift2.2

let webview = WKWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))

Swift3

let webview = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))

サイトを表示する

Swift2.2

let url = NSURL(string: "https://www.google.com")
urlRequest = NSURLRequest(URL: url)
self.webview.loadRequest(urlRequest)

Swift3

let url = URL(string: "https://www.google.com")
urlRequest = URLRequest(url: url)
self.webview.load(urlRequest)

オプション

タイトル取得

var title = self.webview.title

URL取得

var currenturl = self.webview.url

プログレスバー、インジゲーターを表示

ナビゲーションバーを生成するのは省略です。
Swift2.2

var progressView = UIProgressView()
//オブザーバーを使って取得
override func viewDidLoad(){
    //読み込み状態が変更されたことを取得
    self.webview.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
    //プログレスが変更されたことを取得
    self.webview.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)

    //プログレスバーを生成(NavigationBar下)
    progressView = UIProgressView(frame: CGRectMake(0, self.navigationController!.navigationBar.frame.size.height - 2, self.view.frame.size.width, 10))
    progressView.progressViewStyle = .Bar
    self.navigationController?.navigationBar.addSubview(progressView)
}
deinit{
    //消さないと、アプリが落ちる
    self.webview.removeObserver(self, forKeyPath: "estimatedProgress")
    self.webview.removeObserver(self, forKeyPath: "loading")
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "estimatedProgress"{
        //estimatedProgressが変更されたときに、setProgressを使ってプログレスバーの値を変更する。
        self.progressView.setProgress(Float(self.webview.estimatedProgress), animated: true)
    }else if kyPath == "loading"{
        //インジゲーターの表示、非表示をきりかえる。
        UIApplication.sharedApplication().networkActivityIndicatorVisible = self.webview.loading
        if self.webview.loading{
            self.progressView.setProgress(0.1, animated: true)
        }else{
            //読み込みが終わったら0に
            self.progressView.setProgress(0.0, animated: false)
        }
    }
}

Swift3

var progressView = UIProgressView()

override func viewDidLoad(){
    self.tabBarController?.tabBar.isHidden = true
    self.webview.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
    self.webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)

    //プログレスバーを生成(NavigationBar下)
    progressView = UIProgressView(frame: CGRect(x: 0, y: self.navigationController!.navigationBar.frame.size.height - 2, width: self.view.frame.size.width, height: 10))
    progressView.progressViewStyle = .bar
    self.navigationController?.navigationBar.addSubview(progressView)
}

deinit{
    //消さないと、アプリが落ちる
    self.webview.removeObserver(self, forKeyPath: "estimatedProgress")
    self.webview.removeObserver(self, forKeyPath: "loading")
}

override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>?) {
    if keyPath == "estimatedProgress"{
        //estimatedProgressが変更されたときに、setProgressを使ってプログレスバーの値を変更する。
        self.progressView.setProgress(Float(self.webview.estimatedProgress), animated: true)
    }else if keyPath == "loading"{
        UIApplication.shared().isNetworkActivityIndicatorVisible = self.webview.isLoading
        if self.webview.isLoading {
            self.progressView.setProgress(0.1, animated: true)
        }else{
            //読み込みが終わったら0に
            self.progressView.setProgress(0.0, animated: false)
        }
    }
}
取得するもの WKWebViewのオブザーバーのkeyPath
サイトのURL url
サイトのタイトル title
読み込み loading
進捗 estimatedProgress
戻る canGoBack
進む canGoForward

スワイプで戻る、進む

self.webview.allowsBackForwardNavigationGestures = true

UserScript

Swift2.2

//sourceに、実行するスクリプトを代入
let source = "console.log('Hello, UserScript!');"
let userScript = WKUserScript(source: source, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
let userController = WKUserContentController()
userController.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userController
webview = WKWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height), configuration: configuration)

Swift3

//sourceに、実行するスクリプトを代入
let source = "console.log('Hello, UserScript!');"
let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let userController = WKUserContentController()
userController.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userController
self.webview = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), configuration: configuration)

リンク

WKWebView Class Reference - Apple Developer

コメント

勉強したての頃に書いたので、間違いがありましたら教えてください。
webViewのframe指定はあえてCGRectMake()を使って書きました。Swift3になってCGRectMake()がないみたいなんですが、CGRect()でいいんですかね?

(9/30追記)
removeObserverはdeinitに書くのが一般的だそうなので書き換えました。

65
54
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
65
54