Reputation: 7425
Using Swift
I am trying to download a JPG
from a URL and then saving that image to a file, but when I try to save it to a different directory it won't. It will download to the app's Documents
folder, but not when I try to set the path to another subfolder.
let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0].stringByAppendingPathComponent("SubDirectory") as String
let filepath = dir.stringByAppendingPathComponent("test.jpg")
UIImagePNGRepresentation(UIImage(data: data)).writeToFile(filepath, atomically: true)
When I run this, it doesn't save the image to it? Why is this happening? Do I need to create the subfolder beforehand?
Upvotes: 3
Views: 3323
Reputation: 438287
A couple of thoughts:
Does the subdirectory folder already exist? If not, you have to create it first. And it's now advisable to use NSURL
instead of path strings. So that yields:
let filename = "test.jpg"
let subfolder = "SubDirectory"
do {
let fileManager = NSFileManager.defaultManager()
let documentsURL = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let folderURL = documentsURL.URLByAppendingPathComponent(subfolder)
if !folderURL.checkPromisedItemIsReachableAndReturnError(nil) {
try fileManager.createDirectoryAtURL(folderURL, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = folderURL.URLByAppendingPathComponent(filename)
try imageData.writeToURL(fileURL, options: .AtomicWrite)
} catch {
print(error)
}
I would advise against converting the NSData
to a UIImage
, and then converting it back to a NSData
. You can just write the original NSData
object directly if you want.
The process of round-tripping this through a UIImage
can make lose quality and/or metadata, potentially making the resulting asset larger, etc. One should generally use the original NSData
where possible.
Upvotes: 7