Hey all, made a quick video showing how to hook up communication between a website (remote/local) and your swift app. Basically it works by making custom url requests that the webview listens for. Swift can respond by running javascript functions. You could even pass data back and forth through JSON if you wanted. Check it out, let me know if you have questions:
Click Here to Download the project files or view them on github.
this was clear as a bell! Thank you so much for your time!
PERFECT! This is exactly what Im looking for. For those using Swift 3 see below that it worked for me
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
// runs slightly before viewDidLoad
override func viewWillAppear(_ animated: Bool) {
if let url = Bundle.main.url(forResource: “web/index”, withExtension: “html”) {
// URL fragment, loaded app vs user touch, want to be able to tell the context of your app
let frag = URL(string: “#FRAG_URL”, relativeTo: url)!
let request = URLRequest(url: frag)
webView.delegate = self //This view controller is webview delegate
webView.loadRequest(request)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Listens for URL requests and accepts them, stops or lets them go through
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print(“request: \(request)”)
if let scheme = request.url?.scheme {
if scheme == “mike” {
print(“we got a mike request: \(scheme)”)
if let result = webView.stringByEvaluatingJavaScript(from: “someJavascriptFunc()”) {
print(“result \(result)”)
}// goes through global scope to find this function. Need to define in html
return false;
}
}
return true
}
}
Its a great post. Crystal clear!!
But is it possible to do the same for a remote webpage too?
My usecase here is:
I do not have the html file[as its remote]. I load a urlrequest. I need to call its one of the js functions. The same could be done very easily in android by just setting the javascript interface, but for iOS I am unable to do that.
The js function actually returns a value and for retrieving that value I should set some key [No idea how to do that 🙁 ] Eg: The js function is something like this:
function getContent() {
if platform == “android” {
android.callSomeOtherFunctionReturningTextValue()
} else if platform == “ios” {
ios.callSomeOtherFunctionReturningTextValue()
}
}
Now this “ios”, I need to set in my webView.
But in your sample there is no need of setting any such thing.
Please help!
Hi Monica,
Did you find solution for above usecase? If you find please help me to solve it out facing the same issue. Thanks in advance.