swift - 使用 WKWebView 输入类型=文件上传文件不会打开文件对话框

标签 swift xcode macos progressive-web-apps

我正在使用 Xcode 11.5 并在 WKWebView 中加载网页。我将文件访问权限设置为只读,这是我的应用程序功能列表。

enter image description here

这就是我的 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 并选择输入类型=文件时,对话框会打开,但使用使用 Web View 的 macOS 应用程序时,它不起作用?我需要在我的应用程序上设置更多功能吗?我发现文件输入存在一些旧问题,但它们似乎已解决?

最佳答案

像这样实现 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)
        }
    }
}

关于swift - 使用 WKWebView 输入类型=文件上传文件不会打开文件对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62218264/

相关文章:

ios - URLSessionConfiguration 中的 TLSMinimumSupportedProtocol

ios - 从 Objective-C 加载基于 Swift 的 UIViewController

swift - 简单 swift 脚本的段错误

swift - IBDesignable 类绘图 UIImage 未在 Storyboard 中显示

swift - 在特定部分插入单元格

c++ - 在 QToolBar 后面显示 QWidget

ios - 在 Swift 中检测 CAShapeLayer 上的点击?

xcode - 如何在 Xcode14 中禁用粘性 header

delphi - Mac OS X 上 Lazarus/FreePascal 上的蓝牙

objective-c - NSRunningApplication 'terminated' 不可观察