WKWebView evaluate JavaScript return value

后端 未结 6 1404
孤独总比滥情好
孤独总比滥情好 2020-12-04 09:33

I need to change a function to evaluate JavaScript from UIWebView to WKWebView. I need to return result of evaluating in this function.

Now, I am calling:



        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 09:52

    It's possible to use dispatch semaphore. It works on iOS12+

    Example:

        __block NSString *resultString = nil;
        dispatch_semaphore_t sem = dispatch_semaphore_create(0);
        [self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
            if (error == nil) {
                if (result != nil) {
                    resultString = [NSString stringWithFormat:@"%@", result];
                    dispatch_semaphore_signal(sem);
                }
            } else {
                NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
            }
            finished = YES;
        }];
    
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    
        //process resultString here. 
    

提交回复
热议问题