处理应用未运行时将显示推送通知

时间:2016-11-24 06:04:46

标签: ios swift google-cloud-messaging firebase-cloud-messaging

简介

我基本了解fcm / gcm如何工作以及快速应用程序如何处理接收和发送这些推送通知

问题

当应用程序处于前台时,我已经创建了一个代码,我可以选择将哪个通知显示为横幅。

我将该代码放在AppDelegate

中的此函数中
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)

然后我将按系统默认值过滤推送通知我放入NSUserDefaults swift 2.3 UserDefaults swift 3

我有一个易于获取和设置的类,看起来像这样

class Persistence {
    static let defaults = NSUserDefaults . ....
    static var doShowMessageNotification:Bool {
        get {
            return defaults.get ...
        }
        set(value) {
            defaults.set ...
        }
    }
}

// you get the idea

然后再次进入didRecieveRemoteNotification

switch Persistence.doShowMessageNotification {
case true:
    doThis()
case false:
    break //do nothing in short
}

然后我将检查应用程序状态是否为

func doThis() {
    switch UIApplication.sharedApplication().applicationState {
    case .Active:
        // do some stuff here
    case .Inactive, .Background:
        // do some stuff here       
    }
}

当应用程序正在运行或处于待机状态时,此功能非常有效,但在应用程序终止/关闭时无效。

无论如何都可以在不更改API /服务器代码的情况下工作吗?

1 个答案:

答案 0 :(得分:1)

技术上不可能。当应用程序未运行时,您无法执行此代码。当您的应用未处于活动状态时,您无法隐藏通知。唯一可行的方法是从服务器代码处理此问题。

如果您真的无法通过服务器代码执行此操作,请使用Notification content extension中的Notification content Extension.,您可以处理要在通知中显示的内容。如果您不想从此处显示特定通知,则可以将内容更改为某些默认消息 在扩展程序的plist中,将UNNotificationExtensionDefaultContentHidden设置为false。这将隐藏从服务器收到的默认通知文本,并显示您可以显示所需内容的视图。

您可以在NotificationViewController.swift文件的didReceive方法中获取通知详细信息。

@IBOutlet var titleLabel: UILabel?
@IBOutlet var subtitleLabel: UILabel?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any required interface initialization here.
}

func didReceive(_ notification: UNNotification) {
  if(requiredtoDisplay)
  {
    titleLabel?.text = notification.request.content.title
    subtitleLabel?.text = notification.request.content.subtitle
 }
else
 {
     titleLabel?.text = "default text"
    subtitleLabel?.text = "default tex"  //or call api  to update device token with "" , if you don't want to receive further notification after this 
 }
}