Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get posting from html? #5

Open
starlight173 opened this issue Dec 28, 2017 · 1 comment
Open

How to get posting from html? #5

starlight173 opened this issue Dec 28, 2017 · 1 comment

Comments

@starlight173
Copy link

starlight173 commented Dec 28, 2017

I'm looking around on you library and testing some code.
HTML code:

window.bridge.on('login', (parameters) => {
    window.bridge.post('alert', {'title': 'This is alert title', 'message': 'This is alert message'})
})
function testAlert() {
	window.bridge.post('alert', {'title': 'This is alert title', 'message': 'This is alert message'})
}

Swift code:

 if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
            webView.load(URLRequest(url: url))
}
webView.bridge.printScriptMessageAutomatically = true
webView.bridge.register({ (parameters, completion) in
      print("print - ", parameters?["message"] ?? "")
}, for: "print")
        
 webView.bridge.register({ (parameters, completion) in
    print("print - ", parameters?["message"] ?? "")
}, for: "alert")

// test posting in HTML
  webView.bridge.post(action: "login", parameters: nil)
        
// I wanna run testAlert in index.html
 webView.bridge.evaluate("testAlert()", completion: { (results, error) in

How to get the callback on Swift work? How can I call testAlert from Swift code?
Thanks.

@lovesunstar
Copy link
Owner

  1. you can simply call method webView.bridge.evaluate("testAlert()") if you want to call testAlert from Swift code, but you should not call it in viewDidLoad (webview doesn't load at that time, try to call it after 2 seconds or after the callback webViewDidFinishLoad).

  2. if you want to listen callback from swift code, you should Notify using completion to callback when register actions.

webView.bridge.register({ [weak self] (parameters, completion) in
    guard let strongSelf = self, let parameters = parameters else { return }
    // THIS IS IMPORTANT
    completion(.success(["button_index": 1]))
}, for: "alert")

and a handler when post message

function testAlert() {
    window.bridge.post('alert', {'title': 'This is alert title', 'message': 'This is alert message'}, (results, error)=>{
    // THIS IS IMPORTANT , 
    })
}
  1. callback on swift when call js is just the return value from javascript.
function foo() {
    return {"foo": "bar"}
}
webView.bridge.evaluate("testAlert()", completion:(result, error) {
    // result is {"foo": "bar"}
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants