问题
I'm trying to load an image from an absolute path into an NSImage
and even though the same full path works in other scenarios when I'm using it in this context, the variable just ends up being nil
. I've tried using both the file path and an NSURL
to achieve it.
//: 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")
}
My final goal is to load the image into an NSData
object so I can run a transform on it and then set the manipulated in memory image as the desktop background.
回答1:
As per Droppy's comment, this was due to the Swift Playground running in a sandbox and not allowing access to files outside of it's workplace. I've moved the images I need into the playground itself to test and it now works as expected. Details on how to do this can be found here.
来源:https://stackoverflow.com/questions/31086999/how-come-i-cant-successfully-load-an-nsimage-from-its-full-path-swift-2