等待直到添加了通知,然后继续执行我的其余代码?

时间:2018-09-15 23:48:09

标签: swift

当用户点击“保存”按钮时,我的应用程序会安排64条通知。如果添加通知时出错,我想显示一条错误消息。但是,通知的添加是异步发生的,因此我无法及时发现错误。如何让我的线程等待所有通知添加完毕后才能继续?由于异步功能,我的变量errorSettingUpNotifications始终等于false,因此我底部的错误检查当前无法正常工作。

    var errorSettingUpNotifications = false
    for i in 0...maxNumberOfReminders
    {
        let randomWordIndex = Int(arc4random_uniform(UInt32(Int(words.count - 1))))
        let content = UNMutableNotificationContent()
        let identifier = "Word\(i)"
        content.title = "Word Of The Day"
        content.body = "\(Array(words)[randomWordIndex].key) - \(Array(words)[randomWordIndex].value)"
        let trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: Calendar.current.date(byAdding: .day, value: i, to: startDate)!), repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request){
            (error) in
            if error != nil
            {
                errorSettingUpNotifications = true
            }
        }
    }
    if (errorSettingUpNotifications == true)
    {
        SVProgressHUD.showError(withStatus: "There was an error setting up your notifications. Please check your internet connection and try again.")
    }
    else
    {
        SVProgressHUD.showSuccess(withStatus: "Settings saved successfully")
    }

1 个答案:

答案 0 :(得分:1)

您可以使用DispatchGroup来实现。来自Apple Documentation

  

DispatchGroup允许工作的聚合同步。您可以使用它们来提交多个不同的工作项,并跟踪它们的完成时间,即使它们可能在不同的队列中运行。

这是它的工作方式。

// Create a dispatch group
let group = DispatchGroup()

var errorSettingUpNotifications = false

for i in 0...maxNumberOfReminders {
    // New block started
    group.enter()

    // Setup notification

    UNUserNotificationCenter.current().add(request) { (error) in
        if error != nil {
            errorSettingUpNotifications = true
        }
        // Block completed
        group.leave()
    }
}

group.notify(queue: .main) {
    if errorSettingUpNotifications {
        // Show error message if failed
    }
}