swift 中的多个警报相互叠加

Multiple alerts on top of each other in swift

现在我收到错误: 警告:尝试在 CollectionViewController 上呈现 UIAlertController:0x7f9af9016200:0x7f9af750d620 已经呈现(空)

有什么方法可以在 swift 中堆叠警报? 这是我的代码,如果项目是在一天前发布的,它会显示警报。 我尝试过两种方法但没有成功。

  1. 暂停 for 循环,直到我按是或否。
  2. 在彼此之上显示许多警报

任何解决方案如何做到这一点?

for p in json! {
     if self.checkDaysPassed(postDate: p["uploadedTime"] as! String) > 1 {
     print("more than one day passed, sell item?")

     let alert = UIAlertController(title: "Sell this item", message: "This item has been unused for a day", preferredStyle: .alert)
     alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
     alert.addAction(UIAlertAction(title: "Yes", style: .default){ (action) in
           print("pressed yes")
     })
     alert.addAction(UIAlertAction(title: "No", style: .cancel){ (action) in
          print("pressed no")
     })
     self.present(alert, animated: true)
    }
}

为了一个接一个地显示警报,我建议添加这个递归代码,

messages添加一个class变量,并为所有true条件填写array。之后,您只需调用 showAlert 方法,该方法将处理一条一条地显示所有消息。

class YourClass {

   var messages: [String] = []


   func yourMethod() {
       for p in json! {
         if self.checkDaysPassed(postDate: p["uploadedTime"] as! String) > 1 {
             messages.append("This item has been unused for a day")
         }
       }
       self.showAlert()
   }

   private func showAlert() {
        guard self.messages.count > 0 else { return }

        let message = self.messages.first

        func removeAndShowNextMessage() {
            self.messages.removeFirst()
            self.showAlert()
        }

        let alert = UIAlertController(title: "Sell this item", message: message, preferredStyle: .alert)
        alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        alert.addAction(UIAlertAction(title: "Yes", style: .default){ (action) in
            print("pressed yes")
            removeAndShowNextMessage()

        })
        alert.addAction(UIAlertAction(title: "No", style: .cancel){ (action) in
            print("pressed no")
            removeAndShowNextMessage()
        })

        UIApplication.shared.delegate?.window??.rootViewController?.present(alert, animated: true)
    }
}