swift 尝试使用wkwebview下载文件时didFailProvisionalLoadForFrame

mfpqipee  于 2023-08-02  发布在  Swift
关注(0)|答案(2)|浏览(259)

我有一个WKWebView,在我的页面上有一个按钮,它可以生成一个PDF,然后提供下载。所以当我在任何浏览器中单击它时,它会立即开始下载。我也想在wkwebview上看到这个。我做了一些研究并实现了以下内容:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    if !navigationResponse.canShowMIMEType {
        decisionHandler(.download)
    } else {
        decisionHandler(.allow)
    }
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
    if navigationAction.shouldPerformDownload {
        decisionHandler(.download, preferences)
    } else {
        decisionHandler(.allow, preferences)
    }
}

func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
    download.delegate = self
}

func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
    download.delegate = self
}

func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let url = dir.appendingPathComponent(suggestedFilename)
        completionHandler(url)
    }
    
}

字符串
但当我点击它时,什么也没有发生,控制台显示以下错误:

WebPageProxy::didFailProvisionalLoadForFrame: frameID=3, domain=WebKitErrorDomain, code=102, isMainFrame=1

wixjitnu

wixjitnu1#

尝试添加以下delegate函数:

func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
    print("webkit download fail: \(error.localizedDescription)")
}

字符串
如果您收到消息“操作无法完成。(NSURLErrorDomain error-3000.)",问题很可能是您的下载目标目录中存在同名的现有文件。更多信息可以在here中找到。
您可能还需要添加以下delegate函数,以确认您的文件是否已实际下载:

func downloadDidFinish(_ download: WKDownload) {
    print("webkit download finished!")
}

njthzxwz

njthzxwz2#

我得到了同样的错误

WebPageProxy::didFailProvisionalLoadForFrame: frameID=3, domain=WebKitErrorDomain, code=102, isMainFrame=1

字符串
结果是,我在WKURLSchemeHandler类中遇到了一个错误,它在响应中设置了一个错误的minetype

相关问题