【问题标题】:Loading local file in WKWebView doesn't working in device在 WKWebView 中加载本地文件在设备中不起作用
【发布时间】:2016-01-05 04:50:01
【问题描述】:

我无法在 wkwebview 中加载本地 epub 文件(从文档目录)。它在模拟器中工作,但不在设备中。我从here 了解到这是 iOS 8 的错误。 iOS 8 已经解决了吗?请帮助我该怎么办。我在设备中遇到错误 -

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

这里是代码 sn-p -

-(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];
}

【问题讨论】:

    标签: ios objective-c ios8 wkwebview local-files


    【解决方案1】:

    一年多后我找到了解决方案,我们需要使用 loadFileURL 来访问本地资源,这是我使用 WKWebView 的工作代码,加上我使用 loadHTMLString 而不是加载。 vistaweb 在我的 WebView 顺便说一句

    感谢这个答案:Load local web files & resources in WKWebView

    对不起,但在 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)")
            }
    

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2020-09-25
      • 2018-09-13
      • 2017-05-24
      • 1970-01-01
      相关资源
      最近更新 更多