2016-04-07 26 views
4

iOS WKWebView uygulamam için bir geri düğmesi oluşturmaya çalışıyorum, böylece kullanıcı bu düğmeyi tıkladığında onları önceki WKWebView sayfasına götürür. Bunu IB ile nasıl yapılacağına dair çok sayıda öğretici buldum ancak düz kodla değil.iOS - WKWebView Geri Düğmesi program aracılığıyla nasıl oluşturulur?

Orjinal 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) 
     } 
    } 

} 

herhangi bir öneriniz Bu defa ne var? Şimdiden teşekkürler.

DÜZENLEME: kod snippet'ından ziyade ViewController'ın tamamını ekler.

EDIT2: Yanıtı, yanıtının başlangıç ​​URL'sini yüklememesiyle k8mil'e yakındı.

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) 
    } 

cevap

6

deneyin sizin WKWebView örneği yerine WKWebView.goBack() üzerinde webView.goBack() yöntemi çağırmak için: Aşağıda onun cevabını sadece adaptasyon. Ayrıca, goBack()'dan sonra doğru sayfada olduğunuzdan emin olmak için webView.reload() yöntemini çağırabilirsiniz.

private var webView : WKWebView!

yüzden gerekli değildir:

Sana daha önce ilan ettiler çünkü WKWebView başka bir örneğini Neeed yok Ayrıca

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) 
    } 
} 

} 

biraz kodunuzu düzenlenmiş

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

Benim için işe yarıyor. Bu size yardımcı olacaktır

Umut :)

+0

ben doğru benim koduna önerinizi eklendi düşünüyorum ama 'self.webView = WKWebView bir "Beklenen Deklarasyonu" olsun (frame: çerçeve)' hattı. düşünceler? –

+0

Düzenlenmiş cevabı kontrol edin ve işe yararsa bana bildirin;) – kamwysoc

+0

cevabınız yakındı, ancak web sitesi yeniden yüklemem gerekiyordu çünkü ilk web sitesi yüklenmiyordu. OP'de biraz düzeltilmiş versiyonu koydum. Yardımın için çok teşekkürler! –

İlgili konular