gpt4 book ai didi

ios - MessageAppExtension : how to load sticker images from assets to MSStickerBrowserView?

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:28 26 4
gpt4 key购买 nike

好吧,我知道这对每个人来说都是新的,但我认为这将是一个简单的概念 - 我在这里按照这个来制作自定义贴纸消息应用程序扩展:

https://code.tutsplus.com/tutorials/create-an-imessage-app-in-ios-10--cms-26870

我已经完全复制了所有内容,并正在尝试创建一个基本的 MSStickerBrowserView 显示(然后使用逻辑进行过滤,但还没有尝试过)我的 Assets 文件夹中的贴纸 png:

enter image description here

本教程似乎没有从 Assets 中加载,而只是从他们的项目中加载,不管他们的代码像这里一样旧:

var stickers = [MSSticker]()

func loadStickers() {
for i in 1...2 {
if let url = Bundle.main.urlForResource("Sticker \(i)", withExtension: "png") { //ERROR!!
do {
let sticker = try MSSticker(contentsOfFileURL: url, localizedDescription: "")
stickers.append(sticker)
} catch {
print(error)
}
}
}
}

我得到了错误

Bundle has no member URLforResource

我在这方面找不到任何东西。我怎样才能在应用程序中以编程方式显示我的贴纸?

错误:

enter image description here

这些是我尝试加载的图像,无论它们的名称如何:

enter image description here

最佳答案

教程不使用 Assets 目录的原因是,在调用包上的 urlForResource 方法时,您无法获得放置在 .xcassets 文件夹中的图像的有效文件 URL。

您需要单独添加您的 Assets ,就像您添加到应用中的其他文件一样。此时在包上调用 pathForResource 或 urlForResource 将不再返回 nil。

编辑:这是一个函数,它将获取文件夹名称,遍历其内容并返回 [MSSticker]?根据它的发现

func createStickers(from folderName: String) -> [MSSticker]? {

guard
let path = Bundle.main.resourcePath
else { return nil }

var stickers = [MSSticker]()
let folderPath = "\(path)/\(folderName)"
let folderURL = URL(fileURLWithPath: folderPath)

//get a list of urls in the chosen directory
do {
let imageURLs = try FileManager.default.contentsOfDirectory(at: folderURL,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
//loop through the found urls
for url in imageURLs {
//create the sticker and add it, or handle error
do {
let sticker = try MSSticker(contentsOfFileURL: url, localizedDescription: "yourDescription")
stickers.append(sticker)
} catch let error {
print(error.localizedDescription)
}
}

} catch let error {
print(error.localizedDescription)
}

//return nil if stickers array is empty
return stickers.isEmpty ? nil : stickers
}

这应该让您只需调用它并获得您想要的东西:

let stickers = createStickers(from: "YourFolderName")

请注意不要在文件夹名称的开头包含正斜杠 ('/')。

关于ios - MessageAppExtension : how to load sticker images from assets to MSStickerBrowserView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com