简体   繁体   中英

How to attach recorded audio into email? in SWIFT

I've an app that record voices type of "wav" and send emails ,too. I want to add that recorded file into the email as attachment?? here is sendEmail code

func sendemail(email: String){
    if( MFMailComposeViewController.canSendMail() ) {
        println("Can send email.")

        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self

        //Set the subject and message of the email
        mailComposer.setSubject("Voice Note")
        mailComposer.setMessageBody("my sound", isHTML: false)
        mailComposer.setToRecipients([email])
// the app doesn't go trough this IF STATEMENT 
        if let filePath1 =      NSBundle.mainBundle().pathForResource("fahad", ofType: "wav") {
            println("File path loaded.")

            if let fileData = NSData(contentsOfFile: filePath1) {
                println("File data loaded.")
                mailComposer.addAttachmentData(fileData, mimeType: "audio/wav", fileName: "fahad")
            }
        }
        self.presentViewController(mailComposer, animated: true, completion: nil)
    }
}

Solved the answer from the comments, adding answer for other #Programmers :

func sendemail(email: String){
    if( MFMailComposeViewController.canSendMail() ) {
        println("Can send email.")

        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self

        //Set the subject and message of the email
        mailComposer.setSubject("Voice Note")
        mailComposer.setMessageBody("my sound", isHTML: false)
        mailComposer.setToRecipients([email])

        if let docsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
            var fileManager = NSFileManager.defaultManager()
            var filecontent = fileManager.contentsAtPath(docsDir + "/" + fileName)
            mailComposer.addAttachmentData(filecontent, mimeType: "audio/x-wav", fileName: fileName)
        }

        self.presentViewController(mailComposer, animated: true, completion: nil)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM