【问题标题】:BackGround App refresh and apple push notifications.背景应用刷新和苹果推送通知。
【发布时间】:2014-05-29 18:23:40
【问题描述】:
在我的应用中,我使用的是 APNS。当应用程序正在运行并处于前台状态时,我会收到推送通知。当我按下主页按钮时,我无法接收推送通知。
我需要帮助有两个原因
- 当我的应用处于后台状态时,如何获得推送通知?
- 如果我的应用程序未运行或未启动并且推送通知来了,我想在后台更新数据而无需用户点击。
如果您能给我一个简短的教程,我将不胜感激。提前致谢
我的代码是:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
if(application.applicationState == UIApplicationStateActive)
{
NSLog(@"Active");
[self addData];
}
else
{
NSLog(@"Not active");
[self addData];
}
}
【问题讨论】:
标签:
ios
objective-c
apple-push-notifications
【解决方案1】:
请按步骤操作
首先你必须在 appdelegate 中注册推送通知
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
现在检查通知的启动选项。
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{}
现在保存通知的令牌ID并发送到服务器
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSString* deviceT = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
[UserDefault setDeviceToken:deviceT];
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
}
现在在设备设置中检查通知中心您的应用程序是否存在。如果您的应用程序不在列表中,那么您将不会收到通知。如果您的应用程序是后台的,推送通知总是会出现。您可以先查看设备设置-通知中心-您的应用可用性。
- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if(app.applicationIconBadgeNumber!=0)
{
app.applicationIconBadgeNumber = app.applicationIconBadgeNumber - 1;
}
if (app.applicationState == UIApplicationStateInactive)
{
}
else if (app.applicationState == UIApplicationStateActive)
{
[self showNotificationInActiveMode:userInfo.alertBody];
}
}
对于第二点,除非应用程序未运行,否则您无法更新数据。如果要更新数据,则必须单击推送通知以启动或在前台打开应用程序。
如果没有运行或未启动,则无法更新数据。