9
7

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.

[swift4]WKWebViewを使ったwebview

Last updated at Posted at 2018-07-15

WKWebViewを使ったWebView表示

swift4使用

また使いそうなのでメモ

storyboardは手を入れない。全部コードで。
リンク先は全部Safariに飛ばす

色々サイトを調べて作成。サイトのリンク消してしまった。

ViewController.swift
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    var webView: WKWebView!
    let firstViewUrl = "https://yahoo.co.jp"
    
    // toolBar設定
    var toolBar: UIToolbar?
    var rewindButton = UIBarButtonItem()
    var fastForwardButton = UIBarButtonItem()
    var refreshButton = UIBarButtonItem()
    var openInSafari = UIBarButtonItem()
    
    // portraitのみを想定
    var topPadding:CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // インジケータ表示設定
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        
        // ツールバー生成
        let width:CGFloat = view.frame.size.width
        let height:CGFloat = view.frame.size.height
        self.toolBar = self.createToolBar(frame: CGRect(x: 0, y: height-44, width: width, height: 40.0), position: CGPoint(x: width/2, y: height-20.0))

    }

    override func viewDidAppear(_ animated: Bool) {
        
        let screenWidth:CGFloat = view.frame.size.width
        let screenHeight:CGFloat = view.frame.size.height
        
        // iPhone X , X以外は0となる
        if #available(iOS 11.0, *) {
            let window = UIApplication.shared.keyWindow
            topPadding = window!.safeAreaInsets.top
        }
        
        // Webページの大きさを画面に合わせる
        let rect = CGRect(x: 0,
                          y: topPadding,
                          width: screenWidth,
                          height: screenHeight - topPadding)
        
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: rect, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        
        // スワイプで戻るを許可
        //webView.allowsBackForwardNavigationGestures = true
        
        let webUrl = URL(string: firstViewUrl)!
        let req = URLRequest(url: webUrl)
        webView.load(req)
        
        // インスタンスをビューに追加する
        self.view.addSubview(webView)
        
        // サブビューを追加する
        self.view.addSubview(self.toolBar!)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // WebView がコンテンツの読み込みを完了した後に呼ばれる
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // インジケータを非表示にする
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        
        self.rewindButton.isEnabled = self.webView!.canGoBack
        self.fastForwardButton.isEnabled = self.webView!.canGoForward

    }
    
    // WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        // リンククリックは全部Safariに飛ばしたい
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            UIApplication.shared.open(navigationAction.request.url!)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
    
    // WKUIDelegate
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        // リンククリックは全部Safariに飛ばしたい
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            UIApplication.shared.open(navigationAction.request.url!)
        }
        
//        // target="_blank"なリンクが開かない時の対処
//        if navigationAction.targetFrame == nil {
//            webView.load(navigationAction.request)
//        }
        
        return nil
    }
    
    // Create ToolBar
    func createToolBar(frame: CGRect, position: CGPoint) -> UIToolbar {
        // UIWebViewのインスタンスを生成
        let _toolBar = UIToolbar()
        
        // ツールバーのサイズを決める
        _toolBar.frame = frame
        
        // ツールバーの位置を決める
        _toolBar.layer.position = position
        
        // 文字色を設定する
        _toolBar.tintColor = UIColor.black
        // 背景色を設定する
        _toolBar.backgroundColor = UIColor.white
        
        // 各ボタンを生成する
        let spacerEdge: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spacerEdge.width = 16
        let spacer: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spacer.width = 42
        self.rewindButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 101)!, target: self, action: #selector(back))
        self.fastForwardButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 102)!, target: self, action: #selector(forward))
        self.refreshButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh))
        self.openInSafari = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(safari))
        let spacerRight: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        // ボタンをツールバーに入れる
        _toolBar.items = [spacerEdge, rewindButton, spacer, fastForwardButton, spacerRight, refreshButton, spacer, openInSafari, spacerEdge]
        
        return _toolBar
    }
    
    // 戻るボタンの処理
    @IBAction func back(_: AnyObject) {
        self.webView?.goBack()
    }
    
    // 進むボタンの処理
    @IBAction func forward(_: AnyObject) {
        self.webView?.goForward()
    }
    
    // 再読み込みボタンの処理
    @IBAction func refresh(_: AnyObject) {
        self.webView?.reload()
    }
    
    // safari で開く
    @IBAction func safari(_: AnyObject) {
        let url = self.webView?.url
        UIApplication.shared.open(url!, options: [:], completionHandler: nil)
    }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?