Save image file to temp directory
Asked Answered
R

3

8

I have an image file named "Image.png", and it is saved in my main bundle (right beside the ViewController.swift file in the Project Navigator hierarchy). I want to save a copy of this image to the temporary directory. I've never done it before, what code could I use please?

Russon answered 3/3, 2016 at 1:15 Comment(0)
T
26

Something like this should do the trick. I'm assuming you wanted the answer in Swift.

 /**
 * Copy a resource from the bundle to the temp directory.
 * Returns either NSURL of location in temp directory, or nil upon failure.
 *
 * Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
 */
public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> NSURL?
{
    // Get the file path in the bundle
    if let bundleURL = NSBundle.mainBundle().URLForResource(resourceName, withExtension: fileExtension) {

        let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)

        // Create a destination URL.
        let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(resourceName).\(fileExtension)")

        // Copy the file.
        do {
            try NSFileManager.defaultManager().copyItemAtURL(bundleURL, toURL: targetURL)
            return targetURL
        } catch let error {
            NSLog("Unable to copy file: \(error)")
        }
    }

    return nil
}

Although, I'm not really sure why you would want to do this rather than directly accessing the bundle resource.

Tickler answered 3/3, 2016 at 1:27 Comment(2)
Thanks a bunch, Matt!Russon
No problem @dimery2006, if it helped please consider accepting the answer :)Tickler
A
9

Swift 4.x version of mszaro's answer

/**
 * Copy a resource from the bundle to the temp directory.

 * Returns either NSURL of location in temp directory, or nil upon failure.
 *
 * Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
 */
public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> NSURL?
{
    // Get the file path in the bundle
    if let bundleURL = Bundle.main.url(forResource: resourceName, withExtension: fileExtension) {

        let tempDirectoryURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)

        // Create a destination URL.
        let targetURL = tempDirectoryURL.appendingPathComponent("\(resourceName).\(fileExtension)")

        // Copy the file.
        do {
            try FileManager.default.copyItem(at: bundleURL, to: targetURL)
            return targetURL as NSURL
        } catch let error {
            NSLog("Unable to copy file: \(error)")
        }
    }

    return nil
}
Amelita answered 25/11, 2017 at 16:30 Comment(1)
NSURL is not appropriate for Swift 4. Don't use that. And the proper syntax to append file name and extension is let targetURL = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension))Enthusiasm
P
5

Here's the answer in Swift 5

/**
 * Copy a resource from the bundle to the temp directory.

 * Returns either URL of location in temp directory, or nil upon failure.
 *
 * Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
 */

public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> URL?
    {
        // Get the file path in the bundle
        if let bundleURL = Bundle.main.url(forResource: resourceName, withExtension: fileExtension) {

            let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)

            // Create a destination URL.
            let targetURL = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension)

            // Copy the file.
            do {
                try FileManager.default.copyItem(at: bundleURL, to: targetURL)
                return targetURL
            } catch let error {
                print("Unable to copy file: \(error)")
            }
        }

        return nil
    }

I'd recommend to read this article to learn more about temporary files

Pater answered 15/10, 2020 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.