3

介紹

我FCM/GCM如何工作的一個基本的瞭解,以及如何SWIFT應用手柄接收和發送這些推送通知處理該推送通知將顯示,當應用程序沒有運行

問題

當應用程序在前臺時,我做了一個代碼,我可以選擇將哪個通知顯示爲橫幅。

我把這個函數裏面的代碼裏面AppDelegate

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

然後我會過濾系統默認設置推送通知我把裏面NSUserDefaultsSWIFT 2.3UserDefaults迅速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 /服務器代碼的情況下工作?

+0

這是不可能的,如果應用程序已被迫退出。 http://stackoverflow.com/a/26587688/4539192 – Rikh

+0

我的意思是,我想選擇顯示哪些推送通知,而不是哪個推送通知來處理動作。請原諒我的英語 因此,根據我的理解,真的沒有辦法做到這一點,我真的應該只是玩API /服務器代碼? –

+1

這是正確的。如果您的應用程序未運行,則通知由iOS處理,您的應用程序不會被調用 – Paulw11

回答

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 
} 
} 
+0

良好的回覆隊友。但我無法編輯我的信息。plist的原因是隻讀的,如果我要創建我的應用程序的「設置」部分。我猜服務器編碼確實是這樣。 –

相關問題