0

I am trying to build an iMessage app that allows a person to press a button which inserts a blue UIView into the iMessage text field. I am not sure how I can get the UIView in the iMessage text field.

I've tried to convert the UIView to a UIImage, then convert that to an MSSticker, however, I need a URL for the sticker and since I created the UIImage in code, I do not have a URL for the path.

Here, I create the UIView:

func createOval() -> UIImage {
    let blueOval = UIView(frame: CGRect(x: 5, y: 0, width: 10, height: 10))
    blueOval.backgroundColor = .black

    let label = UILabel()
    label.text = "Hello"
    blueOval.addSubview(label)

    let image = blueOval.asImage()
    return tagImage
}

The extension that enables the asImage() conversion:

extension UIView {

    func asImage() -> UIImage {
        if #available(iOS 10.0, *) {
            let renderer = UIGraphicsImageRenderer(bounds: bounds)
            return renderer.image { rendererContext in
                layer.render(in: rendererContext.cgContext)
            }
        } else {
            UIGraphicsBeginImageContext(self.frame.size)
            self.layer.render(in:UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return UIImage(cgImage: image!.cgImage!)
        }
    }

}

How can I insert that UIView into the iMessage text field?

  • Have you read the [documentation](https://developer.apple.com/documentation/messages/msconversation)? Your limited options for inserting stuff are listed there. I'd just write the image to a file so you have the URL for it. – Roope Aug 27 '19 at 15:58
  • @Roope OK, I was able to write the image as a file and grab that URL. I added it as an attachment. Also, is there any way to get the attachment to be inline with the rest of the text? –  Aug 27 '19 at 16:28
  • Not sure if it can take an `NSAttributedString` which can do inline images. But just use the search and check something like [this](https://stackoverflow.com/questions/22704292/add-uiimageview-in-uitextview-as-in-imessage) or [this](https://stackoverflow.com/questions/23621469/ios-sharing-images-with-text-in-messages-like-emoji). – Roope Aug 27 '19 at 17:53

0 Answers0