arraysswiftfor-loopmfmailcomposeviewcontroller

Sending an email with a loop as body in Swift


I would like to send an email with different steps and values depending on what the user has edited on an image. For that, I'm using UserDefaults to save values.

Then I have the next code into an UIAlertController:

alert.addAction(UIAlertAction(title: "Send", style: .default)
        { action -> Void in
            //i is the last step register

            let nombre = alert.textFields![0]

            for n in 1...self.i {
                print("Step \(n): \(self.filterUserDefaults.string(forKey: "Step_\(n)")!)")
            }

            let filters = [
                "Brillo",
                "Exposicion",
                "Contraste",
                "Saturacion",
                "Saturacion_color",
                "Temperatura",
                "Blanco_Negro",
                "HUE",
                "Tintado_Rojo",
                "Tintado_Rosa",
                "Tintado_Naranja",
                "Tintado_Amarillo",
                "Tintado_Purpura",
                "Tintado_Verde",
                "Tintado_Azul",
                "Tintado_Marron",
                "Tintado_Gris"]
            for filter in filters {
                print("\(filter) = \(self.filterUserDefaults.float(forKey: filter).roundTo(places: 3))")
            }
            self.sendMail(filtro: nombre.text!, body: "XXXX")
        })
        present(alert, animated: true)
    }
    func sendMail(filtro: String, body: String) {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["blablabla@gmail.com"])
            mail.setSubject("Filtro \(filtro)")
            mail.setMessageBody(body, isHTML: true)
            present(mail, animated: true)
        } else {
            print("Error presenting email app.")
        }
    }

So printing is working as I expect but the problem is to put these prints into the body of sendMail function...

I tried:

            var steps: [String]?

            for n in 1...self.i {
                steps = ["Step \(n): \(self.filterUserDefaults.string(forKey: "Step_\(n)")!)"]
            }
            .
            .
            .
            self.sendMail(filtro: nombre.text!, body: steps!.joined(separator: "\n"))

But only the last step is written into the body's email and not the array...

Please, can anyone help me?

Thank you in advance!


Solution

  • You are almost there, you need to initialise your array variable and use append

    var steps = [String]()
    
    for n in 1...self.i {
        steps.append("Step \(n): \(self.filterUserDefaults.string(forKey: "Step_\(n)")!)")
    }
    ...
    self.sendMail(filtro: nombre.text!, body: steps.joined(separator: "\n"))