为什么无法从完整路径成功加载NSImage?斯威夫特2 [英] How come I can't successfully load an NSImage from it's full path? Swift 2

查看:110
本文介绍了为什么无法从完整路径成功加载NSImage?斯威夫特2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像从绝对路径加载到NSImage中,即使在这种情况下使用其他场景时,相同的完整路径也可以使用,但变量最终以nil结尾.我尝试使用文件路径和NSURL来实现它.

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")
}

我的最终目标是将图像加载到NSData对象中,以便可以对其进行转换,然后将在内存图像中操作的图像设置为桌面背景.

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.

推荐答案

按照此处.

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.

这篇关于为什么无法从完整路径成功加载NSImage?斯威夫特2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆