Open ghost opened 7 years ago
@kantsoft: what did you mean "use the webView declared as property in the sayGreeting method" ? sayGreeting method is a method of Swift, you can use swift to declare some local variable to use. In my example: sayGreeting is used to call from javascript. Let try to run my demo to understand it.
I'll show you the original source you're working on.
import Foundation import JavaScriptCore import UIKit
@objc protocol MyExport : JSExport { func updateUserInfo(_ userid : String) func callbackGetSharedPreferences(userid:String) }
class ViewController: UIViewController,MyExport {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL (string: "url :)")
webView.delegate = self
let requestObj = URLRequest(url: url! as URL)
webView.loadRequest(requestObj)
webView.addJavascriptInterface(ViewController(), forKey: "ios");
print("viewDidLoad Function Finished")
}
func updateUserInfo(_ userid: String) {
print("JS Interface works!")
self.callbackGetSharedPreferences(userid: userid)
}
func callbackGetSharedPreferences(userid: String)
{
print(userid)
print(self.webView)
self.webView?.stringByEvaluatingJavaScript(from: "callbackGetSharedPreferences('test1')")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Below is javascript.
jQuery(document).ready(function($) { ios.getSharedPreferences(); });
function callbackGetSharedPreferences(msg){ alert(msg); }
ios.getSharedPreferences works fine. However, the callbackGetSharedPreferences does not trigger an alert. The webView Property seems to have a problem and I do not know how to do this.
thank you :)
@kantsoft you are wrong: webView.addJavascriptInterface(ViewController(), forKey: "ios"); By this way, you created a new instance of ViewController without webView object.
--> correct your code: webView.addJavascriptInterface(self, forKey: "ios");
Thank You :) Happy Coding
@kantsoft I just update project. Try it :)
Hi I have a problem using the ur code in addJavascriptInterface() where UIViewController is subview. Let me explain more detail about it. I have and application where the UIView (with webview) is a addsubview of parent view.
So in my subview's webView added javascript interface. So when the UI launched the HTML button seem not fire to the JSInterface's function. So i suspect the add interface is not set to current webview object?
Test I had create a button where call showAlert, it work well and even at webview Delegate webViewDidFinishLoad
So can u suggest any idea about this problem?
I'm a korea understand English is poor. :)
JSInterface class in..
ViewController
@IBOutlet weak var webView: UIWebView!
How do I use the webView declared as a property in the sayGreeting method?