wkwebview不称呼`di di di di di di di di finish`委托法
我正在实现一个自定义 WKWebViewClass。 init() 将 navigationDelegate 设置为 self,并开始加载。但是,didFinish 从未被调用。我收到 didFailProvisionalNavigation 错误
didFailProvisionalNavigation 操作无法完成。 (kCFErrorDomainCFNetwork 错误 1。)
let pdf = generatePDF(frame: view.bounds)
view.addSubview(pdf)
pdf.startGenerating(){
}
public class generatePDF: WKWebView, WKUIDelegate, WKNavigationDelegate {
static var observer: NSObjectProtocol!
public override init(frame: CGRect, configuration: WKWebViewConfiguration = WKWebViewConfiguration()) {
super.init(frame: frame, configuration: configuration)
doInit()
}
func doInit() {
DocMakerInfo.isDoneLoading = false
self.navigationDelegate = self
self.uiDelegate = self
print("didInit")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func startGenerating(completion: @escaping () -> Void) {
openDocument(fileName: DocMakerInfo.fileName, extenstion: DocMakerInfo.extenstion)
completion()
}
private func openDocument(fileName:String, extenstion:String){
do {
#if targetEnvironment(macCatalyst)
let homeDirURL = (NSSearchPathForDirectoriesInDomains(.downloadsDirectory, .userDomainMask, true) as [String]).first!
let docURL = URL(string: "file://\(homeDirURL)/")!
#else
let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
#endif
let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)
for url in contents {
#if targetEnvironment(macCatalyst)
if url.description.contains("/\(fileName)\(extenstion)") {
webView.frame = view.bounds
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
let dataFileMimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
do {
let fileContent = try Data(contentsOf: url)
self.load(fileContent, mimeType: dataFileMimeType, characterEncodingName: "", baseURL: url)
//self.view = self.webView
Dynamic.NSWorkspace.sharedWorkspace.activateFileViewerSelectingURLs([url])
} catch let error {
print(error.localizedDescription)
}
}
#else
if url.description.contains("\(fileName)\(extenstion)") {
self.bounds = CGRect(x: 0, y: 0, width: 700.00, height: 1000.00)
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
self.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
self.load(URLRequest(url: fileURL))
print("startedLoading")
}
#endif
}
} catch {
Swift.print(#file, #function, "could not locate \(extenstion) file !!!!!!!")
}
}
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("didStartProvisionalNavigation")
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation", error.localizedDescription)
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail", error.localizedDescription)
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("doneloading")
let config = WKPDFConfiguration()
webView.createPDF(configuration: config) { result in
switch result {
case .success(let data):
#if targetEnvironment(macCatalyst)
#else
let destURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(DocMakerInfo.fileName).pdf")
do {
try data.write(to: destURL)
print("createpdf")
DocMakerInfo.isDoneLoading = true
} catch {
print("didFinish", error)
}
#endif
case .failure(let error):
print("create pdf failure: \(error)")
}
}
}
}
I am implementing a custom WKWebViewClass. The init() is settings the navigationDelegate to self, and starting the load. However, didFinish is never called. I am getting a didFailProvisionalNavigation error
didFailProvisionalNavigation The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 1.)
let pdf = generatePDF(frame: view.bounds)
view.addSubview(pdf)
pdf.startGenerating(){
}
public class generatePDF: WKWebView, WKUIDelegate, WKNavigationDelegate {
static var observer: NSObjectProtocol!
public override init(frame: CGRect, configuration: WKWebViewConfiguration = WKWebViewConfiguration()) {
super.init(frame: frame, configuration: configuration)
doInit()
}
func doInit() {
DocMakerInfo.isDoneLoading = false
self.navigationDelegate = self
self.uiDelegate = self
print("didInit")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func startGenerating(completion: @escaping () -> Void) {
openDocument(fileName: DocMakerInfo.fileName, extenstion: DocMakerInfo.extenstion)
completion()
}
private func openDocument(fileName:String, extenstion:String){
do {
#if targetEnvironment(macCatalyst)
let homeDirURL = (NSSearchPathForDirectoriesInDomains(.downloadsDirectory, .userDomainMask, true) as [String]).first!
let docURL = URL(string: "file://\(homeDirURL)/")!
#else
let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
#endif
let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)
for url in contents {
#if targetEnvironment(macCatalyst)
if url.description.contains("/\(fileName)\(extenstion)") {
webView.frame = view.bounds
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
let dataFileMimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
do {
let fileContent = try Data(contentsOf: url)
self.load(fileContent, mimeType: dataFileMimeType, characterEncodingName: "", baseURL: url)
//self.view = self.webView
Dynamic.NSWorkspace.sharedWorkspace.activateFileViewerSelectingURLs([url])
} catch let error {
print(error.localizedDescription)
}
}
#else
if url.description.contains("\(fileName)\(extenstion)") {
self.bounds = CGRect(x: 0, y: 0, width: 700.00, height: 1000.00)
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
let fileURL = docURL.appendingPathComponent("\(fileName)\(extenstion)")
self.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
self.load(URLRequest(url: fileURL))
print("startedLoading")
}
#endif
}
} catch {
Swift.print(#file, #function, "could not locate \(extenstion) file !!!!!!!")
}
}
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("didStartProvisionalNavigation")
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation", error.localizedDescription)
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail", error.localizedDescription)
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("doneloading")
let config = WKPDFConfiguration()
webView.createPDF(configuration: config) { result in
switch result {
case .success(let data):
#if targetEnvironment(macCatalyst)
#else
let destURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(DocMakerInfo.fileName).pdf")
do {
try data.write(to: destURL)
print("createpdf")
DocMakerInfo.isDoneLoading = true
} catch {
print("didFinish", error)
}
#endif
case .failure(let error):
print("create pdf failure: \(error)")
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以注意到的几件事:
你所拥有的:
你应该做的是使用自动布局或框架给它一个框架,因为即使它确实加载了一些东西,没有框架你也看不到任何东西
所以例如:
正常尝试看看您最终是否有更好的结果
更新以包含完整的源代码
这与您的PDF类相同,我仅将
openDocument
函数更改为打开本地 PDF 文件,所以这是唯一的区别然后我有一个 ViewController
结果是加载 PDF 的 webview:
<图片src="https://i.sstatic.net/PRH9a.png" alt="在 WKWebView swift iOS 中加载的 PDF">
我的控制台上的打印输出:
根据 Will 的评论进行更新
根据我读到的内容,这可能是文件权限错误 这里和此处
我没有将
其更改为此处,所以请尝试一下:
我已将 excel 文件添加到我的文档目录中并尝试将其加载到 web 视图中,以下是我在
generatePDF
类:Excel 加载正常,并且正确调用完成加载的通知
<图片src="https://i.sstatic.net/j8LGT.png" alt="在 WKWebView swift iOS 中加载 Excel xlsx">
Few things I can note:
What you have:
What you should do is give it a frame using autolayout or frames because even if it does load something, without a frame you cannot see anything
So for example:
openDocument
works well as it cannot be tested at my end, however, I just used my local PDF and this worked fine with all the notifications workingGive this a try and see if you have any better results on your end
Update to include the full source code
This is the same as your PDF class, I have only changed the
openDocument
function to open a local PDF file so this is the only differenceThen I have a ViewController
The result is a webview loading the PDF:
The print out on my console:
Update based on Will's comments
This could be a file permission error based on what I read here and here
Instead of what you do here
I changed this to, so give that a try:
I have added an excel file to my documents directory and tried to load it in the webview, here are my changes in the
generatePDF
class:The excel loads fine and also the notifications of done loading is called properly