Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image file to temp directory

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?

like image 557
dimery2006 Avatar asked Mar 03 '16 01:03

dimery2006


People also ask

What is temp file path?

Temp files often have the extension . TMP and are stored in the C:\Users\AppData\Local\Temp folder.


2 Answers

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.

like image 146
mszaro Avatar answered Oct 13 '22 18:10

mszaro


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
}
like image 25
Hooda Avatar answered Oct 13 '22 19:10

Hooda