Swift 3.0转换错误

时间:2016-09-27 12:48:09

标签: ios swift nsdata swift3

我已将Swift 2.2代码转换为Swift 3.0,但我收到以下错误。

open func saveToPath(_ path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
    if let image = getChartImage(transparent: format != .jpeg) {
        var imageData: Data!
        switch (format)
        {
        case .png:
            imageData = NSUIImagePNGRepresentation(image)
            break

        case .jpeg:
            imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality))
            break
        }

        let url = NSURL(string: path)
        return imageData.write(to: url as! URL, options: true)
    }
    return false
}

错误:

  

无法转换类型' Bool'预期的参数类型    ' data.writeOptions' (又名' NSData.writingOptions'))

此代码有什么问题?

1 个答案:

答案 0 :(得分:1)

需要修复以下两行:

let url = NSURL(string: path)
return imageData.write(to: url as! URL, options: true)
  1. 使用URL,而不是NSURL
  2. 使用正确的初始值设定项将文件路径字符串转换为文件URL。
  3. 将正确的值传递给options参数。
  4. 固定代码应该是:

    let url = URL(fileURLWithPath: path)
    return imageData.write(to: url, options: .atomic)