且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

应用在前台 iOS 时获取推送通知

更新时间:2022-12-27 11:40:13

如果应用程序在前台运行,iOS 将不会显示通知横幅/警报.那是设计使然.但是我们可以通过使用UILocalNotification来实现,如下

If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. But we can achieve it by using UILocalNotification as follows

  • 检查应用程序在接收远程时是否处于活动状态
    通知.如果处于活动状态,则触发 UILocalNotification.

  • Check whether application is in active state on receiving a remote
    notification. If in active state fire a UILocalNotification.

if (application.applicationState == UIApplicationStateActive ) {

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.userInfo = userInfo;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.alertBody = message;
    localNotification.fireDate = [NSDate date];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

斯威夫特:

if application.applicationState == .active {
    var localNotification = UILocalNotification()
    localNotification.userInfo = userInfo
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.alertBody = message
    localNotification.fireDate = Date()
    UIApplication.shared.scheduleLocalNotification(localNotification)
}