ehhhuang
ehhhuang

Reputation: 117

How to display a JavaScript alert dialog in UIWebView using stringByEvaluatingJavaScriptFromString but not performSelectorOnMainThread in Swift?

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.

Upvotes: 1

Views: 5935

Answers (1)

ehhhuang
ehhhuang

Reputation: 117

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()
    }
}

Upvotes: 2

Related Questions