1

In Objective-C, the following code works in viewDidLoad:

[self.myWebView performSelectorOnMainThread:
@selector(stringByEvaluatingJavaScriptFromString:)
withObject:@"alert('Test')" waitUntilDone:NO];

This code is suggested by this:

UIWebView stringByEvaluatingJavaScriptFromString hangs on iOS5.0/5.1 when called using GCD

It says that performSelectorOnMainThread works with stringByEvaluatingJavaScriptFromString. This brings out an alert dialog and it can be closed by clicking the OK button. However, dispatch_async does not work and the dialog freezes and the OK button cannot be pressed.

The question is: How to make the above function of dialog work in Swift? How to convert the code into Swift?

The problem is that performSelectorOnMainThread used in Objective-C is not usable in Swift.

If I directly call the below code in viewDidLoad, the device is suspended with the LaunchScreen:

override func viewDidLoad() {
    super.viewDidLoad()
    myWebView.stringByEvaluatingJavaScriptFromString("alert('test')");

I have tried the Alternative solutions to performSelectorOnMainThread but the results are either a frozen LaunchScreen or a frozen alert dialog.

Can somebody please tell me how to call stringByEvaluatingJavaScriptFromString to display a JavaScript alert dialog in Swift? Thank you.

1 Answer 1

2

I have resolved this issue by loading a web page and call stringByEvaluatingJavaScriptFromString in webViewDidFinishLoad.

The solution is as below:

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var myWebView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        var myPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
        myWebView.delegate = self
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: myPath!)!))
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        myWebView.stringByEvaluatingJavaScriptFromString("alert('Hello')")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.