解决方案非常简单。直接使用路径。gif。
请小心,如果您的gif位于特定文件夹中,则此文件夹不能是文件夹引用。
func sticker(for mySticker: MySticker, completion: @escaping (_ sticker: MSSticker) -> Void) {
let fileName = mySticker.name + ".gif"
let url = cacheURL.appendingPathComponent(fileName)
// Create an operation to process the request.
let operation = BlockOperation {
// Check if the sticker already exists at the URL.
let fileManager = FileManager.default
guard !fileManager.fileExists(atPath: url.absoluteString) else { return }
// Create the sticker image and write it to disk.
guard let image = UIImage(named:mySticker.name), let imageData = UIImagePNGRepresentation(image) else { fatalError("Unable to build image \(mySticker.name)") }
do {
try imageData.write(to: url, options: [.atomicWrite])
} catch {
fatalError("Failed to write sticker image \(mySticker.name) to cache: \(error)")
}
}
// Set the operation's completion block to call the request's completion handler.
operation.completionBlock = {
do {
let sticker = try MSSticker(contentsOfFileURL: url, localizedDescription: "My Sticker")
completion(sticker)
} catch {
print("Failed to write image to cache, error: \(error)")
}
}
}
具有
struct MySticker {
var name: String
var num: Int
}