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.