gpt4 book ai didi

ios - Swift:使用 evaluateJavascript

转载 作者:可可西里 更新时间:2023-11-01 01:42:24 30 4
gpt4 key购买 nike

我是 Swift 开发的新手,我有一个正在开发的混合应用程序,我已经连接了身份验证。当用户使用设备上的指纹传感器进行身份验证时,我想触发 JS 或以其他方式与 WKWebView 交互......但出于某种原因,我似乎无法让它工作。我可以做一些简单的事情,例如更改窗口 HREF...但如果我做一些更复杂的事情,它要么什么都不做,要么失败。

这是我的 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)

}

我似乎无法在此处获取 webView 的句柄。如果我尝试在此处实际评估脚本,它会抛出以下错误:

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 句柄,因为我知道如果我在从 View 中成功导航后立即尝试这样的操作,它将正常工作,例如:

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

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

}

很明显,在我的 logInWithStoredCredentials 函数中,它丢失了 webView 的上下文。

如何在我的 logInWithStoredCredentials 函数中获得 webView 的正确句柄?

对不起大家 - 我知道这是一个相当基本的问题,但我已经思考了几个小时,这是一个非常紧迫的问题,我必须 swift 解决。

最佳答案

看起来您的 UI 中有 UIWebView 而不是 WKWebView:

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

您应该改为实例化一个 WKWebView 实例。另请注意,WKWebView 无法在 Interface Builder 中创建,您必须在运行时将其添加到 View 层次结构中。

关于ios - Swift:使用 evaluateJavascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444969/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com