簡體   English   中英

處理應用未運行時將顯示推送通知

[英]Handling which Push Notifications will show when app is NOT Running

介紹

我對fcm / gcm如何工作以及swift應用程序如何處理接收和發送這些推送通知有基本的了解

問題

當應用程序處於前台時,我已經創建了一個代碼,我可以選擇將哪個通知顯示為橫幅。

我將該代碼放在AppDelegate此函數中

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)

然后,我將按照系統默認值過濾推送通知我放入NSUserDefaults swift 2.3UserDefaults for 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 /服務器代碼的情況下工作嗎?

技術上不可能。 當應用程序未運行時,您無法執行此代碼。 當您的應用未處於活動狀態時,您無法隱藏通知。 唯一可行的方法是從服務器代碼處理此問題。

如果您真的無法通過服務器代碼執行此操作,請使用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 
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM