swiftimagemessagemfmessagecomposeviewcontroller

Swift 3 - Sending message with image - Undetermined Literal


Currently trying to open MFMessageComposeViewController with an image attached but the typeIdentifier that I have found in older code seems to not be the right fit and I'm not able to find any documentation regarding attaching an image to a message other than copying the image to the PasteBoard/clipboard then having the user manually paste it in the message.

func sendMessageWith(imageData: Data) -> MFMessageComposeViewController? {
  if MFMessageComposeViewController.canSendText() == true {
      let composeVC = MFMessageComposeViewController()
      composeVC.messageComposeDelegate = self
      composeVC.addAttachmentData(imageData, typeIdentifier: kUTTypeJPEG, filename: "image.jpg")

      print("OK")
      return composeVC
    }

  print("Try Again")
  return nil
}

Solution

  • You need to import MobileCoreServices framework:

    import MobileCoreServices
    

    which contains the UTCoreTypes header which contains kUTTypeJPEG.

    and you have to cast the constant to String because it's a CFString:

    composeVC.addAttachmentData(
        imageData,
        typeIdentifier: kUTTypeJPEG as String,
        filename: "image.jpg"
    )