Is there a writeToFile equivalent for Swift 3's 'Data' type?

30,251

Use write(to: fileURL).

For example:

let fileURL = try! FileManager.default
    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("test.jpg")

do {
    try jpegData.write(to: fileURL, options: .atomic)
} catch {
    print(error)
}

Or, if you really are stuck with a path, convert that to a URL:

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

But, generally, it's preferable to use URL references throughout your code nowadays, retiring the use of path strings.

Share:
30,251

Related videos on Youtube

Kyle G
Author by

Kyle G

App developer + UI designer.

Updated on December 20, 2020

Comments

  • Kyle G
    Kyle G over 3 years

    I've some code which returns the new iOS 10 / Swift 3 NSData replacement(?) type: Data

    if let jpegData = UIImageJPEGRepresentation(newImage, 0.8) { ... }
    

    I want to write this image to disk, however NSData's writeToFile: method is not present for this class. It does have a writeToURL: method, but that doesn't seem to work with a file path (and appending component).

    Can anyone clarify how I would now do this, as used to be the case in Swift 2:

    jpegData.writeToFile(imagePath, atomically: true) 
    

    Thanks!

  • Kyle G
    Kyle G almost 8 years
    This is fantastic! Thanks Rob. And thanks for making the switch to .atomic.
  • Nicolas Miari
    Nicolas Miari almost 8 years
    Apple seems to be moving towards URL-based file APIs and deprecating(?) the path(String)-based ones.
  • Rob
    Rob over 6 years
    Largely so, yes, but with some odd exceptions (e.g. UIImage(contentsOfFile:), but no file URL rendition).
  • Iurie Manea
    Iurie Manea over 6 years
    Does not work if file path(name, folders) contains unicode characters. Solution is: path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)
  • Rob
    Rob about 5 years
    @IurieManea - Good point. Yes, if you’re passing a path or URL string to URL(string:) or URL(fileURLWithPath:), you have to make sure the string is properly percent escaped. However, if you use methods like let fileURL = baseURL.appendingPathComponent("😀.dat"), it does the percent encoding for you.