我构建了一个消息应用扩展程序,灵感来自Ice Cream Builder(Apple示例代码):https://developer.apple.com/library/content/samplecode/IceCreamBuilder/Introduction/Intro.html
而是使用" png"我的贴纸的图像,我想使用GIF动画。因为gif对于贴纸来说更有趣!
在示例代码中,贴纸是使用PNG格式从xcassets文件夹中的文件URL创建的。
func sticker(for mySticker: MySticker, completion: @escaping (_ sticker: MSSticker) -> Void) {
// Determine the URL for the sticker.
let fileName = mySticker.name! + ".png"
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 for stickers") }
do {
try imageData.write(to: url, options: [.atomicWrite])
} catch {
fatalError("Failed to write sticker image 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)")
}
}
// Add the operation to the queue to start the work.
queue.addOperation(operation)
}
我尝试编辑文件名:
let fileName = mySticker.name! + ".gif"
......但当然它不起作用
我注意到动画GIF格式只有在我创建了一个" Sticker pack"在xcassets文件夹中。
但我的代码并没有使用它,错误就是这一行:
guard let image = UIImage(named:mySticker.name!), let imageData = UIImagePNGRepresentation(image) else { fatalError("Unable to build image for stickers") }
这似乎合乎逻辑,但我找不到解决方法。
答案 0 :(得分:0)
解决方案非常简单。直接使用路径.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
}