解决WKWebView加载本地HTML页面ajax请求跨域的问题

一、创建WKWebView的时候设置WKWebViewConfiguration的属性_allowUniversalAccessFromFileURLs为YES,代码如下
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        [configuration setValue:@YES forKey:@"_allowUniversalAccessFromFileURLs"];
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    // 遍历打印私有属性
    unsigned int count;
    Ivar *ivarList = class_copyIvarList([WKWebViewConfiguration class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivarList[i];
        NSLog(@"私有属性%s", ivar_getName(ivar));
    }
    
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"Article" ofType:@"html"];
    NSMutableString* appHtml = [NSMutableString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];

    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [wkWebView loadHTMLString:appHtml baseURL:baseURL];
    [self.view addSubview:wkWebView];
    wkWebView.frame = self.view.bounds;

你可能感兴趣的:(ios开发)