swift - 使用 WKWebView 的输入类型 = 文件上传文件不会打开文件对话框
问题描述
我正在使用 Xcode 11.5 并在 WKWebView 中加载网页。我将文件访问权限设置为只读,这是我的应用程序功能列表。
这就是我的loadView
样子
override func loadView() {
//Inject JS string to read console.logs for debugging
let configuration = WKWebViewConfiguration()
let action = "var originalCL = console.log; console.log = function(msg){ originalCL(msg); window.webkit.messageHandlers.iosListener.postMessage(msg); }" //Run original console.log function + print it in Xcode console
let script = WKUserScript(source: action, injectionTime: .atDocumentStart, forMainFrameOnly: false) //Inject script at the start of the document
configuration.userContentController.addUserScript(script)
configuration.userContentController.add(self, name: "iosListener")
//Initialize WKWebView
webView = WebView(frame: (NSScreen.main?.frame)!, configuration: configuration)
//Set delegates and load view in the window
webView.navigationDelegate = self
webView.uiDelegate = self
view = webView
}
当我在 iOS 上使用 Safari 并选择输入类型 = 文件时,对话框打开但使用我的 macOS 应用程序使用 web 视图它不起作用?我需要在我的应用程序上设置更多功能吗?我发现了一些文件输入的老问题,但它们似乎已经解决了?
解决方案
像这样实现了 UIDelegate。
func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.begin { (result) in
if result == NSApplication.ModalResponse.OK {
if let url = openPanel.url {
completionHandler([url])
}
} else if result == NSApplication.ModalResponse.cancel {
completionHandler(nil)
}
}
}
推荐阅读
- node.js - JSON对象调用问题
- python - 为什么某些名称与“维基百科”python 3.9 中的任何页面都不匹配?
- node.js - 如何在 React 中制作交互式 SSH 终端?
- node.js - React:使用 Next.js 上传损坏的分块文件
- java - 如何存储我从上一个屏幕获得的 lastid 并获取该 id 并单击下一个选项卡中的 id
- mysql - 提高 SQL 性能:多次插入或更新多个表
- pyspark - pyspark collect_list() 和 collect_set() 使用 groupByKey 还是使用 reduceByKey?
- git - 如何使用“git checkout -d”?
- groovy - groovy中的转置列表
- postgresql - PostgreSQL:从选择中插入的一些麻烦与冲突