我有一个快速的应用程序。
我从服务器收到GCM推送通知。
在IOS中,我了解操作系统会在我的应用程序位于bg时显示通知。
当我的应用程序在fg上时,如何显示推送消息(通知)并且我是负责显示通知的人?
我应该使用local-push(与远程推送相比)吗?
当应用程序在bg中时,显示推送的代码是什么?
我知道此代码处理向用户显示推送
但它不是通知,它只是打开警报
func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("Notification received: \(userInfo)")
// This works only if the app started the GCM service
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// [START_EXCLUDE]
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
// [END_EXCLUDE]
}
答案 0 :(得分:1)
您将收到通知(在userInfo中),但如果应用程序位于前台,则不会显示。您可以做的是触发本地通知或在应用程序位于前台时使用UIAlertView。
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
application.applicationIconBadgeNumber = 0; //For resetting the badge number to zero.
if (application.applicationState == UIApplicationStateActive) //For checking if app is in foreground.
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification received:" message:[NSString stringWithFormat:@"Received notification while app was in foreground:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}
答案 1 :(得分:0)
如果您想在应用程序位于前台时处理通知,则可以使用此类https://github.com/LeoNatan/LNNotificationsUI之类的自定义横幅。 代码应如下所示:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (application.applicationState == UIApplicationStateActive)
{
LNNotification* notification = [LNNotification notificationWithMessage:@"Notification Message"];
[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"app_identifier"];
}
}