Search code examples
iosswiftnsdataswift3

Swift 3.0 converting error


I have converted Swift 2.2 code to Swift 3.0, but I'm getting the following error.

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
}

error :

Cannot convert value of type 'Bool' to expected argument type 'data.writeOptions' (aka 'NSData.writingOptions'))

What's wrong with this code?


Solution

  • The following two lines need to be fixed:

    let url = NSURL(string: path)
    return imageData.write(to: url as! URL, options: true)
    
    1. Use URL, not NSURL.
    2. Use the proper initializer to convert a file path string into a file URL.
    3. Pass the proper value to the options parameter.

    The fixed code should be like:

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