我正在iOS应用程序中实现APNS。我在前台收到苹果推送通知,但当我的应用程序进入后台或非活动模式时,我的应用程序没有收到任何推送通知。
我尝试过的代码如下:
- (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];
}
}
请告诉我哪里出错了或遗失了什么。
答案 0 :(得分:2)
当应用程序处于后台或处于非活动状态时,您不应以编程方式显示通知。当应用处于其中一种状态时,iOS会自动显示alert
字典的aps
文字,并且只有在显示通知并由用户点按以打开您的应用后才会调用您的代码。< / p>
如果用户未通过点击通知打开您的应用,您的代码将永远不会被调用。此外,仅当应用程序处于活动状态或在后台运行时,才会调用didReceiveRemoteNotification
方法。如果它没有运行,则会调用另一种方法 - application:didFinishLaunchingWithOptions
。