Сохранить файл изображения во временный каталог

У меня есть файл изображения с именем «Image.png», и он сохранен в моем основном пакете (рядом с файлом ViewController.swift в иерархии Project Navigator). Я хочу сохранить копию этого изображения во временный каталог. Я никогда не делал этого раньше, какой код я могу использовать, пожалуйста?


person dimery2006    schedule 03.03.2016    source источник


Ответы (3)


Что-то вроде этого должно помочь. Я предполагаю, что вы хотели получить ответ в 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
}

Хотя я не совсем уверен, почему вы хотите сделать это, а не напрямую обращаться к ресурсу пакета.

person mszaro    schedule 03.03.2016
comment
Большое спасибо, Мэтт! - person dimery2006; 04.03.2016
comment
Нет проблем @dimery2006, если это помогло, рассмотрите возможность принятия ответа :) - person mszaro; 08.03.2016

Swift 4.x версия ответа mszaro

/**
 * 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
}
person Hooda    schedule 25.11.2017
comment
NSURL не подходит для Swift 4. Не используйте это. И правильный синтаксис для добавления имени файла и расширения: let targetURL = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension)) - person vadian; 25.11.2017

Вот ответ в 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
    }

Я рекомендую прочитать эту статью, чтобы узнать больше о временных файлах

person umayanga    schedule 15.10.2020