Call viewWillDisappear when user quits application ios - ios

I have an application that stores values in the viewWillDisappear method in one of my classes. For example, I store the data and time in the viewWillAppear method and the same again when in the viewWillDisappear method so I'm able to compare the time difference and log this out.
However, if the user presses the home button on the device, then the viewWillDisappear code is not run. I've tried to call this particular method in the AppDelegate's applicationDidEnterBackground, but this stores the wrong information as the viewWillDisappear method isn't actually run. I've also tried to store them in NSUserDefaults, but again, as the viewWillDisappear method isn't run, then the wrong values are stored.
Is there a way to make the viewWillDisappear method run for that view as soon as the user presses their home button?

In the viewWillAppear register for this notification...
-(void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(appEnteredBackground:)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
}
-(void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)appEnteredBackground:(NSNotification *)appEnteredBackgroundNotification {
//do your thing
}

Related

Save data from textField into a file when the application has closed or terminated

In my application has a view controller named "Home" with a textField.
I read about applicationDidEnterBackground and applicationWillTerminate methods in the AppDelegate file.
I know how to create, save, read data from a file.
My question is, How I can get an NSString from the "Home" viewController (that there store the textField data) to the AppDelegate applicationDidEnterBackground method and do there all my things with that data?
You could use NSNotificationCenter to register for a notification in your view controller that fires off whenever you enter applicationDidEnterBackground or applicationWillTerminate.
So in either of those methods you put something like
[[NSNotificationCenter defaultCenter] postNotificationName:#"someDescriptiveName" object:self userInfo:#{#"key" : #"value"}];
userInfo expects an NSDicitonary and you can pass it any type of object in there, in your case you dont need to pass anything from here back to your viewcontroller, your just using it as a means to let your view controller know the app is closing.
In your view controller you would register for that notification with something like this
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(methodToCall:) name:#"someDescriptiveName" object:nil];
Then whenever your appDelegate post that notification, your view controller which is registered to listen for it would fire off "methodToCall" which can be a method you right to do anything and it takes in an nsnotification which then lets you access the nsdicitonary its carrying.
- (void)methodToCall:(NSNotification *)notif{
NSLog(#"methodToCall fired with data %#",[[notif userInfo]valueForKey:#"key"]);}
You can do this with the help of this inside your controller:
-(id)init
{
if((self = [super init]))
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:[UIApplication sharedApplication]];
}
return self;
}
-(void)appDidEnterBackground:(NSNotification *)note {
NSLog(#"appDidEnterBackground");
}
you can also use applicationWillTerminate in place of UIApplicationDidEnterBackgroundNotification

NSNotificationCenter RemoveObserver Not Always Working

Normally I add my observers in viewWillAppear and remove them in viewWillDisappear. In this case I need one of the observers to continue even after the view is gone so that it can finish some work. In order to make sure that the observer is only added once with this view, I do the following:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:#"imageSaved"
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(postMessageWithImage:)
name:#"imageSaved"
object:nil];
}
I have performed a search through the rest of the application to ensure that this observer is NOT registered anywhere else. Unfortunately sometimes, but not all times and there is no consistent factor, the notification is fired twice. I have also ensured with breakpoints and NSLog that the postNotifcationName is NOT called more than once. I have not been able to reproduce on the iPhone as the problem seems confined to the iPad.
In further troubleshooting I have checked that the method is being called from the same thread (no reason it wouldn't be but just to check). This problem DOES go away if I put the removeObserverin viewWillDisappear, however, again that is not how I need this to work.
Clearly this is a case where the observer for this is being registered twice but I cannot find a reason why that would be. As you can see from the code, any time this observer is registered it is first removed. My only other thought is whether self could get "corrupted" such that the removeObserverwouldn't function properly?
Add your observer when the view will show, and remove it when will disappear.
ADD:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(postMessageWithImage:)
name:#"imageSaved"
object:nil];
}
REMOVE:
- (void)postMessageWithImage:(NSNotification*)aNotification
{
[[NSNotificationCenter defaultCenter]removeObserver:self
name:#"imageSaved"
object:nil];
// here do your job
}
This is perfectly valid and efficient.
Instead of adding the observer in viewWillAppear:, try adding the observer you wish to persist when the view disappears in viewDidLoad. Then you can call your removeObserver:name:object: in your dealloc method
If you just want something to be executed once, put it in the predicate of a dispatch_once() call, like
static dispatch_once_t lock;
dispatch_once(&lock, ^{
// put your addObserver call here
});

Why is my NSNotification its observer called multiple times?

Within an App I make use of several viewcontrollers. On one viewcontroller an observer is initialized as follows:
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(myMethod:) name:#"MyNotification" object:nil];
Even when removing the NSNotification before initializing the number of executions of myMethod: is being summed up by the amount of repeated views on the respective viewcontroller.
Why does this happen and how can I avoid myMethod: being called more then once.
Note: I made sure by using breakpoints that I did not made mistakes on calling postNotification multiple times.
Edit: This is how my postNotification looks like
NSArray * objects = [NSArray arrayWithObjects:[NSNumber numberWithInt:number],someText, nil];
NSArray * keys = [NSArray arrayWithObjects:#"Number",#"Text", nil];
NSDictionary * userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object:self userInfo:userInfo];
edit: even after moving my subscribing to viewwillappear: I get the same result. myMethod: is called multiple times. (number of times i reload the viewcontroller).
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(myMethod:) name:#"MyNotification" object:nil];
}
edit: something seems wrong with my lifecycle. ViewDidUnload and dealloc are not getting called, however viewdiddisappear is getting called.
The way I push my Viewcontroller to the stack is as follows where parent is a tableview subclass (on clicking the row this viewcontroller is initiated:
detailScreen * screen = [[detailScreen alloc] initWithContentID:ID andFullContentArray:fullContentIndex andParent:parent];
[self.navigationController pushViewController:screen animated:YES];
Solution:
Moving removal of nsnotification to viewdiddisappear did the trick. Thanks for guidance!
Based on this description, a likely cause is that your viewcontrollers are over-retained and not released when you think they are. This is quite common even with ARC if things are over-retained. So, you think that you have only one instance of a given viewcontroller active, whereas you actually have several live instances, and they all listen to the notifications.
If I was in this situation, I would put a breakpoint in the viewcontroller’s dealloc method and make sure it is deallocated correctly, if that’s the intended design of your app.
In which methods did you register the observers?
Apple recommends that observers should be registered in viewWillAppear: and unregistered in viewWillDissapear:
Are you sure that you don't register the observer twice?
Ran into this issue in an application running swift. The application got the notification once when first launched. the notification increases the number of times you go into the background and come back. i.e
app launches one - add observer gets gets called once in view will appear or view did load - notification is called once
app goes into background and comes back, add observer gets called again in view will appear or view did load. notification gets called twice.
the number increases the number of times you go into background and come back.
code in view will disappear will make no difference as the view is still in the window stack and has not been removed from it.
solution:
observe application will resign active in your view controller:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResign:", name: UIApplicationWillResignActiveNotification, object: nil)
func applicationWillResign(notification : NSNotification) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
this will make sure that your view controller will remove the observer for the notification when the view goes into background.
it is quite possible you are subscribing to the notifications
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object:self userInfo:userInfo];
before self gets initialized. And trying to unsubscribe 'self' which isn't really subscribed to, and you will get all global myNotification notifications.
If your view was hooked up in IB, use -awakeFromNib: as the starting point to register for notifications
It is possible that the class with the observer is, quite appropriately, instantiated multiple times. When you are debugging it will kinda look like the notification is being posted multiple times. But if you inspect self you might see that each time is for a different instance.
This could easily be the case if your app uses a tab bar and the observer is in a base class of which your view controllers are subclasses.

Call a method every time a UIViewController is shown

I want to show a full page image Ad every time a UIViewController is shown.
I think I have to call the method inside a viewDidAppear or ViewWillAppear, but they are being called once.
- (void) viewDidAppear:(BOOL)animated{
[self showAds];
}
- (void) showAds{
//Do Something
}
What should I do to call a method every time a uiviewcontroller is shown( even if its already created)?
ViewWillAppear will be called every time a UIViewController is shown,but won't be called when the app is back to foreground.
you can use Notification to achieve your goal by following code,
This scenario is specially when your app is in background and user press HOME button to active it.
Register for Notifcation when your application enterForground in viewDidLoad only.
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(handleEnteredBackground)
name: UIApplicationDidBecomeActiveNotification
object: nil];
write a method to invoke when application enterForground
-(void)handleEnteredBackground
{
NSLog(#"%s",__FUNCTION__);
// Your stuff here
}
Dont forget to Remove Observer in viewDidUnload method
[[NSNotificationCenter defaultCenter] removeObserver:self];
Post New Notification everytime your application enterForground
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidBecomeActiveNotification object:nil];
}
ViewWillAppear should be called every time. Use:
- (void) viewWillAppear:(BOOL)animated{
[self showAds];
}

XCode ARC Multiple instances of the same view

I am new to iOS development and I am writing a 3-View Location Application.
The first view is the main view of the application, the second view is a table view with several locations and the third view is a detail view, where the user is able to edit or add new Locations to the table view.
I'm using the CLLocationManager in the first and in the third view but every view of both has got his own CLLocationManager instances, because for the detail view I need the best accuracy whereas in the MainView I dont need the best accuracy.
So here is the problem:
In my AppDelegate.m I have got a notification, which fires when the Applications enters foreground:
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName: #"didEnterForeground" object: nil userInfo: nil];
}
In my third view, the DetailViewController.m, I register in the viewDidLoad for this notification:
- (void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(enteredBackground:) name: #"didEnterBackground" object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(enteredForeground:) name: #"didEnterForeground" object: nil];
}
The enteredForeground Method in DetailViewController.m just needs to start the Location Manager again (the didEnterBackground Method stopped him)
- (void) enteredForeground: (NSNotification*) notification {
[self.locationManager startUpdatingLocation];
}
I am using XCode 4.2 with ARC.
The problem is, that if I visited the DetailView for about 10 times, go to background (f.e. from the MainView), then I enter foreground again then 10 LocationManagers will be started immediately (this is what my NSLog says).
It seems that for the DetailView (and for the other Views) the same number of instances like the number of visits for these views exist.
Maybe the views dont get released properly if they disappeared, perhaps because of the NSNotification?!
I would appreciate if someone could help me with this matter, cause so many LocationManagers will stress the battery pretty hard.
Thanks in advance!
I believe you need to stopUpdatingLocation when it goes to the background. Otherwise, it will spawn multiple instances.

Resources