简体   繁体   中英

Multiple alerts on top of each other in swift

Right now I'm getting error: Warning: Attempt to present UIAlertController: 0x7f9af9016200 on CollectionViewController: 0x7f9af750d620 which is already presenting (null)

Is there way i can stack alerts in swift? There is my code, it shows alert if item is posted more than day ago. Two ways i have tried to do this but not succeeded.

  1. Pause the for loop until i press yes or no.
  2. Present many alerts on top of each others

Any solutions how to manage to do this?

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)
    }
}

To show alerts after one another, i would suggest to add this recursive code,

Add a class variable for messages and fill the array for all the true conditions. After that you have to just call the showAlert method that will handle showing all the messages one by one.

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM