我正在使用一个名为DSBridge https://github.com/wendux/DSBridge-IOS将移动应用程序(在本例中为 iOS 代码)连接到包含我的应用程序主要逻辑的 javascript 代码。这涉及在不可见的 WKWebView 上运行 JavaScript。
我的 JavaScript 代码需要调用本机 iOS 应用程序中的一个方法,该方法需要异步执行(以免阻塞 UI),为此,我在 JavaScript 中使用回调,并在本机中使用completionHandler。
我的 Objective C 函数如下:
- (void)read:(NSDictionary *) args :(JSCallback) completionHandler{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSLog(@"In Read");
while(self->connection != NULL) {
if([self->connection isMessageAvailable]) {
[self->connection messageRetrieved];
NSLog(@"Message Received in ViewController");
completionHandler([self->connection getMessage], YES);
}
}
});
}
这是从我的 JavaScript 中调用的:
function read() {
data = "reading";
dsBridge.call("read", data, function (read_result) {
console.log("read_result = ", read_result)
return read_result;
});
}
问题在于 JavaScript,一旦本机应用程序返回消息,我需要 JavaScript 函数“read”返回值“read_result”。现在我的代码正在调用目标 C,它正在正确执行并将所需的值返回到 JavaScript 中的回调函数,但 JavaScript 函数“读取”已经完成,没有返回值。
有没有办法让我停止 JavaScript 直到回调完成?
您可以将回调传递给read()
函数并在底层 Objective-C 代码返回时调用它
function read(clb) {
data = "reading";
dsBridge.call("read", data, function (read_result) {
clb(read_result);
});
}
和你的来电者
read(res => {
//result available here
console.log(res);
})
或者使用 Promise
function read() {
data = "reading";
return new Promise(resolve => {
dsBridge.call("read", data, function (read_result) {
resolve(read_result);
});
});
}
和来电者
read()
.then(res => {
//result available here
console.log(res);
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)