How come I can't successfully load an NSImage from it's full path? Swift 2

情到浓时终转凉″ 提交于 2019-12-24 16:04:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!