Magnas
Magnas

Reputation: 4054

Swift 3.0 Writing binary image data with write(toFile: atomically:)

I'm working through a tutorial Project10 and trying to convert it to Swift 3.0 as I go. It is the usually straight forward case of using a UIImagePickerController to select an image and then save it to the Documents Directory.

I'm getting an error on this line:

jpegData.write(toFile: imagePath, atomically: true)

Which began life as this:

jpegData.writeToFile(imagePath, atomically: true)

The error wants to replace my arguments with:

jpegData.write(to: imagePath, options: true)

I'm pretty sure that's not what I want and it leads to further String/URL errors anyway. The two methods, in full are:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    var newImage: UIImage

    if let possibleImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        newImage = possibleImage
    } else if let possibleImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        newImage = possibleImage
    } else {
        return
    }

    let imageName = NSUUID().uuidString
    let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

    if let jpegData = UIImageJPEGRepresentation(newImage, 80) {
        jpegData.write(toFile: imagePath, atomically: true)
    }

    dismiss(animated: true, completion: nil)
}

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

Am I simply getting confused with Strings, NSStrings and URLs?

Upvotes: 4

Views: 10231

Answers (3)

Magnas
Magnas

Reputation: 4054

Well I have made some progress with the following:

let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
let path = URL(fileURLWithPath: imagePath)
if let jpegData = UIImageJPEGRepresentation(newImage, 80) {
   try! jpegData.write(to: path, options: [.atomic])
}

Ugly and slack with the possible error (for now) but using a version of El Capitan's suggested method and converting the String to an URL moves me forward.

Upvotes: 5

Naresh
Naresh

Reputation: 17902

in Swift 4.1 and Xcode 9.4.1

This is the perfect solution, we need to use try

do {
    try data.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
    print(error)
}

Upvotes: 0

Noot
Noot

Reputation: 44

This code is for Swift 3:

  if let jpegData = UIImageJPEGRepresentation(iconImage!, 80) {
      do {
            try jpegData.write(to: imagePath!)

         } catch {
             print("write image failed")       
         }
   }

Upvotes: 0

Related Questions