IOS: UIImagePNGRepresentation (). writeToFile does not write to the intended directory

Usage Swift

I am trying to download JPG

from a url and then save this image to a file, but when I try to save it to another directory it fails. It will be downloaded to the application folder Documents

, 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 on it? Why is this happening? Do I need to create a subfolder beforehand?

+3


source to share


1 answer


A few thoughts:



  • Is there a subdirectory folder? If not, you must create it first. And now it is advisable to use NSURL

    path strings instead. Thus, we get:

    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 suggest not converting NSData

    to UIImage

    , and then converting it back to NSData

    . You can just write the original NSData

    object if you like.

    A round trip through process UIImage

    can result in a loss of quality and / or metadata, which could potentially lead to the resulting asset becoming larger, etc. If possible, use the original one NSData

    .

+7


source







All Articles