Swift stringByEvaluatingJavaScriptFromString

若如初见. 提交于 2019-12-05 04:11:29

The method you are trying to call is prototyped as the following:

func stringByEvaluatingJavaScriptFromString(_ script: String) -> String?

This means :

  • It takes a String as single parameter
  • It returns an optional String (String?)

You need to have an instance of UIWebView to use it:

let result = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitUserSelect='none'")

Because the return type is optional, it needs to be unwrapped before you can use it. But be careful, it may not have a value (i.e. it may be equal to nil) and unwrapping nil values leads to runtime crashes.

So you need to check for that before you can use the returned string:

if let returnedString = result {
    println("the result is \(returnedString)")
}

This means: If result is not nil then unwrap it and assign it to a new constant called returnedString.

Additionally, you can wrap it together with:

let script = "document.documentElement.style.webkitUserSelect='none'"
if let returnedString = webView.stringByEvaluatingJavaScriptFromString(script) {
    println("the result is \(returnedString)")
}

Hope this makes sense to you.

This method is used to call the javascript script directly from uiwebview

let htmlTitle = myWebView.stringByEvaluatingJavaScriptFromString("document.title");
println(htmlTitle) 

http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!