[英]How to read image from file system within macOS app
可能應用程序會打開一個對話框,允許選擇圖像並將其顯示給用戶。 用戶對 select 圖像的代碼是:
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
?
我很感激幫助。
感謝@matt 評論中的鏈接,我實現了答案。 把它留在這里以防對任何人有幫助。
<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>
Codable
結構,用於保存書簽數據和圖像名稱(或您可能擁有並需要保存的任何Codable
數據)。struct CodableImage: Codable {
let bookmarkData: Data
let name: String
}
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)
}
首先從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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.