我正试图将一个图像从绝对路径加载到NSImage
中,即使在其他场景中使用相同的完整路径,当我在此上下文中使用它时,该变量最终也是nil
。我已经尝试使用文件路径和NSURL
来实现它
//: Playground - noun: a place where people can play
import Cocoa
import AppKit
print ("Starting")
/**
Attempt to do via NSURL
**/
// The workspace
var workspace = NSWorkspace.sharedWorkspace()
// Main screen
var screen = NSScreen.mainScreen()
let filemgr = NSFileManager.defaultManager()
print(filemgr.currentDirectoryPath)
let filePath1 = "/Users/daniel/Google Drive/elementarian wallpapers/Bicycle by midnighttokerkate.png"
let filePath2 = "/Users/daniel/Google Drive/elementarian wallpapers/Buildings Foggy Sky by solutionall.png"
let file1 = NSURL(fileURLWithPath: filePath1, isDirectory: false)
let file2 = NSURL(fileURLWithPath: filePath2, isDirectory: false)
do {
try workspace.setDesktopImageURL(file2, forScreen: screen!, options: [:])
print("Successfully set background from NSURL")
} catch {
print("Failed to set")
}
print("Attempting to set from NSData...")
/**
Attempt to do via NSData
**/
// Load image from URL first
if filemgr.fileExistsAtPath(filePath2) {
print("File exists")
var image = NSImage(contentsOfURL: file2)
if image != nil {
print ("Not nil")
} else {
print ("Nil")
}
} else {
print("File not found")
}
我的最终目标是将图像加载到NSData
对象中,这样我就可以对其进行转换,然后将内存中操作的图像设置为桌面背景。
根据Droppy的评论,这是由于Swift Playground在沙盒中运行,不允许访问其工作场所之外的文件。我已经把我需要的图像移到操场上进行测试,现在它可以像预期的那样工作了。关于如何做到这一点的详细信息可以在这里找到。