I have created an Unity iOS App. The reason I have created the App on unity is because it can be easily ported to other platforms.
I am communicating with Axivity Sensors via BLE technology. Everything is working fine. But now I want to run the app in background. So for that I found that I should use UIApplicationDidBecomeActiveNotification and UIApplicationWillResignActiveNotification notifications so that I can do some background processing.
But sometimes I am not notified when App becomes active or deactive.
Is there anything that I am doing wrong or is there a better way to do that ?
Following is the code:
-(id) init {
self = [super init];
if (!self) return nil;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
return self;
}
-(void)appWillResignActive:(NSNotification*)note {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(BLEOnCharactersticsUpdateNotification:)
name:BLEOnCharactersticsUpdate object:nil];
}
-(void)appDidBecomeActive:(NSNotification*)note {
NSLog(@"AppDidBecomeActive ");
[[NSNotificationCenter defaultCenter] removeObserver:self name:BLEOnCharactersticsUpdate object:nil];
for(int timeStampIndex = 0; timeStampIndex < [timeStampArray count]; timeStampIndex++) {
NSLog(@"TimeStamp %i : Value : %@",timeStampIndex,[timeStampArray objectAtIndex:timeStampIndex]);
}
}
-(void)appWillTerminate:(NSNotification*)note {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
How do you guarantee that the object from the code sample exists during whole application lifecycle?
Most likely, it's deallocated at some point of execution, that's why it doesn't receive the notifications. iOS itself guarantees that the app always receives at least UIApplicationDidBecomeActiveNotification and UIApplicationWillResignActiveNotification.
P.S.You subscribe for notifications in init method. And unsubscribe in appWillTerminate. A better place to unsubscribe would be dealloc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With