Loading local file in WKWebView doesn't working in device

北战南征 提交于 2020-05-29 07:40:23

问题


I can't load local epub file (from document directory) in wkwebview. It's working in simulator but not in device. I learned that it's a bug for iOS 8 from here. Is it already solved for iOS 8 ? Please help me what should i do. I got error in device as -

The operation couldn't be completed. (KCFErrorDomainCFNetwork error 1.)

Here is code snippet -

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.webView removeObserver:self forKeyPath:@"loading"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.progressView setProgress:0.0f animated:NO];

    if ([self.documentDirectory checkEpubFileIfExistsAtPath:self.epubFolder]) {

        NSString *filePath = [NSString stringWithFormat:@"%@/%@/%@/OEBPS/%@", [self.documentDirectory getDocumentsDirectory], self.epubFolder, self.epubName, [_html_link substringToIndex:[_html_link rangeOfString:@"#"].location]];

        //Loading webview with progress bar action
        if ([_html_link rangeOfString:@"#"].location != NSNotFound) {

            self.tag = [_html_link substringFromIndex:[_html_link rangeOfString:@"#"].location];
            NSURL *URL = [NSURL fileURLWithPath:filePath];
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            [self.webView loadRequest:request];
        }

    } else {

        NSDictionary *object = [self.alertMessages getMessageObj:@"translationNotAvailable"];
        [self presentViewController:[self.alertController alertWithCustomOkayAction:[object objectForKey:@"title"] message:[object objectForKey:@"msg"] callback:^(void) {

            [self dismissViewControllerAnimated:YES completion:nil];

        }] animated:YES completion:nil];
    }
}

//Constraints for Web View
- (void) setConstraintsForWebView {
    [self.webView setTranslatesAutoresizingMaskIntoConstraints:NO];

    WKWebView *webView = self.webView;
    UIProgressView *progressView = self.progressView;
    UIToolbar *toolBar = self.toolBar;

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[webView]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[progressView]-0-[webView]-[toolBar]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(progressView, webView, toolBar)]];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //Do any additional setup after loading the view.
    self.alertController = [AlertController new];
    self.alertMessages = [AlertMessages new];
    self.documentDirectory = [DocumentDirectory new];
    self.languageController = [LanguageController new];

    //Set observer for webview load
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero];
    self.webView.navigationDelegate = self;
    [self.view insertSubview:self.webView belowSubview:self.progressView];
    [self setConstraintsForWebView];

}

#pragma mark KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"loading"]) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:self.webView.loading];
    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.hidden = self.webView.estimatedProgress == 1;
        self.progressView.progress = self.webView.estimatedProgress;
    }
}


#pragma mark Web view navigation delegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self.progressView setProgress:0.0f animated:NO];
    if (self.tag) {
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"window.location.hash='%@'", self.tag] completionHandler:nil];
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {

    [self presentViewController:[self.alertController alertWithAction:@"Error!" message:error.localizedDescription] animated:YES completion:nil];
}

回答1:


After more than 1 year I found the solution, we need to use loadFileURL to have access to the local resources, here is my working code with WKWebView, plus instead of load I use loadHTMLString. vistaweb in my WebView BTW

Thanks to this answer : Load local web files & resources in WKWebView

Sorry but is in Swift

        do {

            let local = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
            // Loading: Library/Caches/repositorioLocal/esferas/znvUifZhH8mIDr09cX8j/index.html
            let resourceFolder = "repositorioLocal/esferas/znvUifZhH8mIDr09cX8j"
            let fileToLoad = "index.html"

            let urlToFolder = URL(fileURLWithPath: local).appendingPathComponent(resourceFolder)
            let urlToFile =  URL(fileURLWithPath: local).appendingPathComponent(resourceFolder).appendingPathComponent(fileToLoad)
            let fileContent = try String(contentsOf: urlToFile)

            let webConfiguration = WKWebViewConfiguration()
            webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
            webConfiguration.allowsInlineMediaPlayback = true

            vistaweb = WKWebView(frame: self.view.frame, configuration: webConfiguration)
            self.vistaweb.loadFileURL(urlToFolder, allowingReadAccessTo: urlToFolder)
            self.vistaweb.loadHTMLString(fileContent, baseURL: urlToFile)
            self.view.addSubview(vistaweb)

        } catch let error {
            print("Error: \(error.localizedDescription)")
        }


来源:https://stackoverflow.com/questions/34604354/loading-local-file-in-wkwebview-doesnt-working-in-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!