0
I have an app that is in Object-C and I’m trying to pass it to Swift, but I’m having some problems, one of them is Nsnotification that is not working.
In Object-C, I’m using it as follows:
- (void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[super viewDidLoad];
}
- (void) applicationDidEnterBackground:(NSNotification*)notification {
NSLog(@"Entro em back");
}
In Swift I’m trying this way, but this not calling the function:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
func applicationDidEnterBackground() {
println("Entro em back")
}
In my case, I need to upload information to Nsuserdefaults when the app loads and saves user-changed information when the app enters the background.
Note: I can’t access any of the two functions.
The code is working perfectly. Probably your View Controller is not being instantiated correctly. Check where it is instantiated.
– Rafael Leão
It is not easier to use delegate of
AppDelegate
?– Paulo Rodrigues
@I don’t know, is it usual? The guy who taught me to 'program' for IOS said that it was not common to make changes in Appdelegate, so much so that in the project Objective-C I had to create the
NSNotification
– David Batista
@Rafaelleão am not with the code here, but I created in Viewcontroller which is created as default in the project. She is blank yet! rs
– David Batista
@Davidbatista good, these methods are in the
AppDelegate
just for this purpose. There are the two you need, bothapplicationDidEnterBackground
how muchapplicationWillEnterForeground
.– Paulo Rodrigues
@Paulorodrigues now the question is... how to access the information of my Viewcontroller by the 'Appdelegate'?
– David Batista
@Paulorodrigues These methods are only interesting in some cases, in others the notifications are more interesting.
– fpg1503
@Davidbatista Just a friendly Minder: don’t use
NSUserDefaults
for different things of user preferences and App settings.– fpg1503
@fpg1503 sorry but did not understand! ... In my case it is to store two screen information ('String' / 'Int')... that the user can change.
– David Batista