Reputation: 2160
I am implementing APNS in my iOS application. I am getting apple push notifications in foreground, but when my app goes in background or inactive mode, my app does not receive any push notification.
My code which I tried is as follows:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
NSLog(@"active");
NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];
NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Active" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}else if (state == UIApplicationStateBackground){
NSLog(@"background");
NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];
NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Background" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}else{
NSLog(@"Inactive");
NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];
NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Inactive" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Please tell me where I am going wrong or missing something.
Upvotes: 2
Views: 749
Reputation: 394136
You are not supposed to display the notification programatically when the app is in the background or inactive. iOS displays the alert
text of the aps
dictionary automatically when the app is in one of these states, and your code is called only after the notification is displayed and tapped by the user to open your app.
If the user doesn't open your app by tapping the notification, your code will never be called. In addition, the didReceiveRemoteNotification
method is only called if the app is active or running in the background. If it is not running, a different method is called - application:didFinishLaunchingWithOptions
.
Upvotes: 2