2016-04-07 20 views
4

iOS WKWebViewアプリケーション用の戻るボタンを作成しようとしています。そのため、ユーザーがボタンをクリックすると、以前のWKWebViewページに移動します。私はIBでこれを行う方法について多くのチュートリアルを見つけましたが、ストレートコードでは見つかりませんでした。これは私がこれまで持っているものです。iOS - WKWebViewの[戻る]ボタンをプログラムで作成するには?

オリジナルViewController.swift:

import UIKit 
import WebKit 

class ViewController: UIViewController, WKNavigationDelegate { 

    private var webView: WKWebView! 

    let wv = WKWebView(frame: UIScreen.mainScreen().bounds) //needed for working webview 

    self.webView = WKWebView(frame: frame) 
    self.webView.navigationDelegate = self 

    func rightbutton(text: String, action: Selector) { 
     let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action) 
     self.navigationItem.rightBarButtonItem = rightButton 
    } 

    func action() { 
     if self.webView.canGoBack { 
      print ("Can go back") 
      self.webView.goBack() 
      self.webView.reload() 

     } else { 
      print ("Can't go back") 
     } 
    } 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return } 
     wv.navigationDelegate = self 
     wv.loadRequest(NSURLRequest(URL: url)) 
     view.addSubview(wv) 


     webView.goBack() 
     webView.reload() 



     prefButton() 
     //backButton() 

     NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionEnter", 
      object: nil) 

     NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionUpdate", 
      object: nil) 

     NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionExit", 
      object: nil) 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func prefButton() { 
     let image = UIImage(named: "icon-pref128") as UIImage? 
     let button = UIButton(type: UIButtonType.Custom) as UIButton 
     let screenSize: CGRect = UIScreen.mainScreen().bounds 
     let screenWidth = screenSize.width 
     let screenHeight = screenSize.height 

     button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width) 
     button.setImage(image, forState: .Normal) 
     button.addTarget(self, action: "buttonClicked:", forControlEvents:.TouchUpInside) 
     self.view.addSubview(button) 
    } 

    func buttonClicked(sender:UIButton) 
    { 
     UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) 
    } 

    func receiveNotification(notification: NSNotification) { 
     print(notification.userInfo) 
    } 

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { 
     if navigationAction.navigationType == .LinkActivated { 
      if let newURL = navigationAction.request.URL, 
       host = newURL.host where !host.containsString("communionchapelefca.org") && 
        UIApplication.sharedApplication().canOpenURL(newURL) { 
         if UIApplication.sharedApplication().openURL(newURL) { 
          print(newURL) 
          print("Redirected to browser. No need to open it locally") 
          decisionHandler(.Cancel) 
         } else { 
          print("browser can not url. allow it to open locally") 
          decisionHandler(.Allow) 
         } 
      } else { 
       print("Open it locally") 
       decisionHandler(.Allow) 
      } 
     } else { 
      print("not a user click") 
      decisionHandler(.Allow) 
     } 
    } 

} 

任意の提案ですか?前もって感謝します。

EDIT:コードスニペットではなくViewController全体を添付します。

EDIT2:答えがk8milで終わったのは、彼の答えが初期URLをロードしなかったためです。以下は彼の答えからの調整のみである:

private func createWebView() { 
     guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return } 
     let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height) 
     self.webView = WKWebView(frame: frame) 
     self.webView.navigationDelegate = self 
     self.webView.loadRequest(NSURLRequest(URL: url)) 
     self.view.addSubview(self.webView) 
    } 

答えて

6

ではなくWKWebView.goBack()あなたWKWebViewインスタンスでwebView.goBack()メソッドを呼び出すようにしてください。 goBack()の後にも、webView.reload()メソッドを呼び出して、正しいページにいることを確認することができます。

私は少し

import UIKit 
import WebKit 

class ViewController: UIViewController, WKNavigationDelegate { 

private var webView: WKWebView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { 
     return 
    } 

    //create WebView and Back button 
    createWebView() 
    backButton() 


    prefButton() 


    NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionEnter", 
      object: nil) 

    NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionUpdate", 
      object: nil) 

    NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "receiveNotification:", 
      name: "BeaconServiceRegionExit", 
      object: nil) 

} 


private func createWebView() { 
    let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height) 
    self.webView = WKWebView(frame: frame) 
    self.webView.navigationDelegate = self 
    self.view.addSubview(self.webView) 
} 

func addBackButton(text: String, action: Selector) { 
    //this function will add Button on your navigation bar e 

    let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action) 
    self.navigationItem.rightBarButtonItem = rightButton 
} 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func prefButton() { 
    let image = UIImage(named: "icon-pref128") as UIImage? 
    let button = UIButton(type: UIButtonType.Custom) as UIButton 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 
    let screenWidth = screenSize.width 
    let screenHeight = screenSize.height 

    button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width) 
    button.setImage(image, forState: .Normal) 
    button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) 
    self.view.addSubview(button) 
} 

func backButton() { 
    let image = UIImage(named: "icon-back") as UIImage? 
    let button = UIButton(type: UIButtonType.Custom) as UIButton 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 
    let screenWidth = screenSize.width 
    let screenHeight = screenSize.height 

    button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width) 
    button.setImage(image, forState: .Normal) 
    button.addTarget(self, action: "customGoBack:", forControlEvents: .TouchUpInside) 
    self.view.addSubview(button) 
} 

func customGoBack(sender: UIButton) { 
    if self.webView.canGoBack { 
     print("Can go back") 
     self.webView.goBack() 
     self.webView.reload() 
    } else { 
     print("Can't go back") 
    } 
} 

func buttonClicked(sender: UIButton) { 
    UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) 
} 

func receiveNotification(notification: NSNotification) { 
    print(notification.userInfo) 
} 

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { 
    if navigationAction.navigationType == .LinkActivated { 
     if let newURL = navigationAction.request.URL, 
     host = newURL.host where !host.containsString("communionchapelefca.org") && 
       UIApplication.sharedApplication().canOpenURL(newURL) { 
      if UIApplication.sharedApplication().openURL(newURL) { 
       print(newURL) 
       print("Redirected to browser. No need to open it locally") 
       decisionHandler(.Cancel) 
      } else { 
       print("browser can not url. allow it to open locally") 
       decisionHandler(.Allow) 
      } 
     } else { 
      print("Open it locally") 
      decisionHandler(.Allow) 
     } 
    } else { 
     print("not a user click") 
     decisionHandler(.Allow) 
    } 
} 

} 

あなたのコードを編集したあなたが以前に宣言したので、また、あなたがWKWebViewの別のインスタンスをneeedいない:それは必要ありません

private var webView : WKWebView!

wv.navigationDelegate = self 
wv.loadRequest(NSURLRequest(URL: url)) 
view.addSubview(wv) 

私にとってはうまくいきます。これはあなたを助ける

希望:)

+0

は私が私が正しく自分のコードにあなたの提案を追加しましたと思いますが、私は、 'self.webView = WKWebViewで「期待宣言」を取得(フレーム:フレーム)'ラインを。思考? –

+0

編集した回答をチェックし、それが動作するかどうか教えてください) – kamwysoc

+0

あなたの答えは近いですが、最初のウェブサイトが読み込まれていないため、webview部分を修正する必要がありました。私は少し修正されたバージョンをOPに入れました。助けてくれてありがとう! –

関連する問題