Simple Design for Swift bridge with Javascript. Also can get javascript console.log.

Overview

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.

bilibili Video is here.

Installation with CocoaPods

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

pod 'SDBridgeSwift', '~> 1.0.5'

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.0.7"))
]

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>

Global support for free

WhatsApp: SDBridgeSwift Support

Telegram: SDBridgeSwift Support

WeChat Group:

Email: [email protected]

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.

You might also like...
A custom logger implementation and Task Local helper for swift-log

LGNLog A custom logger implementation and TaskLocal helper for Swift-Log. Why and how This package provides two and a half things (and a small bonus):

A logging backend for swift-log that sends logging messages to Logstash (eg. the ELK stack)
A logging backend for swift-log that sends logging messages to Logstash (eg. the ELK stack)

LoggingELK LoggingELK is a logging backend library for Apple's swift-log The LoggingELK library provides a logging backend for Apple's apple/swift-log

🍯 Awesome log aggregator for iOS
🍯 Awesome log aggregator for iOS

🍯 Awesome log aggregator for iOS

Puree is a log collector which provides some features like below
Puree is a log collector which provides some features like below

Puree Description Puree is a log collector which provides some features like below Filtering: Enable to interrupt process before sending log. You can

Automate box any value! Print log without any format control symbol! Change debug habit thoroughly!

LxDBAnything Automate box any value! Print log without any format control symbol! Change debug habit thoroughly! Installation You only need drag LxD

A log should tell a story, not drown the reader in irrelevance.

StoryTeller A log should tell a story, not drown the reader in irrelevance Story Teller is an advanced logging framework that takes an entirely differ

Log messages to text files and share them by email or other way.
Log messages to text files and share them by email or other way.

LogToFiles How to log messages to text files and share them by email or share center. 1 - Add the Log.swift file to your App 2 - Just log the messages

Simply, Logify provides instant colorful logs to improve log tracking and bug tracing
Simply, Logify provides instant colorful logs to improve log tracking and bug tracing

Logify Simply, Logify provides instant colorful logs to improve log tracking and bug tracing. Why I need to use Logify? As discussed before in a lot o

100 Days of SwiftUI log

100DaysOfSwiftUI 100 Days of SwiftUI log Table of Contents Day 1: variables, constants, strings, and numbers Day 1 Variables store values and can be c

Owner
null
📱💬🚦 TinyConsole is a micro-console that can help you log and display information inside an iOS application, where having a connection to a development computer is not possible.

TinyConsole TinyConsole is a tiny log console to display information while using your iOS app and written in Swift. Usage Wrap your Main ViewControlle

Devran Cosmo Uenal 2k Jan 3, 2023
A Swift-based API for reading from & writing to the Apple System Log (more commonly known somewhat inaccurately as "the console")

CleanroomASL Notice: CleanroomASL is no longer supported The Apple System Log facility has been deprecated by Apple. As a result, we've deprecated Cle

Gilt Tech 62 Jan 29, 2022
Gedatsu provide readable format about AutoLayout error console log

Gedatsu Gedatsu provide readable format about AutoLayout error console log Abstract At runtime Gedatsu hooks console log and formats it to human reada

bannzai 520 Jan 6, 2023
Customizable Console UI overlay with debug log on top of your iOS App

AEConsole Customizable Console UI overlay with debug log on top of your iOS App AEConsole is built on top of AELog, so you should probably see that fi

Marko Tadić 142 Dec 21, 2022
Gedatsu provide readable format about AutoLayout error console log

Gedatsu Gedatsu provide readable format about AutoLayout error console log Abstract At runtime Gedatsu hooks console log and formats it to human reada

bannzai 475 Jun 24, 2021
Log every incoming notification to view them again later, also includes attachments and advanced settings to configure

Vē Natively integrated notification logger Installation Add this repository to your package manager

alexandra 43 Dec 25, 2022
Delightful console output for Swift developers.

Rainbow adds text color, background color and style for console and command line output in Swift. It is born for cross-platform software logging in te

Wei Wang 1.7k Dec 31, 2022
XCLog is a Swift extension that helps you print something in console when debugging your projects.

XCLog XCLog is a Swift extension that helps you print something in console when debugging your projects. Installation Open Xcode > File > Add Packages

null 1 Jan 9, 2022
Styling and coloring your XCTest logs on Xcode Console

XLTestLog Notes with Xcode 8 and XLTestLog Since Xcode 8 killed XcodeColors, the current way using XCTestLog on Xcode 8 is just plain texts with emoji

Xaree Lee 58 Feb 2, 2022
JustLog brings logging on iOS to the next level. It supports console, file and remote Logstash logging via TCP socket with no effort. Support for logz.io available.

JustLog JustLog takes logging on iOS to the next level. It supports console, file and remote Logstash logging via TCP socket with no effort. Support f

Just Eat 509 Dec 10, 2022