Swift 中的结构和从 url 制作 UIImage 时出现问题?

Problems with structs in Swift and making a UIImage from url?

好吧,我不熟悉结构或我在 Swift 中处理的磨难,但我需要做的是在我的 iMessage 应用程序扩展中创建一个带有标签的 iMessage,这意味着iMessage 的图像部分设置为贴纸。

我仔细阅读了 Apple 的文档和 https://www.captechconsulting.com/blogs/ios-10-imessages-sdk-creating-an-imessages-extension,但我不明白该怎么做,也不明白结构是如何工作的。我阅读了结构,但这并没有帮助我完成 Apple 在他们的示例代码中所做的事情(可在 Apple 下载)

Apple 所做的是他们首先撰写一条消息,我理解这一点,将他们的结构作为 属性,但我采用贴纸

guard let conversation = activeConversation else { fatalError("Expected a conversation") }
        //Create a new message with the same session as any currently selected message.
        let message = composeMessage(with: MSSticker, caption: "sup", session: conversation.selectedMessage?.session)

        // Add the message to the conversation.
        conversation.insert(message) { error in
            if let error = error {
                print(error)
            }
        }

然后他们这样做(这直接来自示例代码)来撰写消息:

   fileprivate func composeMessage(with iceCream: IceCream, caption: String, session: MSSession? = nil) -> MSMessage {
        var components = URLComponents()
        components.queryItems = iceCream.queryItems

        let layout = MSMessageTemplateLayout()
        layout.image = iceCream.renderSticker(opaque: true)
        layout.caption = caption

        let message = MSMessage(session: session ?? MSSession())
        message.url = components.url!
        message.layout = layout

        return message
    }
}

基本上这条线是我遇到的问题,因为我需要将我的贴纸设置为图像:

layout.image = iceCream.renderSticker(opaque: true)

Apple 做了一个我在 renderSticker 中不明白的复杂功能,将图像部分从他们的贴纸中拉出来,我已经尝试过他们的方法,但我认为这样更好:

let img = UIImage(contentsOfURL: square.imageFileURL)
        layout.image = ing

layout.image 需要一个 UIImage,我可以从贴纸中获取 imageFileURL,但我无法将其放入 UIImage。我收到一个错误,它与可用的重载不匹配。

我可以在这里做什么?如何将贴纸中的图像插入到消息中?如何从其 imageFileURL 获取图像?

UIImage 没有 init(contentsOfURL:) 初始值设定项。最接近的是 init(contentsOfFile:).

要将那个与您的文件一起使用 URL 您可以这样做:

let img = UIImage(contentsOfFile: square.imageFileURL.path)

我不确定问题到底是什么,但我会尽力解决 --

正如 rmaddy 所提到的,如果您想在给定文件位置的情况下创建图像,只需使用他指定的 UIImage 构造函数即可。

至于只发送一个贴纸(你在 rmaddy 的回答的评论中询问过),你可以只在 iMessage 对话中插入一个贴纸。此功能作为 MSConversation 的一部分提供。这是文档的 link:

https://developer.apple.com/reference/messages/msconversation/1648187-insert

可以从您的 MSMessagesAppViewController 访问活动对话。