8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WebViewのjavascriptからViewControllerのfunctionを呼び出す方法

Last updated at Posted at 2015-09-18

Problem

WebViewにロードしたjavascriptから、ViewControllerのfunctionを呼び出したい

Solution

サンプルコード

  • サンプルコードで使用しているライブラリ
  • SwiftFilePath: NSFileManagerのWrapperなので、必要ではない

WebViewEvent.js

open("native://anchorClicked?anchorUrl=" + anchorUrl)

WebViewController.swift

class WebViewController: UIViewController, UIWebViewDelegate {

  @IBOutlet weak var webView: UIWebView!

...(省略)...

  func getJavascriptString() -> String {
    let path = NSBundle.mainBundle().pathForResource("WebViewEvent", ofType: "js")!
    return Path(path).readString()!
  }

  func webViewDidFinishLoad(webView: UIWebView) {
    self.webView.stringByEvaluatingJavaScriptFromString(getJavascriptString())
  }

  func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    var url = request.URL!.standardizedURL
    if (url?.scheme == "native") {
      if url?.host == "anchorClicked" {
        let queryStrings = getQueryStrings(url!.query)
        anchorClicked(queryString)
      }
    }
  }

  func anchorClicked(queryString: [String: String]) {
    println(queryString["anchorUrl"])
  }
  
  func getQueryStrings(query: String?) -> [String: String] {
    var queryStrings = [String: String]()
    if let query = query {
      for qs in query.componentsSeparatedByString("&") {
        // Get the parameter name
        let key = qs.componentsSeparatedByString("=")[0]
        // Get the parameter value
        var value = qs.componentsSeparatedByString("=")[1]
        value = value.stringByReplacingOccurrencesOfString("+", withString: " ")
        value = value.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        
        queryStrings[key] = value
      }
    }
    return queryStrings
  }
  
}


8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?