Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What is going on with this article?
@HavenSpring

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

More than 3 years have passed since last update.

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

7
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
zozotech
70億人のファッションを技術の力で変えていく

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
7
Help us understand the problem. What is going on with this article?