error-handlingswift2xcode7uiimagepngrepresentation

error handling in Swift 2


i have to fix the follow code for swift2.

if !UIImagePNGRepresentation(img).writeToFile(imagePath, options: nil, error: &error) {
                        if let actualError = error {
                            NSLog("Image not saved. \(actualError)")
                        }
                    }

To compile it i have this error on if row: Cannot invoke writeToFile with an argument list of type (String, options: _, error: inout NSError?)

How I can fix it.


Solution

  • Try it with

    UIImagePNGRepresentation(img)?.writeToFile(imagePath, atomically: true)
    

    instead. Check the Apple Docs.

    Edit:

    To answer your question more precisely use the error handling in Swift 2.

    do {
        try UIImagePNGRepresentation(img)?.writeToFile(imagePath, options: .DataWritingAtomic)
    } catch let error as NSError {
        print("Image not saved. \(error.description)")
    }