Apple recommends dismissing any UIAlertViews/UIActionSheets
when entering background state in iOS 4. This is to avoid any confusion on the user's part when he relaunches the application later. I wonder how I could elegantly dismiss all UIAlertViews at once, without retaining a reference to it everytime I set one up...
Any idea ?
The straightforward way is to hold a reference to the UIAlertView so you can dismiss it. Of course as petert mentioned you can do it with a Notification or use the delegate method on UIApplication
does not always mean that you are going to the background. You will for example also receive that delegate call and notification (you get both) when the user gets a phone call or receives and SMS. So you have to decide what should happen if the user gets an SMS and presses cancel to stay in your app. You maybe want to make sure that your UIAlertView is still there.
So I would dismiss the UIAlertView and save the state in the delegate call when you really go into the background:
Have a look at Session 105 - Adopting Multitasking on iOS4 of WWDC10 available for free at developer.apple.com. It gets interesting at 16:00 min
Check out this graphic to understand the different states of an application
Create category on UIAlert View
Use http://nshipster.com/method-swizzling/ Swizzle "show" method
Keep track of alert view shown by keeping week references in array.
- When you want to remove all data call Dismiss on saved alert views and empty an array.
A totally different approach is a recursive search.
Recursive function for your application delegate
Calling it from the applicationDidEnterBackground procedure
My call would be to add a category to UIAlertview adding the following function :
And to suscribe to
UIApplicationWillResignActiveNotification
:As someone mentioned in a comment: the accepted answer isn't the best/cleanest one since iOS 4.0 when we have blocks! Here's how I do it:
if you only have one or two specific alert windows you show (as do most apps), then you can just create an
assign
ivar to the alert:Then, in the app delegate:
You can put this in
applicationDidEnterBackground:
or wherever you see fit. It closes the alert programmatically upon application exit. I've been doing this and it works great.