我现在完全无助,我正在尝试发送一封电子邮件以在 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/