Access Asset Catalog pathForResource

后端 未结 6 1308
滥情空心
滥情空心 2020-11-27 17:46

It appears that:

[[NSBundle mainBundle] pathForResource:@\"name\" ofType:@\"png\"];

Does not return anything for assets that are inside the Ima

6条回答
  •  青春惊慌失措
    2020-11-27 18:22

    I wanted to access some vector assets for creating UNNotificationAttachment with local resources so I came up with this helper class. It basically just gets image from assets, saves its data to disk and return file URL. I hope that helps someone.

    import UIKit
    
    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
        }
    
    }
    

提交回复
热议问题