Search code examples
iosswifttextmfmessagecomposeviewcontroller

How do I attach an mp3 to MFMessageComposeViewController?


I have multiple mp3 files in my project. I would like to know how I can access this file (file path) and attach it to the text message I will be sending out.

Does anybody know how to do this? Please provide some code if possible!


Solution

  • MFMessageComposeViewController has a few handy methods for you:

    func addAttachmentURL(_ attachmentURL: NSURL, withAlternateFilename alternateFilename: String?) -> Bool

    and

    func addAttachmentData(_ attachmentData: NSData,typeIdentifier uti: String, filename filename: String) -> Bool

    You'd probably want to do something like:

    let pFileUrl = NSURL(fileURLWithPath:pSongPath];
    do {
       let pData = try NSData(contentsOfURL: pFileUrl, options: NSDataReadingOptions())
       pMailComposer.addAttachmentData(pData, mimeType:"audio/mpeg" fileName:@"song.mp3")
    } catch let error as NSError {
       print("error while trying to load data - \(error.localizedDescription)")
    }
    

    (I didn't run this through a compiler so I might be off an optional or two)