首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在objective-C中从UIWebView迁移到WKWebView后无法加载本地JS文件

在objective-C中从UIWebView迁移到WKWebView后无法加载本地JS文件
EN

Stack Overflow用户
提问于 2021-01-16 13:36:11
回答 1查看 92关注 0票数 0

我的UIWebView是这样的:

代码语言:javascript
复制
 #import <UIKit/UIKit.h>
 #import "DataProvider.h"

@implementation QHArticle
{
    UIWebView *_helperWebView;
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _helperWebView = [[UIWebView alloc] init];
        [_helperWebView loadHTMLString:@"<html><script src='Article.js'></script><body onload='Article.init();'></body></html>" baseURL:[[NSBundle mainBundle] bundleURL]];
    }
    return self;
}

-(NSString*)callJSMethod:(NSString*)method
{
    return [_helperWebView stringByEvaluatingJavaScriptFromString:method];
}

-(NSArray *)listArticle
{
    NSString *json = [self callJSMethod:@"(function() {return JSON.stringify(Article._data.news)})()"];
    ;
    NSError *error;
    NSArray *result = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    return [result subarrayWithRange:NSMakeRange(1, result.count-2)];
}

当我尝试上面的代码时,它工作得很好。但是,代码更改为WKWebView后,如下所示:

代码语言:javascript
复制
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import "DataProvider.h"

@implementation QHArticle
{
    WKWebView *_helperWebView;
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _helperWebView = [[WKWebView alloc] init];
        [_helperWebView loadHTMLString:@"<html><script src='Article.js'></script><body onload='Article.init();'></body></html>" baseURL:[[NSBundle mainBundle] bundleURL]];
    }
    return self;
}

- (NSString *)callJSMethod:(NSString *)method
{
    __block NSString *resultString = nil;
    __block BOOL finished = NO;

    [_helperWebView evaluateJavaScript:method completionHandler:^(id result, NSError *error) {
        if (error == nil) {
            if (result != nil) {
                resultString = [NSString stringWithFormat:@"%@", result];
            }
        } else {
            NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
        }
        finished = YES;
    }];

    while (!finished)
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return resultString;
}

我收到一条错误信息,"evaluateJavaScript错误:……找不到文章对象“,并且在电话上出现白色空白屏幕。我把它移植到WKWebView后仍然找不到问题,请帮助。我只想使用Objective-C,而不是Swift,因为这是遗留代码。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-01-17 08:33:46

WKWebView不会从file:// URL加载任何内容。

首先,将Article.js脚本加载到一个字符串中;您可以使用evaluateJavaScript:来运行它。

要将字符串注入到特定WKWebView加载的每个页面中,您需要创建一个WKUserScript,将其附加到WKUserContentController,然后将其附加到WKWebViewConfiguration

然后使用[WKWebView initWithFrame:configuration:]创建您的WKWebView

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65746804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档