Swift stringByEvaluatingJavaScriptFromString

I am trying to use some javascript in my webview with a new

stringByEvaluatingJavaScriptFromString Function

I am not very familiar with the syntax, so I tried

  func stringByEvaluatingJavaScriptFromString( "document.documentElement.style.webkitUserSelect='none'": String) -> String? 

as shown here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString : but I get an "Expected" error message . delimiter "

+6
source share
2 answers

The method you are trying to call is prototyped as follows:

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

It means:

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

To use it, there must be an instance of UIWebView :

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

Because the return type is optional , you must expand it before you can use it. But be careful, it may not matter (that is, it may be nil ), and the expanding nil values ​​will lead to runtime failures.

So, you need to check this before you can use the returned string:

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

This means: if result not nil , then expand it and assign it to a new constant called returnedString .

Alternatively, you can wrap it along 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.

+9
source

This method is used to call javascript script directly from uiwebview

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

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

0
source

Source: https://habr.com/ru/post/975875/


All Articles