Swift-如何在后台获取某些静默通知,在前台获取其他静默通知?

时间:2019-07-16 16:25:10

标签: ios swift push-notification

在我的应用程序中,用户可以彼此发送聊天消息并下订单(类似于OfferUp)。我使用无提示推送通知,但没有问题。

我想要做的就是拥有它,这样当用户A向用户B发送订单时,无论用户B位于background还是foreground中,都会通过静默通知。

但是,当userA向userB发送消息时,仅当userB仅在background中时,静默通知才应通过。如果userB在前台,则不需要通知。

我将orderId用于订单,将messageId用于邮件。

我在App Delegate's中收到静默通知:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    let userInfo = notification.request.content.userInfo

    // I can parse userInfo and get the messageId or the orderId

    guard let userInfo = userInfo as? [String: Any] else { return }

    if let orderId = userInfo["orderId"] as? String {
    }

    if let messageId = userInfo["messageId"] as? String {
    }
}

OrderVC:

func orderWasPlacedNowSendNotification() {

    let urlString = "https://fcm.googleapis.com/fcm/send"

    var apsDict = [String: Any]()
    apsDict.updateValue(title, forKey: "title")
    apsDict.updateValue(body, forKey: "body")
    apsDict.updateValue(1, forKey: "content-available")

    var dataDict = [String: Any]()
    dataDict.updateValue(orderId, forKey: "orderId") // orderId

    var paramDict = [String: Any]()
    paramDict.updateValue(apsDict, forKey: "notification")
    paramDict.updateValue(toToken, forKey: "to")

    paramDict.updateValue(dataDict, forKey: "data")

    let request = NSMutableURLRequest(url: url as URL)
    URLSession.shared.dataTask(with: request as URLRequest) ...
}

MessageVC:

func messageWasSentNowSendNotification() {

    let urlString = "https://fcm.googleapis.com/fcm/send"

    var apsDict = [String: Any]()
    apsDict.updateValue(title, forKey: "title")
    apsDict.updateValue(body, forKey: "body")
    apsDict.updateValue(1, forKey: "content-available")

    var dataDict = [String: Any]()
    dataDict.updateValue(messageId, forKey: "messageId") // messageId

    var paramDict = [String: Any]()
    paramDict.updateValue(apsDict, forKey: "notification")
    paramDict.updateValue(toToken, forKey: "to")

    paramDict.updateValue(dataDict, forKey: "data")

    let request = NSMutableURLRequest(url: url as URL)
    URLSession.shared.dataTask(with: request as URLRequest) ...
}

如何分隔静默通知?

1 个答案:

答案 0 :(得分:0)

根据您的逻辑,您需要在willPresent内返回

if application.applicationState == .active {   
    completionHandler([])  // no alert/sound
}
else if application.applicationState == .background  { 
     completionHandler([.sound,.alert]) // alert with sound
} 

您可以根据需要添加更多支票,但最后一次可以分别返回任何用于slient / alert的补全