【发布时间】:2016-04-18 22:34:47
【问题描述】:
我开发了一个 OS X 应用程序,有时我需要将一些图片保存到磁盘。我有办法做到这一点:
func saveImageAtPath(image: NSImage, path: String)
{
if let data = image.TIFFRepresentation
{
let bitmap = NSBitmapImageRep(data: data)
let pngImage = bitmap?.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])
NSLog("Path : %@", path)
if let _ = pngImage?.writeToFile(path, atomically: false)
{
NSLog("Everything should work...")
}
}
}
当我尝试保存图像时,似乎一切正常,控制台中显示以下文本:
路径: /Users/myusername/Documents/Pictures/Apps/testPictures/mypicture.png
一切都应该正常...
一个月前一切正常。 这是我的conf:
OS X 优胜美地 10.10.5 Xcode 7.2
如果有人有想法...那就太好了!
提前致谢。
【问题讨论】:
-
if let _ = pngImage?解包可选但不考虑writeToFile的Bool结果。使用writeToFile:options:error:捕获错误 -
感谢您的回答,我应该考虑一下...
writeToFile:options:error似乎不再存在。而且我无法使用writeToFile(path: String, options: NSDataWritingOptions) throws成功捕获错误 -
您必须将
throws方法包装在do - try <method> - catch块中 -
感谢您的快速回答 vadian。我不明白的是我无法真正捕捉到错误,我必须创建自定义错误,对吗?那我怎么知道到底发生了什么?
-
不,
throws确实会引发错误的方法。包括错误指针 (**NSError) 在内的所有方法在 Swift 2 中都显示为throw方法。请阅读 Swift 语言指南中有关错误处理的章节。
标签: swift macos nsdata osx-yosemite writetofile