首页 > 解决方案 > 文件“xxx”无法保存在文件夹“xxx”中 - 不保存 NSOpenPanel 的 NSImage 在 swift macos 中选择的 url

问题描述

我是 MACOS Development 的新手,正在制作一个应用程序。在我的应用程序中,我打开 NSOpenPanel 并选择一个文件夹或任何目录(如下载、文档),然后 NSOPenPanel 开始方法给我选择的 URL。我想在该选定的 URL 上保存多个图像,但面对此错误无法实现。

文件“xxx”无法保存在文件夹“xxx”中。

@IBAction func menuExportTapped(_ sender: NSMenuItem) {
        let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = false
        openPanel.allowsMultipleSelection = false
        openPanel.canChooseDirectories = true
        openPanel.canCreateDirectories = true
        openPanel.title = NSLocalizedString("change_the_folder", comment: "")
        openPanel.runModal()
        openPanel.begin { [weak self] (result) -> Void in
            if result == .OK {
                self?.myImage?.writePNG(toURL: openPanel.url!)
            } else {
                openPanel.close()
            }
        }
}

我测试了 writePNG 代码,它工作正常。

extension NSImage {
public func writePNG(toURL url: URL) {
        
        guard let data = tiffRepresentation,
              let rep = NSBitmapImageRep(data: data),
              let imgData = rep.representation(using: .png, properties: [.compressionFactor : NSNumber(floatLiteral: 1.0)]) else {
            
            Swift.print("\(self) Error Function '\(#function)' Line: \(#line) No tiff rep found for image writing to \(url)")
            return
        }
        
        do {
            try imgData.write(to: url)
        }catch let error {
            Swift.print("\(self) Error Function '\(#function)' Line: \(#line) \(error.localizedDescription)")
        }
    }
}

请帮我解决一下这个。谢谢你!

标签: swiftmacosswift5nsimagensopenpanel

解决方案


推荐阅读