Skip to content

Instantly share code, notes, and snippets.

@fahied
Created April 11, 2019 06:28
Show Gist options
  • Save fahied/d4a99e12914eb3edb074663828240907 to your computer and use it in GitHub Desktop.
Save fahied/d4a99e12914eb3edb074663828240907 to your computer and use it in GitHub Desktop.
Get URL from Xcode asset catalogs
import UIKit
//It basically just gets image from assets, saves its data to disk and return file URL.
class AssetExtractor {
static func createLocalUrl(forImageNamed name: String) -> URL? {
let fileManager = FileManager.default
let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let url = cacheDirectory.appendingPathComponent("\(name).png")
guard fileManager.fileExists(atPath: url.path) else {
guard
let image = UIImage(named: name),
let data = UIImagePNGRepresentation(image)
else { return nil }
fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
return url
}
return url
}
}
@mauriciochirino
Copy link

Nice workaround 👏 I'd add a file type extension parameter defaulted in png.

@mauriciochirino
Copy link

mauriciochirino commented Mar 29, 2021

/// Retrieves (or creates should it be necessary) a temporary image's local URL on cache directory for testing purposes
/// - Parameter name: image name retrieved from asset catalog
/// - Parameter imageExtension: Image type. Defaults to `.jpg` kind
/// - Returns: Resulting URL for named image
func createLocalUrl(forImageNamed name: String, imageExtension: String = "jpg") -> URL? {
    let fileManager = FileManager.default

    guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
        print("Unable to access cache directory")
        return nil
    }

    let url = cacheDirectory.appendingPathComponent("\(name).\(imageExtension)")

    // If file doesn't exist, creates it
    guard fileManager.fileExists(atPath: url.path) else {
        // Bundle(for: Self.self) is used here instead of .main in order to work on test target as well
        guard let image = UIImage(named: name, in: Bundle(for: Self.self), with: nil),
              let data = image.jpegData(compressionQuality: 1) else {
            print("Impossible to convert to jpg data")
            return nil
        }

        fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
        return url
    }

    return url
}

@michzio
Copy link

michzio commented Apr 22, 2022

it is url to cache not to .xcassets catalog

@DenimMerzhan
Copy link

it is url to cache not to .xcassets catalog

@ulkoart
Copy link

ulkoart commented Sep 21, 2023

it is url to cache not to .xcassets catalog

@eldaroid
Copy link

it is url to cache not to .xcassets catalog

@Jasperav
Copy link

it is url to cache not to .xcassets catalog

@ovoitenk
Copy link

it is url to cache not to .xcassets catalog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment