iPhone app entering background state and presenting a UIAlertView - iphone

If an app delegate receives the -willResignActive message and a UIAlertView is within 0.5 seconds of being shown, the app will present two alert views (one a duplicate) when it becomes active once more.
This is a problem, because if responding to the first alert view means there are no responders to the duplicate (likely!) the app will just crash.
Thoughts?

The best solution I have is to retain a static reference to a UIAlertView, dismiss (with clicked button index -1), release, and then allocate/init a new instance at the same address. This makes sure there's only ever one alert view scheduled or showing. If an alert view is already showing, ignore (or manage) the new request (failsafe popping to root view or some such).
It's not very satisfactory because UIAlertViews have nothing to do with the workings and shouldn't be static. In my mind at least.

Related

Dismissing a UIAlertView

I put an in app purchase into my app, and when the user taps a button, the purchase is started. So basically, they tap the button, and then depending on the speed on their Internet connection, they could be waiting for up to ten seconds until a new alert view comes up asking if they would like to buy the product. The user will probably tap the button multiple times since nothing came up, and then multiple purchase alert views will come up. Additionally, this could maybe be seen by the user as an app bug. In the end, this is a problem.
I want an alert view to come up with a spinning wheel that says "Loading..." when the users taps the buy button. Now my problem is, how do I get that to dismiss when the new alert view comes up asking the user if they want to buy the product?
if ([UIAlertView alloc] that says: #"whatever Apple's alert view says")
{
//dismiss the "Loading..." alert view here
}
I doubt that would work, so any input is appreciated. Thanks!
You need to have access to that alertview. You can do this. Create a alertview instance var in app delegate and when you want to show loading initialize that instance var assign to your property and when you want to dismiss just call
[alertViewinstance dismissWithClickedButtonAtIndex:0];
Write this piece of code in a method in appDelegate. Hope you get the idea. If not let me know I'll post the sample code here.

Objective-C object dealloc'd while other objects still has a delegate reference to it causes crashes. How to prevent this?

I have an app with a navigation controller as the root view. There are many views that can be pushed in.
The user has to create an account to use the app. The user can then log into this account from other devices, but only one device can be logged onto the same account at a time. So if multiple devices try to log into an account, only the latest device will be logged in and the other devices are logged off (a push is sent to the devices).
Since there are multiple views that the device could be showing before it was logged off, I call popToRootViewControllerAnimated: to get back to the root view. This is because when the user logs in the next time I only want the root view to be shown (the new account might not have access to the previously shown view).
If the user has an alert view or action sheet presented (which uses the current view as its delegate) before the push is received, the view will still be shown after the popToRootViewControllerAnimate: method is called. If the user then taps on a button for the alert view or action sheet, it will send a message to the dealloc'd view and crash the app.
An example:
myViewController is being shown to the user.
myViewController create an action sheet prompting the user for a decision.
The push is received for the device to log out.
The navigation controller pops all the views controllers and now shows myRootViewController.
Since the view controllers are popped, myViewController is now dealloc'd.
The action sheet from myViewController is still shown.
When the user selects an option form the action sheet, a message is sent to myViewController, and since it is already dealloc'd, a crash will occur.
Is there any way to prevent this?
One solution I have considered would be to keep track of all the objects that uses a specific view controller as its delegate. Then when that view controller dealloc's it will also set all the object's delegates to nil. This requires me to manually take care of every view controller when they create an object that uses itself as the delegate, since I cannot think of a way to automatically create and update this list.
Any better solution (or improvement to mine) would be appreciated!
Edit: The alert view and action sheet are only examples of some objects that I would use myViewController as a delegate. I am also using a number of other classes (and third-party libraries) that implements this delegate pattern.
A few ideas:
you can encapsulate the alert/action sheet view and delegate in a single class. Then when you need an alert view, create MyAlertView instead, which will also be its own delegate and will do [self release] after the user taps a button.
make your App Delegate the only delegate for all your alert views and action sheets. App Delegate is always around while the application is running, so there won't be a problem with a released delegate.
The problem with both solutions is that if you need your application to know what happened in the alert view/action sheet, you somehow need to tell the interested class of the user's choice.
You can do that by either using delegates of your own - which would mean you're back to square one - or use notifications: when the alert view/action sheet delegate is called, it would post a notification ([[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:self userInfo:userInfo];), while the interested object would look for that notification ([[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onNotification:) name:NotificationName object:nil];) and perform whatever tasks necessary in onNotification:(NSNotification*)aNotification method.
You'll be able to agree with yourself on what type of information is passed in those notifications (I would think the button number in a NSNumber class would be enough, or perhaps pass the button text, too). And you won't have to keep track of all alert views - just don't forget to remove the observer ([[NSNotificationCenter defaultCenter] removeObserver:self name:postNotificationName object:nil];) in the views' dealloc.
Edit:
"This requires me to manually take care of every view controller when they create an object that uses itself as the delegate, since I cannot think of a way to automatically create and update this list."
Actually you probably can do this in a semi-automated way: make a singleton object with a method like
-(id)delegate:(id)delegate for:(id)forWhom
And then instead of
someThingy.delegate = self;
you'd do
someThingy.delegate = [[DelegateLocker defaultLocker] delegate:self for:someThingy];
Inside the DelegateLocker you'd have a MutableDictionary with delegate class as a key and a MutableArray of someThingies as a value. Then in your view controllers' deallocs you'd call
[[DelegateLocker defaultLocker] delegateIsDying:self];
which would go through the thingies and assign delegate = nil for each
The drawback of course is that you'll be retaining all the thingies for an indefinite period of time instead of releasing them immediately.
So the ViewController that presented the action sheet iand set itself as the delegate right? So why dont you keep a reference to the ActionSheet in the ViewController, in the dealloc method of the view controller, you can check if the action sheet is visible, if it is then set the delegate of the action sheet to nil,and dismiss it...
so
-(void)dealloc
{
if(myActionSheet && [myActionSheet visible])
{
[myActionSheet setDelegate: nil];
//dismiss
}
}
Hope that helps
If you want automated solution, I think you can make a function to iterate through Ivars of your view controller to see if any Ivar has delegate property and set it to nil.

viewDidAppear not firing ever again after app enters foreground

I have traced a problem in my iPhone app code to the viewDidAppear method not always firing. When you start the app the event fires as expected. However if I close the app using a phone capable of multitasking and reopen in. My viewDidAppear events no longer fire.
My views are loaded from Nibs and I use viewDidUnload to clean up (release and nil all outlets). My views are nested in side and tab bar then navigation controllers. I looks like the events aren't wired up properly when the nibs reload. Any idea on what I'm doing wrong/missing and how I can fix this?
Thanks in advance.
UPDATE I do not mean the event is not fired when the app first comes into the foreground. I mean the event never fires again. Even when changing between tabs or moving though the navigation views.
Example:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(#"viewDidAppear called");
}
This code is placed in two views, each on different tabs. Each time I swap between tabs "viewDidAppear called" is written to the log. When I close and reopen the app and swap between tabs this no longer happens. Other button events fire normally.
Btw, the viewDidUnload method is really badly named btw -- it's not an 'opposite' to viewDidLoad, it's only called if there was a low memory situation and the view for that controller was unloaded due to not being visible at that time.
(ORIGINAL, NOT SO RELEVANT ANSWER:)
Please see my answer to this similar question:
Why does viewWillAppear not get called when an app comes back from the background?
Basically, viewDidAppear gets called after your UIViewController's view was added to the application's UIWindow heirarchy. Backgrounding then restoring the app doesn't change your view in that respect, so viewDidAppear doesn't get called -- it's correct behaviour, and not a bug. Check out the API docs for UIViewController.
Found it.
While not new to programming I am new to iPhone development. On researching this problem I found it was not recommended to call the viewWillAppear and viewWillDisappear methods manually.
My viewWillDisappear methods resign any keyboards if shown, when my app enters the background it loads a splash screen ready for when the app re-enters the foreground (there is some logic I need to do to work out what the user is shown on restarting the app and I can do this under the splash screen).
As viewWillDisappear is not called when the app goes into the background to make sure no keyboards appeared over my splash screen I was calling viewWillDisapper in the applicationDidEnterBackground method. I guess this also un-registers my events.
By adding viewWillAppear to my applicationDidEnterForeground method my events started firing again. Lesson learned, I will refactor this so I don't call these events manually.
Thanks for the help.

Dismiss or destroy all view controllers, action sheets, etc?

I'm implementing a custom URL scheme in my navigation based app to let users import data from an email, and so I have this method in my app delegate:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
It would be nice, if after importing the data in that method, I could use popToRootViewController to go back to the rootViewController to show the user the new data.
However, that doesn't work if the user had imported the data while a modal view controller or action sheet was up (popToRootViewController doesn't dismiss those, and causes the app to freeze).
Is there any way I can safely dismiss/destroy all view controllers/action sheets/alert views except for the rootViewController?
Or perhaps some way to tell from within my app delegate if the user has an action sheet or modal view controller up?
Or, do I just leave them where they left off, and not provide any immediate indication that data was successfully added?
You'll have to keep track of them yourself. An easy way to do that is to post a notification, with a reference to the modal view/sheet/alert in the userinfo dictionary, every time you display something modal. Whenever a modal view returns, post a different notification.
Observe the notifications in your app delegate (or wherever it makes sense to do so, but the app delegate is simplest). When you receive the first one, store a (weak) reference to the modal view, and zero the reference when you receive the second one. In between, you'll be able to respond to -application:handleOpenURL: by dismissing the modal view if your reference is non-nil.
Note also that in the case of alerts, it's probably best to dismiss them when you enter the background. Weeks might pass before you are foregrounded again, and it's bad style to greet the user with "Are you sure? OK/Cancel" when they may no longer have any idea what you're asking about.

UIAlertViewDelegate clickedButtonAtIndex: usefulness?

The UIAlertViewDelegate protocol defines two methods, alertView:clickedButtonAtIndex: and alertView:didDismissWithButtonIndex:, which seem to me to be identical in usefulness.
Why is there a clickedButtonAtIndex and a didDismissButtonWithIndex when they both do the same thing? I realize there is also a willDismissButtonWithIndex that happens before the alert view is dismissed, but is there any reason to use clickedButtonAtIndex instead of didDismissButtonWithIndex?
I found a more useful difference between the two:
When showing a UIAlertView, and the device goes to sleep, alertView:didDismissWithButtonAtIndex: gets called, even though the alert view is not actually dismissed. It is shown again once the device wakes up. alertView:clickedButtonAtIndex: is only called when the user clicks one of the buttons.
The alertView:clickedButtonAtIndex: is called when the user clicks a button on an alert view whereas the alertView:didDismissWithButtonIndex: is called after an alert view is dismissed from the screen. (See the UIAlertViewDelegate Protocol Reference.)
The difference is minimal but it allows you to do something before or after animation.
If the alert view disappears for any reason (including being covered by another UIAlertView, going to sleep, etc.), didDismissWithButtonAtIndex: is called. This can mean that the method can be called even without the user clicking on anything. This can lead to unexpected behaviour if you depend on this delegate callback to be called in response to the user actually clicking on a button. In this case clickedButtonAtIndex: is more useful.
I couldn't reproduce Ed's behaviour by locking my device with the alert view present on iOS 7.
However, the most important difference between alertView:clickedButtonAtIndex:, alertView:didDismissWithButtonIndex: and alertView:willDismissWithButtonIndex: is that the first method (clickedButtonAtIndex:) is only called when the user explicitly taps on a button on your alert view (hence 'clicked').
Is it possible that an alert view is dismissed without clicking on a button? Yes, you could programmatically hide an alert view using the UIAlertView method dismissWithClickedButtonIndex:animated:.
So, if you need some behavior to be always triggered upon the dismissal of the alert view—whether it was triggered by the user tapping on a button or triggered programmatically—then using the didDismissWithButtonIndex: and willDismissWithButtonIndex: makes more sense.