Search code examples
iosswiftasynchronousbackground-processmailcore2

Sending mails with SMTP Mailcore2 in Background while App is running


Im writing a iOS app which needs to send regular updates in the background after the user adds new data (Barcoder Scanner, scancodes). I can't find any ways to send the mail in background via SMTP and mailcore2 without problems and limitations.

I already tried this with:

  1. Tried it with background fetch https://developer.apple.com/documentation/uikit/core_app/managing_your_app_s_life_cycle/preparing_your_app_to_run_in_the_background/updating_your_app_with_background_app_refresh But this is very irregular and it takes some time until it triggers.

  2. In AppDelegate.swift:

func applicationDidEnterBackground(_ application: UIApplication) {
        BackgroundTask.run(application: application) { [...] }
}

But then the data is only send if i close/minimize the app and if the BackgroundTask is not complete the app will freeze and I receive this error: XPC connection interrupted I also run into problems because I need to wait for the sendOperation to return but as this is async I build a workaround to keep the Thread running and processing my "if success else ..." afterwards. More in the full code:

typealias CompletionHandler = (Error?) -> Void

/// Provides syncronous access to results returned by
/// asynchronous processes with completion handlers
class SyncMaker {
    var result: Error? = nil

    /// Generates a synchronous-compliant completion handler
    func completion() -> CompletionHandler{
        return {
            (error: Error?) in

            // Store result, return control
            self.result = error
            CFRunLoopStop(CFRunLoopGetCurrent())
        }
    }

    // Perform task (that must use custom completion handler) and wait
    func run(_ task: @escaping () -> Void) -> Error? {
        task()
        CFRunLoopRun()
        return result
    }
}

func applicationDidEnterBackground(_ application: UIApplication) {
        BackgroundTask.run(application: application) { backgroundTask in
            if (scanManager.hasDataToSend()) {
                let smtpSession = MCOSMTPSession()
                let settings: Settings = scanManager.getSettings()
                smtpSession.hostname = settings.credMailServer
                smtpSession.username = settings.credMailSource
                print(settings.credMailSource)
                smtpSession.password = settings.credMailPassword
                smtpSession.port = UInt32(settings.credMailPort)
                […] Setting auth and connection typ
                smtpSession.isCheckCertificateEnabled = false
                smtpSession.timeout = 100
                smtpSession.connectionLogger = {(connectionID, type, data) in
                    if data != nil {
                        if let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
                            NSLog("Connectionlogger: \(string)")
                        }
                    }
                }

                let builder = MCOMessageBuilder()
                builder.header.to = [MCOAddress(displayName: settings.credMailDest, mailbox: settings.credMailDest)!]
                builder.header.from = MCOAddress(displayName: settings.credMailSource, mailbox: settings.credMailSource)
                builder.header.subject = "ScanLMS"
                builder.htmlBody = ""

                guard let attachment = MCOAttachment(data: scanManager.getSendData().data(using: .ascii), filename: "scans.txt") else {
                    print("Cant init attachment!")
                    backgroundTask.end()
                    return
                }
                attachment.mimeType =  "text/plain"
                builder.addAttachment(attachment)

                let rfc822Data = builder.data()
                let sendOperation = smtpSession.sendOperation(with: rfc822Data!)
                var sendingError: Bool = true

                print("Trying to send mail...")
                if (sendOperation != nil) {
                    print("Starting sendOperation...")
                    let syncMaker = SyncMaker() //full class on top of code
                    let result = syncMaker.run {
                        sendOperation?.start(
                            syncMaker.completion())
                    }
                    if (result != nil) {
                        print("Error sending email: \(result!)")
                    } else {
                        sendingError = false
                        print("Successfully sent email!")
                    }
                } else {
                    print("Cant init sendOperation")
                    sendingError = true
                }
                if (sendingError) {
                    print("Error, returning")
                } else {
                    print("Send done")
                    print("Updating scanManager with send data...")
                    scanManager.updateSendData()
                    print("Done, returning")
                }
            } else {
                print("No new send data")
            }
            backgroundTask.end()
        }
    }

Solution

  • I lowered the smtpSession.timeout = 100 to 3 (seconds) and now its not blocking the UI anymore. More a hack then a solution, but it works.