Giter Site home page Giter Site logo

sdbridgeswift's Introduction

language language Support  CocoaPods CocoaPods

SDBridgeOC is here.

If your h5 partner confused about how to deal with iOS and Android. This Demo maybe help.

YouTube video is here.

视频接入教程和常见问题都在这里(遇到问题一定要看哦😯 ).

Installation with CocoaPods

Add this to your podfile and run pod install to install:

pod 'SDBridgeSwift', '~> 1.1.0'

If you can't find the last version, maybe you need to update local pod repo.

pod repo update

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding SDBridgeSwift as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/SDBridge/SDBridgeSwift", .upToNextMajor(from: "1.1.0"))
]

Manual installation

Drag the WebViewJavascriptBridge folder into your project.

In the dialog that appears, uncheck "Copy items into destination group's folder" and select "Create groups for any folders".

Usage

var bridge: WebViewJavascriptBridge!
  1. Instantiate bridge with a WKWebView:
func setupView() {
        title = "WebViewController"
        view.backgroundColor = .white
        view.addSubview(webView)
        bridge = WebViewJavascriptBridge(webView: webView)
        
        // This can get javascript console.log
        bridge.consolePipeClosure = { water in
            guard let jsConsoleLog = water else {
                print("Javascript console.log give native is nil!")
                return
            }
            print("Next line is Javascript console.log----->>>>>>>")
            print(jsConsoleLog)
        }
        // This register for javascript call
        bridge.register(handlerName: "DeviceLoadJavascriptSuccess") { (parameters, callback) in
            let data = ["result":"iOS"]
            callback?(data)
        }
        let fileURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "Demo", ofType: "html")!)
        let request = URLRequest.init(url: fileURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15.0)
        webView.navigationDelegate = self;
        // Loading html in local ,This way maybe meet cross domain. So You should not forget to set
        // webView.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        // If you loading remote web server,That can be ignored.
        webView.load(request)
        view.addSubview(callJavascriptBtn)
        view.addSubview(callJSAsyncBtn)
    }
  1. In Swift, and call a Javascript Sync function:
  @objc func callSyncFunction(_ sender:UIButton){
    let data = ["iOSKey": "iOSValue"]
    bridge.call(handlerName: "GetToken", data: data) { responseData in
        guard let res = responseData else {
            print("Javascript console.log give native is nil!")
            return
        }
        print(res)
    }
    }
  1. In Swift, and call a Javascript Async function:
  @objc func callJSAsyncFunction(_ sender:UIButton){
        let data = ["iOSKey": "iOSValue"]
        bridge.call(handlerName: "AsyncCall", data: data) { responseData in
            guard let res = responseData else {
                print("Javascript console.log give native is nil!")
                return
            }
            print(res)
        }
    }
  1. In javascript file or typescript and html file like :
<script>
    console.log("1111111111111");
    const bridge = window.WebViewJavascriptBridge;
    // JS tries to call the native method to judge whether it has been loaded successfully and let itself know whether its user is in android app or IOS app
    bridge.callHandler('DeviceLoadJavascriptSuccess', {key: 'JSValue'}, function(response) {
        let result = response.result
        if (result === "iOS") {
        console.log("Javascript was loaded by IOS and successfully loaded.");
        window.iOSLoadJSSuccess = true;
        } else if (result === "Android") {
        console.log("Javascript was loaded by Android and successfully loaded.");
        window.AndroidLoadJSSuccess = true;
       }
    });
    // JS register method is called by native
    bridge.registerHandler('GetToken', function(data, responseCallback) {
        console.log(data);
        let result = {token: "I am javascript's token"}
        //JS gets the data and returns it to the native
        responseCallback(result)
    });
    
    bridge.registerHandler('AsyncCall', function(data, responseCallback) {
        console.log(data);
        //Call await function must with  (async () => {})();
        (async () => {
            const callback = await generatorLogNumber(1);
            let result = {token: callback};
            responseCallback(result);
        })();
    });

    function generatorLogNumber(n){
        return new Promise(res => {
            setTimeout(() => {
            res("Javascript async/await callback Ok");
              }, 1000);
        });
     }
</script>

History version update ?

v1.0.4

1.Swift can get console.log Multi parameter.

v1.0.5

1.Optimize code.

License

SDBridgeSwift is released under the MIT license. See LICENSE for details.

sdbridgeswift's People

Contributors

housenkui avatar charles3447 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.