SwiftStarter
SwiftStarter

Reputation: 247

How to write an image to a path in swift 3.0

I'm using core data to store a url to an image that was taken from the imagepicker.

So far I have the following:

    let tempImage = info[UIImagePickerControllerOriginalImage] as? UIImage

    let image = UIImageJPEGRepresentation(tempImage!, 0.2)

    let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
    let imageName = UUID().uuidString + ".jpg"

    let aPath = path.path

    let imagePath = (aPath as NSString).appendingPathComponent(imageName)

The result is now I have a path as a string to save in core data. But how do I write the image to the path? I was trying to use:

   let result = image!.writeToFile(path, atomically: true)

But i get an error saying value of type data has no member writeToFile. Is there another way to do it in swift 3.0?

Thanks for your help.

Upvotes: 3

Views: 5425

Answers (3)

SwiftStarter
SwiftStarter

Reputation: 247

With help from Dylansturg,

I was able to rewrite my code to work. Here is the code for future reference:

do {
   let result = try image?.write(to: path, options: .atomic)
} catch let error { 
    print(error) 
}

Upvotes: 4

dylansturg
dylansturg

Reputation: 1708

In Swift 3, UIImageJPEGRepresentation creates Data instead of NSData. You can use write instead of writeToFile.

You should be able to use:

image.write(to: URL(fileURLWithPath: path), options: .atomic)

and write out your image data image to a file at path. Notice that it uses a URL instead of a string file path, and the options parameter has changed.

Upvotes: 17

EkkoG
EkkoG

Reputation: 122

Maybe you can try to convert the UIImage object to NSData object, then follow this link to write the NSData object to a path:

https://developer.apple.com/reference/foundation/nsdata/1408033-writetofile?language=objc

Upvotes: 0

Related Questions