js調用ios的方法


摘要

在做h5應用的時,有時有些功能js並不能實現的特別完美。比如下載進度條或上傳文件進度等。如果能調用ios或者android的方法,實現進度,以及文件上傳或者下載列表更好一些。如果使用第三方的js插件。又要考慮到ios和android的版本問題,支持上並不是特別完美。

WebViewJavascriptBridge

WebViewJavascriptBridge是一個開源的ios項目,通過橋的方式obc調用js或者js調用obc方法。項目地址:WebViewJavascriptBridge

用法

1.Import the header file and declare an ivar property:

#import "WebViewJavascriptBridge.h"
....
@property WebViewJavascriptBridge* bridge;

2.Instantiate WebViewJavascriptBridge with a UIWebView (iOS) or WebView (OSX):

self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];

3.Register a handler in ObjC, and call a JS handler:

[self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"ObjC Echo called with: %@", data);
    responseCallback(data);
}];
[self.bridge callHandler:@"JS Echo" responseCallback:^(id responseData) {
    NSLog(@"ObjC received response: %@", responseData);
}];

4.Copy and paste setupWebViewJavascriptBridge into your JS:

function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}

5.Finally, call setupWebViewJavascriptBridge and then use the bridge to register handlers and call ObjC handlers:

setupWebViewJavascriptBridge(function(bridge) {

    /* Initialize your app here */

    bridge.registerHandler('JS Echo', function(data, responseCallback) {
        console.log("JS Echo called with:", data)
        responseCallback(data)
    })
    bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
        console.log("JS received response:", responseData)
    })
})

通過第4和5步驟,js就可以調用objc的方法了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM