文件路径中的空格替换为(null)

时间:2016-04-03 19:36:44

标签: swift macos cocoa

我试图检查当前的桌面墙纸是否有特定的文件名。我想通过将文件名附加到desktopImageURLForScreen并使用fileExistsAtPath检查该文件是否存在(不是一个完美的解决方案,但它适用于我的目的)来实现。这是我的代码:

guard let wallpaperDirectoryURL = workspace.desktopImageURLForScreen(screen)
    else { NSLog("Error getting desktop image URL."); return }

let URLToCheckIfExists = wallpaperDirectoryURL.URLByAppendingPathComponent("\(lastId).jpg")
let stringToCheckIfExists = URLToCheckIfExists.absoluteString
print(stringToCheckIfExists)
let lastIdIsCurrentWallpaper = NSFileManager.defaultManager().fileExistsAtPath(stringToCheckIfExists)

我的问题是,当文件路径中有空格时,文件路径的字符串会替换空格和后面的字符(null)。

所以代替路径:

/Users/Joe/Library/Application Support/Wallpaperer/Wallpapers/4d65y1.jpg

我明白了:

/Users/Joe/Library/Application(null)upport/Wallpaperer/Wallpapers/4d65y1.jpg

这里发生了什么?我怎样才能找到正确的道路?

1 个答案:

答案 0 :(得分:1)

好吧,我很快发现了问题。我应该使用URLToCheckIfExists.path而不是URLToCheckIfExists.absoluteString