iOS 16.4中WKWebView下载文件为0及Share Sheet报错求助
问题分析
代码在iOS16.4失效的核心原因有两个:
- 直接用字符串拼接文件路径,易出现编码错误(如文件名含空格时),导致WKWebView无法正确写入文件,最终生成0字节空文件
- 未校验文件存在性、有效性就传入ShareSheet,触发系统文件识别错误
修正后的代码
var filePathDestination: URL? func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) { // 用URL API构造合法路径,避免字符串拼接的编码问题 guard let temporaryDirURL = FileManager.default.temporaryDirectory else { completionHandler(nil) return } let now = Date() let nowTimeStamp = getTimeStamp(dateToConvert: now as NSDate) // 假设getTimeStamp方法已实现 let fileName = "\(nowTimeStamp)\(suggestedFilename)" let destinationURL = temporaryDirURL.appendingPathComponent(fileName) filePathDestination = destinationURL completionHandler(destinationURL) } func downloadDidFinish(_ download: WKDownload) { guard let fileURL = filePathDestination else { return } // 校验文件是否存在且大小正常 do { let fileAttributes = try FileManager.default.attributesOfItem(atPath: fileURL.path) if let fileSize = fileAttributes[.size] as? Int64, fileSize == 0 { print("下载文件为空") return } let data = try Data(contentsOf: fileURL) print("文件大小:\(data.count) bytes") } catch { print("文件校验失败:\(error.localizedDescription)") return } // 弹出ShareSheet let ac = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil) // iPad适配(无需可简化) if let popoverController = ac.popoverPresentationController { popoverController.sourceView = self.view popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 1, height: 1) popoverController.permittedArrowDirections = [] } present(ac, animated: true) }
关键修改点说明
- 路径构造优化:用
FileManager.default.temporaryDirectory获取标准临时目录URL,通过appendingPathComponent拼接文件名,彻底避免路径编码错误,这是解决0字节文件的核心 - 文件有效性校验:弹出ShareSheet前检查文件大小,避免传入空文件触发系统错误
- 简化Popover配置:移除重复的
sourceRect赋值,规范iPad端ShareSheet弹出逻辑 - 避免强制解包:用可选绑定处理
filePathDestination,提升代码稳定性
错误信息对应解释
你遇到的NSOSStatusErrorDomain Code=-10814和No valid file provider found错误,本质是系统无法识别非法文件路径,导致ShareSheet无法读取文件元数据。修正路径构造方式后,这类错误会自动消失。
内容的提问来源于stack exchange,提问作者user1763510
相关产品推荐
相关产品推荐

