Reputation: 47
I am developing a chat application using xCode, Swift, Firestore, and OneSignal for notifications. Everything is set up and I am receiving notifications accordingly, but I want to filter (hide, show) some notifications based on some conditions. For example, I don't want the push notification about "new message" to appear to the user if they're currently chatting with that person, as they're already seeing the message in the current chat view. Is there any way I can achieve this with OneSignal?
Upvotes: 2
Views: 763
Reputation: 5634
You can change appDelegate like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
print("Received Notification: \(notification!.payload.notificationID)")
NotificationCenter.default.post(name: "ReceivedNotification", object: self, userInfo: notification!.payload) // post notification to view controller
}
let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
// This block gets called when the user reacts to a notification received
}
let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false,
kOSSettingsKeyInAppLaunchURL: true]
OneSignal.initWithLaunchOptions(launchOptions,
appId: "YOUR_ONESIGNAL_APP_ID",
handleNotificationReceived: notificationReceivedBlock,
handleNotificationAction: notificationOpenedBlock,
settings: onesignalInitSettings)
OneSignal.inFocusDisplayType = OSNotificationDisplayType.none //Notification is silent and not shown
return true
}
And your chat room view controller:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self,
selector: #selector(receivedNotification(_:)),
name: "ReceivedNotification", object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: "ReceivedNotification", object: nil)
}
@objc func receivedNotification(_ notification: Notification) {
let notificationPayload = notification.userInfo
//check the message belongs to this room then if you want show your local notification , if you want do nothing
}
Upvotes: 1