LoginSignup
3
7

More than 5 years have passed since last update.

Swift3のネイティブアプリとJavascriptの通信

Last updated at Posted at 2017-03-11

Javascript作成

適当にサーバーに配置

communication.html
<html>
<head>
<tite></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//こちらの関数はSwiftから呼ばれる
function fromSwift() {
    $('p').text('Swiftから呼ばれてるよ!!!!');
}

(function() {
    $(window).load(function() {
       //window.location.hashは、URLの「#」記号の後の部分を取得、もしくは、設定するプロパティ。これでSwiftからのデータ取得
       var swiftData = window.location.hash;
       $('p').text('Swiftからもらった:' + swiftData);

       $('.btn').on('click', function() {
            //以下のURLをSwiftから取得
            window.location = "fromJavascript://hello";
       });
    });
})(jQuery)
</script>
<body>
<h1>Swift3のネイティブアプリとJavascritpの通信</h1>
<p></p>
<div class="container">
<button class="btn">Swiftにイベント送信</button>
</div>
</body>
</html>

Swift ViewController

Swiftソース

ViewController.swift
import UIKit
class ViewController: UIViewController , UIWebViewDelegate{

    @IBOutlet weak var web: UIWebView!


    override func viewDidLoad() {
        super.viewDidLoad()
        //LocalサーバーURL
        let url = URL(string: "http://192.168.11.11")
        //#を追加した文字列はwindow.location.hashから取得できる
        let insertUrl = URL(string: "#HelloJavascrpt", relativeTo: url)
        let urlRequest = URLRequest(url: insertUrl!)
        web.delegate = self
        web.loadRequest(urlRequest)
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if let scheme = request.url?.scheme {
            if scheme == "fromjavascript" {

                //Javascriptのメッソドを呼び出す
                web.stringByEvaluatingJavaScript(from: "fromSwift()")
                return false

            }
        }
        return true
    }

}

実行結果

HelloJavascript文字列はSwiftから送られた文字列

スクリーンショット 2017-03-11 13.03.53.png

Swiftにイベント送信クリック後、Swiftからjavascriptメッソド呼び出す

スクリーンショット 2017-03-11 13.04.07.png

3
7
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
3
7