如何在 macOS 应用程序中从文件系统读取图像

regina_fallangi

May 应用程序打开一个对话框,允许选择图像并将其显示给用户。用户选择图片的代码是:

let myFiledialog = NSOpenPanel()
myFiledialog.prompt = "Upload image"
myFiledialog.canChooseDirectories = false
myFiledialog.canChooseFiles = true
myFiledialog.allowedFileTypes = ["png", "jpg", "jpeg"]
myFiledialog.allowsMultipleSelection = false
myFiledialog.begin {  [weak self] result -> Void in
      guard 
           result.rawValue == NSApplication.ModalResponse.OK.rawValue,
           let selectedPath = myFiledialog.url?.path
      else {
            return
      }
      guard let image = NSImage(contentsOfFile: selectedPath) else {
          return
      }
      someImageView.image = image
      UserDefaults.standard.set(selectedPath, forKey: "imagePath")
}

我正确显示图像。这个想法是用户可以关闭应用程序,打开它并查看图像。

我正在获取图像名称:

let pathName = UserDefaults.standard.string(forKey: "imagePath")

我比较设置一个断点,pathName == selectedPath它们是相等的。

然而,做

NSImage(contentsOfFile: pathName!)

nil

这是否与我需要获取读取文件系统中的数据的权限有关?我应该将用户图像保存在我可以访问它们的其他地方吗?也许也是 NSUserDefaults 作为images.data

我很感激你的帮助。

regina_fallangi

感谢@matt 评论中的链接,我实现了答案。把它留在这里以防万一对任何人都有帮助。

  1. 向应用程序添加权利。点击 App -> Target -> Signin & Capabilities -> App Sandbox 并更改文件访问类型的“权限和访问”。Xcode 会询问您是否要创建权利文件。接受。如果不需要,请还原您所做的更改。现在您将拥有该文件<AppName>/<AppName>Release.entitlements添加允许用户使用应用范围书签和 URL ( Apple Docs ) 的权利。这是文件的样子:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
    <key>com.apple.security.files.bookmarks.app-scope</key>
    <true/>
</dict>
</plist>
  1. 创建一个结构,Codable用于保存书签数据和图像名称(或Codable您可能拥有并需要保存的任何数据)。
struct CodableImage: Codable {
    let bookmarkData: Data
    let name: String
}
  1. 为网址添加书签:
do {
    let data = try url.bookmarkData()
    let codableImage = CodableImage(bookmarkData: data, name: "Awesome image")
    UserDefaults.standard.set(try? JSONEncoder().encode(codableImage), forKey: "kImageKey")
} catch {
    print(error)
}
  1. 检索数据

首先获取CodableImage来自UserDefaults

guard 
    let encodedImageData = UserDefaults.standard.value(forKey: "kImageKey") as? Data,
    let codableImage = try? JSONDecoder().decode(CodableImage.self, from: encodedImageData)
else {
    // Data could not be read or decoded or both :(
    return
}

解析书签数据并在已解析的书签过期时更新书签:

var isBookmarkStale = false
guard let url = try? URL(resolvingBookmarkData: codableImage.bookmarkData, bookmarkDataIsStale: &isBookmarkStale) else {
    return nil
}

if isBookmarkStale {
    print("Bookmark is stale. renewing.")
    // If bookmark data is stale, all occurences have to be updated.
            
    let _ = try? url.bookmarkData()
}

最后,从解析的 url 创建图像:

let image = NSImage(contentsOf: url)

归功于URL 书签:对于陈旧数据更新逻辑是和否

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在macOS中卸载Java JDK?

如何在Web应用程序中读取属性文件?

如何在macOS中安装wget?

如何在macOS系统偏好设置中启用FinderSync扩展

如何在macOS下的非基于文档的应用程序中添加选项卡?

如何在macOS应用程序中从App注册服务?

如何在macOS上全屏显示tkinter应用程序?

如何在macOS中启动Spyder?

如何在MacOS中显示NSSavePanel?

如何在.NET Core控制台应用程序中获取MacOS用户名?

如何在Xcode之外运行Xcode应用程序?MacOS Standalone应用程序与Xcode Simulator中的应用程序运行不同

如何在macOS预览应用程序中使用JavaScript for Automator(JXA)保存图像?

如何在macOS(不是iOS)上的SwiftUI中以编程方式从后台打开应用程序窗口?

如何在SwiftUI macOS应用程序中模糊背景?

如何在SwiftUI(macOS)中拖放不在捆绑中的图像

如何在沙盒macOS应用程序和脚本(或程序)之间进行通信

如何在macOS上实现虚拟文件系统?

如何在macOS Catalina中删除系统应用程序?

如何在MacOS上将应用程序从/ Applications移至〜/ Applications

如何在macOS中隐藏Bitnami横幅

如何在 macOS 中完全禁用隔离?

如何在 macOS 终端中复制文件

如何在 Swift / MacOS 中读取键盘状态?

如何从应用程序包中的文件中读取数据 I macOS?

如何在应用程序包 [macOS] 中的 C 中查找当前目录

如何在 macOS 中搜索任何卷?

如何在 MacOS 上运行 .NET Core 3.1 单文件应用程序?

如何在 macOS 上的 Swift 中在 PATH 上启动终端应用程序?

如何在基于文档的 macOS 应用程序中处理不同的文档类型?