WKWebView与本地文件

时间:2014-12-01 17:30:02

标签: ios objective-c wkwebview

我正在使用本地文件测试WKWebView,该文件在模拟器中工作,但它无法在设备中运行

 @interface EDPresentationViewController ()<WKNavigationDelegate,WKScriptMessageHandler>


     @property(nonatomic,strong)WKWebView *webView;

     @property(nonatomic,strong)EDPresentationController *presentationController;

 @end


@implementation EDPresentationViewController

-(void)viewDidLoad
{
    [super viewDidLoad];

    self.presentationController = [[EDPresentationController alloc]init];

    WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc]init];
    self.webView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:webConfiguration];

    NSURL *presentationFolder = [self.presentationController url];
    NSURLRequest *request = [NSURLRequest requestWithURL:presentationFolder];

    [self.webView loadRequest:request];
}

我从以下网址授予网址:

    NSURL *presentationFolder = [self.presentationController url];

没问题,因为我用UIWebview测试了相同的代码并且有效!

我总是得到同样的错误:

Could not create a sandbox extension for '/'

这不起作用,我想它会在Objective-C中起作用,就像在swift中一样

iOS Webkit not working on device, but works on simulator at swift

任何想法都将不胜感激,谢谢


更新2-12-2014

我发现这可能是iOS 8.1中的一个错误,可能会在8.2中修复

https://devforums.apple.com/thread/247777?start=25&tstart=0

我已经测试过将文件移动到临时文件夹,但我没有收到任何错误,但webView只是空的。

我已经使用UIWebView测试了相同的代码(临时文件夹)并且工作正常!

另外,我试过这个:

https://stackoverflow.com/a/26054170/426180

正如我所知,这是有效的,因为css和javascript被嵌入到html中。

2 个答案:

答案 0 :(得分:4)

尝试具有非常小的嵌入式http服务器的XWebView。它比GCDWebServer小得多。通过扩展名添加loadFileURL:allowingReadAccessToURL方法,因此您不了解服务器。

答案 1 :(得分:1)

这就像一个魅力......

@interface ViewController () <WKScriptMessageHandler, WKNavigationDelegate>

...

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];

configuration.userContentController = controller;
[configuration.preferences setValue:@"TRUE" forKey:@"allowFileAccessFromFileURLs"];
self.webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:configuration];
self.webView.navigationDelegate = self;
// Also if you'd have bouncing problem
self.webView.scrollView.bounces = false;
self.webView.scrollView.alwaysBounceVertical = false;
[self.view addSubview:self.webView];

NSString* productURL = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"htmlapp/home.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:productURL]];
[self.webView loadRequest:request];