4
4

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.

ゆるふわにUIWebViewでJavaScriptイベントをひろってみる

Last updated at Posted at 2016-07-22

ソースコード

JavaScript

私のサーバ側でこんな感じに返ってくるようにしてあります。
JSブリッジ! とかいうふざけたボタンがあるのでそれを押すと稼働します!

index.js
location.href = 'app-callback://views?name=success&age=6';

Swift

ViewController.swift
//
//  ViewController.swift
//  JsBridge
//
//  Created by nnsnodnb on 2016/07/23.
//  Copyright © 2016年 nnsnodnb. All rights reserved.
//

import UIKit

// MARK: - UIViewController
class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    // MARK: - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    private func setup() {
        webView.delegate = self
        let url = NSURL(string: "https://nnsnodnb.moe/js-bridge/")
        if let request = url {
            let requestUrl = NSURLRequest(URL: request)
            webView.loadRequest(requestUrl)
        }
    }
    
    private func showAlert() {
        let alert: UIAlertController = UIAlertController(title: "成功!",
                                                         message: nil,
                                                         preferredStyle: .Alert)
        let okButton = UIAlertAction(title: "OK",
                                     style: .Default,
                                     handler: nil)
        
        alert.addAction(okButton)
        
        presentViewController(alert, animated: true, completion: nil)
    }
}

// MARK: - UIWebViewDelegate
extension ViewController: UIWebViewDelegate {

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

        if let scheme = request.URL?.scheme where scheme.hasPrefix("http") {
            return true
        }
        
        if let action = request.URL?.description,
            let query = request.URL?.query {
            
            let queryDicitionary = QueryParser.queryDictionary(query)
            
            if action.hasPrefix("app-callback://views") {
                if queryDicitionary["name"] == "success" {
                    print("Success")
                    showAlert()
                }
            }
            return false
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
}

パラメタをパースするためのクラス

QueryParser.swift
import Foundation

class QueryParser {

    class func queryDictionary(query: String) -> [String:String] {

        var queries = [String: String]()
        let pairs = query.componentsSeparatedByString("&");

        for pair in pairs {
            let elements = pair.componentsSeparatedByString("=")
            let key = elements[0].stringByRemovingPercentEncoding
            let value = elements[1].stringByRemovingPercentEncoding

            if let key = key, value = value {
                quereies[key] = value
            }
        }
        return queries
    }
}

Swift始めたばかりで全然できないですが、これを利用してアプリ側のViewControllerに移動できたりするのは楽しいです!
(Obj-Cではできたけど、SwiftだとUnwrap関係で怒られた。ダレカタスケテェェェ---!!)
一応書いておくと下のようなコードを書きました。

画面遷移
...
if queryDicitionary["name"] == "success" {
    let vc: SuccessViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SuccessViewController") as! SuccessViewController
    self.presentViewController(vc, animated: true, completion: nil)
}
...

叫び

上司の後に出したので丸パクリになってしまった感がすごいですが、同じソースコード(Obj-C)を見てたので仕方ないですよね?震え((((;゚Д゚))))

上司様の記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?