lucasrodesg lucasrodesg -3 years ago 101
iOS Question

Attach an array of doubles to a mail in Swift

I am trying to attach an array of doubles to a mail using the

MFMailComposeViewController
class. So far this is my code in the
ViewController
class:

func prepareMail(data:[Double]) {
// Compose the mail
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
mailComposer.setToRecipients(["mail@mail.com"])
mailComposer.setSubject("subject")
mailComposer.setMessageBody("Hello ", isHTML: false)

// Name data files (accelerometer + label)
let fileName = "file"

if let dataToAttach = data {
//Attach File
mailComposer.addAttachmentData(dataToAttach, mimeType: "text/plain", fileName: "\(fileName)")
self.present(mailComposer, animated: true, completion: nil)
}
}
}


This code raises the following message:


initializer for conditional binding must have Optional type, not
[Double]


So here are my thoughts:


  • Option 1: Convert the array of doubles to a string and send it as a plain/text file. My intuition, however, tells me that this is not a nice solution. I am not a fan of parsing.

  • Option 2: Encode the array somehow and send it using another
    mimetype
    other than plain/text. I explored some options in IANA mime Types, but I am not familiar at all and do not know where to start with.



I am not sure how to proceed.

Answer Source

Your problem is this line if let dataToAttach = data because your data is [Double] and can't be nil, so you don't need to check of is nil, or you can change the parameters type to [Double]? to avoid this compiler error.

Replacing this:

if let dataToAttach = data {
            //Attach File
            mailComposer.addAttachmentData(dataToAttach, mimeType: "text/plain", fileName: "\(fileNames[i])")
            self.present(mailComposer, animated: true, completion: nil)
        }

by this:

   func prepareMail(data:[Double]) {
    // Compose the mail
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setToRecipients(["mail@mail.com"])
    mailComposer.setSubject("subject")
    mailComposer.setMessageBody("Hello ", isHTML: false)

    // Name data files (accelerometer + label)
    let fileName = "file"

    if let dataToAttach = data.map({String($0)}).joined(separator: "\n").data(using: .utf8)
    {
        mailComposer.addAttachmentData(dataToAttach, mimeType: "text/plain", fileName: "\(fileNames[i])")
        self.present(mailComposer, animated: true, completion: nil)
    }

}

will be enough.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download