ios - Swift 如何在 AppDelegate 中发送电子邮件 fetch?

标签 ios swift swift4 appdelegate mailcore2

我现在完全无助,我正在尝试发送一封电子邮件以在 iOS Swift 4 应用程序中上传数据。我发现 Obj-C Mailcore 库可以在正常代码中工作,例如在按钮按下回调中。但是,如果我尝试在我的 AppDelegate 获取函数中使用相同的代码,它不会从completionHandler 返回。

Mailcore 发送操作是异步的,因此我在它周围使用了信号量包装器,但从未调用完成处理程序。

编辑:

显然,该代码在带有信号量的按钮中不起作用。仅当我删除

let _ = semaphore.wait(timeout: DispatchTime.distantFuture)

部分。

那么还有其他方法来等待异步completionBlock的完成吗?


是的,看看我的回答:-)

我的代码:

let smtpSession = MCOSMTPSession()
[...]
let sendOperation = smtpSession.sendOperation(with: rfc822Data!)
[...]
let semaphore = DispatchSemaphore(value: 0)
if (sendOperation != nil) {
    print("Starting sendOperation...")
    sendOperation?.start { (error) -> Void in
        if (error != nil) {
            sendingError = true
            print("Error sending email: \(error)")
        } else {
            print("Successfully sent email!")
        }
        sendingDone = true
        semaphore.signal()
    }
    let _ = semaphore.wait(timeout: DispatchTime.distantFuture)
} else {
    print("Cant init sendOperation")
    sendingError = true
}

最佳答案

完成要么在同一个线程上进行,要么在该线程中运行某些内容。

正常的做法是不要等待,而是在完成本身完成后做任何您需要做的事情。

如果必须使用信号量来执行此操作,请将启动调用移至另一个线程。

关于ios - Swift 如何在 AppDelegate 中发送电子邮件 fetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53446533/

相关文章:

ios - 函数 didReceive RemoteMessage 未被调用 Swift 5

swift - Collection View 中的 ImageView 必须居中且宽高比适合快速

ios - 导航栏 setTitleVerticalPositionAdjustment(_ :for:) method not working for title images on iOS 11 Beta

ios - 在运行时查找 Xcode 构建方案名称

ios - 对于使用 CCCrypt() 的 AES128, key 是否可以超过 128 位?

iOS - 图像元数据未显示在 PC 中,在线解析器中可见

ios - Cocoapods: 没有这样的模块 'CorePlot'

ios - 检测 View Controller 何时可见

ios - 如何在不重置位置的情况下更改UIButton?

ios - Facebook 登录失败,代码为 190 - "The access token was invalidated on the device"