How to Send Local Video to iMessage in Swift

by

This post assumes we have understanding about exporting to mp4 video. The use case example of the discussion exports a video and save it locally inside app’s folder: Document, Cache or Temporary. In my case I am doing some very basic composing of video and saving it to my temporary folder. I want to send this video or share it to my contacts through iMessage or MFMessageComposeViewController. Below is a brief idea on how I am exporting to mp4 video that saves in app’s temporary folder.


let exportURL = URL(fileURLWithPath: NSTemporaryDirectory())
          .appendingPathComponent("filename")
          .appendingPathExtension("mp4")
export.outputFileType = .mp4
export.outputURL = exportURL

export.exportAsynchronously {
  DispatchQueue.main.async {
    switch export.status {
    case .completed:
        print("success")
    default:
      print("Something went wrong during export.")
      print(export.error ?? "unknown error")
      break
    }
  }
}

Now, I found 2 easy effective ways to share or attach video to iMessage or MFMessageComposeViewController.

First way: Attaching the URL

This one is very handy if I already know the URL path of video saved in app’s folder. In my use case I exported the video to folder so I already have the handle to the URL.

But there is one pitfall here, in filename parameter if we don’t give extension format explicitly then it attaches as binary format to iMessage and receiver won’t be able to open it. It becomess apparant and clear itself when we cannot see the thumbnail preview of video in MFMessageComposeViewController before sending.


messageComposeVC.addAttachmentURL(exportURL, withAlternateFilename: “filename.mp4”)

Second way: Attaching the Data

This one is very handy when I already have Data of video file. For example I can make Data from the video in my app’s bundle.


if let video = try? Data(contentsOf: urlPath){
    messageComposeVC.addAttachmentData(video, typeIdentifier: “public.movie”, filename: “filename.mp4”)
}

You might also like: UIImagepicker controller allowsEditing not working

You might also like: How to get Deprecated keyWindow in Swift

More Articles

Recommended posts