WebViewJavascriptBridge 使用 js調iOS原生代碼
阿新 • • 發佈:2017-05-04
創建 smi creat color web var key urn cti
js代碼和原生ios代碼進行交互使用WebViewJavascriptBridge非常簡化了我們的操作特別是在ios這邊
js 掉用ios原生代碼時要註意的幾個事項:
1、js和ios定義好相互調用的各自要掉用對方的函數名
2、ios中的操作:
a、創建一個bridge對象
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
b、註冊ios中給js回調的代碼
[self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"ObjC Echo called with: %@", data); responseCallback(data); }];
b1、或者調用js中的方法 [self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) { NSLog(@"ObjC received response: %@", responseData); }];
3、js代碼中的操作:
1、將一下函數拷貝到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 = ‘https://__bridge_loaded__‘;
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
2、在以下函數中做你的所有要和app交互的動作並且在函數中register對應的時間,需要註意的是如果你的執行函數在這個func外面的話,要在這個函數的回調當中手動掉用你要掉用的執行函數。案例:我們做js的同事認為數據變了後js頁面會自動刷新,然而並沒有,所以這個過程最好能夠在回調的過程中顯示掉用一下。
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) {
anotherOperation()
console.log("JS received response:", responseData) })
})
func anotherOperation(){
}
WebViewJavascriptBridge 使用 js調iOS原生代碼