我试图将图像从绝对路径加载到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
对象中,以便我可以对其进行转换,然后将内存图像中的操作设置为桌面背景。
答案 0 :(得分:1)
根据Droppy's comment,这是由于Swift Playground在沙箱中运行而不允许访问其工作场所之外的文件。我已将我需要的图像移动到游乐场本身进行测试,现在它按预期工作。有关如何执行此操作的详细信息,请参阅here。