【问题标题】:NSData writeToFile method returns true but file is not written to the diskNSData writeToFile 方法返回 true 但文件未写入磁盘
【发布时间】: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? 解包可选但不考虑writeToFileBool 结果。使用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


【解决方案1】:

我花了一整天的时间试图弄清楚如何在 swift 2.0 中编写建议的修复程序,所以现在我想分享它,因为我已经工作了

do{
    let result = try Bool(pngImage!.writeToFile(filePath, options: NSDataWritingOptions.DataWritingAtomic))
}
catch let error as NSError {
    print(error.localizedDescription)
}

我希望这可以节省一些时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多