我有这个方法
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/