swift - first自动完成后启动另一个后台进程

标签 swift background-process

我有这个方法

func reminderInitialSetup() {
         DispatchQueue.global(qos: .background).async {

        let center = UNUserNotificationCenter.current()
        center.removeAllPendingNotificationRequests() 

        for i in (0..<self.arrayMyGoals.count) {

            let tempDict1 = self.arrayMyGoals[i] as! NSMutableDictionary;

            var goal_days : String!

            guard let days = tempDict1.value(forKey: "goal_dates") as? String else{
                return
            }
            goal_days = days

            let goal_time = tempDict1.value(forKey: "goal_time") as! String;

            let goal_name = tempDict1.value(forKey: "goal_name") as! String;

            let goalId : Int!

            goalId = tempDict1.object(forKey: "goal_id") as? Int                
            if goal_days.count > 0 {

                var datesArray = [Any]()

                datesArray = goal_days.components(separatedBy: ",")

                for  j in (0..<datesArray.count){

                    self.setReminder(date: datesArray[j] as! String, time: goal_time, title: goal_name, goalId: String(goalId))

                }
            }


        }
        DispatchQueue.main.async {

        }
    }

}

当我在后台单击按钮时从 web 服务获得响应时调用此方法。当我再次按下按钮时,碰巧该方法正在后台执行,并且 arrayMyGoals 中的对象数量发生变化,从而导致崩溃。 我想在上一个完成后自动启动另一个后台进程

我怎样才能做到这一点

最佳答案

您可以为此使用操作队列。示例:

let operationQueue: OperationQueue = {
    let operationQueue = OperationQueue()
    operationQueue.qualityOfService = .background
    operationQueue.maxConcurrentOperationCount = 1
    return operationQueue
}()

func runTask(id: String) {
    // optional: cancel all previous operations if about to start a new one
    // operationQueue.cancelAllOperations()
    operationQueue.addOperation {
        var wait = 0
        for _ in 0 ..< 10000 {
            wait += 1
        }
        DispatchQueue.main.async {
            print("task \(id) finished")
        }
    }
}

runTask(id: "t1")
runTask(id: "t2")
runTask(id: "t3")

输出:

task t1 finished
task t2 finished
task t3 finished

关于swift - first自动完成后启动另一个后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54180138/

相关文章:

android - 推荐一个靠谱的方法让app关闭后继续运行

ios - 从 AppDelegate 呈现一个 ViewController,它显示出来但导航栏未激活,我无法从那里转换到任何其他 View

ios - graphRequest.start 不返回任何数据

objective-c - 在 swift3.2/4 中正确解除分配 MTAudioProcessingTapRef

swift - 在 swift 自定义 UITabBar 中选择项目

computer-science - 如何运行雅典娜 |公鸡 |伊莎贝尔远程编码?

background-process - Jesque 如何使用 Huge Payload?

Ocaml:获取进程的 CPU 使用率

iOS - 后台 BLE 扫描随机卡住

ios - 根据背景颜色调整图标颜色