2015-02-11 98 views
1

我對Swift開發相當陌生,而且我正在開發一個混合應用程序,我已經連接了身份驗證。當用戶使用設備上的指紋傳感器進行身份驗證時,我想要觸發JS或以其他方式與WKWebView進行交互......但出於某種原因,我似乎無法使其工作。我可以做簡單的事情,比如改變窗口HREF ...但是如果我做更復雜的事情,它可能什麼都不做,或者失敗。Swift:使用evaluateJavascript

這裏是我的viewController的代碼:

import UIKit 
    import WebKit 
    import LocalAuthentication 

    class ViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate { 

     @IBOutlet var containerView : UIView! = nil 

     // @IBOutlet weak var webView: UIWebView! 
     var webView: WKWebView? 
     var contentController = WKUserContentController(); 

     @IBOutlet var activityIndicatorView: UIActivityIndicatorView! 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      // append the userAgent and ensure it contains our browser detect regEx 
      let userAgent = UIWebView().stringByEvaluatingJavaScriptFromString("navigator.userAgent")! + " iPad" 
      NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : userAgent]) 

      // add JS content controller 

      var config = WKWebViewConfiguration() 
      config.userContentController = contentController 

      // instantiate the web view 
      let webView = WKWebView(frame: CGRectZero, configuration: config) 
      webView.setTranslatesAutoresizingMaskIntoConstraints(false) 
      webView.navigationDelegate = self 
      view.addSubview(webView) 

      // customize sizing 
      view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: ["webView": webView])) 

      view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: ["webView": webView])) 

      // open the URL for the app 
      let urlPath = "http://im_a_url" 
      let url: NSURL = NSURL(string: urlPath)! 
      let request = NSURLRequest(URL: url) 
      webView.loadRequest(request) 

     } 

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

     func webView(webView: WKWebView!, didStartProvisionalNavigation navigation: WKNavigation!) { 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
     } 

     func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) { 
    UIApplication.sharedApplication().networkActivityIndicatorVisible = false 

      // trigger authentication 
      authenticateUser() 

     } 

     func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { 

     } 

     func logInWithStoredCredentials() { 
      println("successful auth - log in"); 
      // TO DO - use core data to stor user credentials 
      webView!.evaluateJavaScript("document.getElementById('anonymousFormSubmit').click();", nil) 

     } 

     func authenticateUser() { 
      // Get the local authentication context. 
      let context = LAContext() 

      // Declare a NSError variable. 
      var error: NSError? 

      // Set the reason string that will appear on the authentication alert. 
      var reasonString = "Authentication is needed to access aware360Suite." 

      // Check if the device can evaluate the policy. 
      if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) { 
       [context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in 

        if success { 
         self.logInWithStoredCredentials() 
         // self.webView?.evaluateJavaScript("document.getElementById('auiAuthSubmitBtn').click();", nil) 
        } 
        else{ 
         // If authentication failed then show a message to the console with a short description. 
         // In case that the error is a user fallback, then show the password alert view. 
         println(evalPolicyError?.localizedDescription) 

         switch evalPolicyError!.code { 

         case LAError.SystemCancel.rawValue: 
          println("Authentication was cancelled by the system") 

         case LAError.UserCancel.rawValue: 
          println("Authentication was cancelled by the user") 

         case LAError.UserFallback.rawValue: 
          println("User selected to enter custom password") 
          // self.showPasswordAlert() 

         default: 
          println("Authentication failed") 
          // self.showPasswordAlert() 
         } 
        } 

       })] 
      } 
      else{ 
       // If the security policy cannot be evaluated then show a short message depending on the error. 
       switch error!.code{ 

       case LAError.TouchIDNotEnrolled.rawValue: 
        println("TouchID is not enrolled") 

       case LAError.PasscodeNotSet.rawValue: 
        println("A passcode has not been set") 

       default: 
        // The LAError.TouchIDNotAvailable case. 
        println("TouchID not available") 
       } 


      } 

     } 

    } 

的問題是,在成功的驗證方法:

func logInWithStoredCredentials() { 
     println("successful auth - log in"); 
     // TO DO - use core data to use stored user credentials 
     webView!.evaluateJavaScript("document.getElementById('anonymousFormSubmit').click();", nil) 

    } 

我似乎無法在這裏得到一個處理web視圖。如果我試圖在這裏實際評估腳本,它會拋出以下錯誤:

2015-02-10 17:07:32.912 A360[2282:462860] -[UIWebView evaluateJavaScript:completionHandler:]: unrecognized selector sent to instance 0x1741897f0 
2015-02-10 17:07:32.916 A360[2282:462860] <NSXPCConnection: 0x178103960> connection to service named com.apple.CoreAuthentication.daemon: Warning: Exception caught during decoding of received reply to message 'evaluatePolicy:options:reply:', dropping incoming message and calling failure block. 

Exception: -[UIWebView evaluateJavaScript:completionHandler:]: unrecognized selector sent to instance 0x1741897f0 

我很茫然。我知道我沒有合適的句柄的WebView在這裏,因爲我知道,如果我有過在視圖中成功導航後立即嘗試這樣的操作時,它會正常工作,如:

func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) { 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = false 

     webView.evaluateJavaScript("document.getElementById('anonymousFormSubmit').click();", nil) 

    } 

很顯然,在我的logInWithStoredCredentials函數中,它已經失去了webView的上下文。

如何在我的logInWithStoredCredentials func中獲得webView的正確句柄?

對不起所有 - 我知道這是一個相當基本的問題,但我一直對我的頭撞幾個小時,這是一個非常緊迫的問題,我必須迅速解決。

+0

瀏覽一下新的[library](https://github.com/coshx/caravel),它可以幫助你;) – 2015-06-02 20:55:48

回答

2

它看起來像你的UIWebView而不是WKWebView在UI:

Exception: -[UIWebView evaluateJavaScript:completionHandler:]: unrecognized selector sent to instance 0x1741897f0 

你應該實例化一個WKWebView實例,而不是。另外請注意,WKWebView無法在Interface Builder中創建,您必須在運行時將其添加到視圖層次結構中。

0

您有var webView: WKWebView?在你的班級,但然後重新定義它在viewDidLoadlet webView = WKWebView(frame: CGRectZero, configuration: config) 刪除讓在webView前,讓它工作。

相關問題