I want to show notification only in specific pages like if the userid obtained from payload of notification is not equal to the current userid. Where should I use this condition inside appdelegate? I have used willPresent delegate of userNotificationCenter to deliver the notification when app is in foreground and requesting permission to show notification method in didFinishLauchingWithOptions in AppDelegate.
Sample code of willPresent method is given below.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void){
if let userID = notification.request.content.userInfo["user_id"] {
self.userIDSelected = userID as! String
}
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
if self.currentuserID != self.userIDSelected
{
completionHandler([.alert,.badge,.sound])
}
else
{
completionHandler([])
}
}
Related
Able to store push notification data when app is in foreground and background(when launch notification).
But not on application killed or inactive state in iOS.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
defer { completionHandler() }
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }
// perform action here
}
WillPresent is calling when application is in open state,
did receive is calling when user taps on notification.
In these scenarios able to save notification data.
How to save data When application killed and when no interaction with notification.
How to achieve this ?
I want to show custom UI for notification when App is running but.(Like in whats app). How can i do this custom view. I tried do this in userNotificationCenter but its only showing default notification.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
I want to show notification like whats app when app is runing. Do you have any idea how to do this?
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
showUIViewController()
}
func showUIViewController() {
let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "MyPage", bundle: nil)
let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewController(withIdentifier: "ContactUsDetailViewController") as! ContactUsDetailViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewControlleripad
self.window?.makeKeyAndVisible()
}
First of all, after calling showUIViewController() call the completionHandler with an empty array:
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
showUIViewController()
//1
completionHandler([])
}
1- This code will prevent the system to show the default iOS notification.
Then, Your piece of code to show custom UI for notifications like whatsapp does not make sense.
You should create a custom view and add/remove it as a subview of UIWindow instead of changing its rootViewController.
I think if you want to customize the notification when app is in foreground , I have used the third party and it's really cool and easy to implement, Check this out
https://github.com/souzainf3/RNNotificationView
I am using didReceiveRemoteNotification for detecting the app notification. But it is is getting fired automatically, when the app is at running state. I need the notification selection get detected when the app is at running state, rather than automatic notification detection through didReceiveRemoteNotification. Thanks in Advance
iOS 10+ provide the custom local notification for handling this type of issue when the app is running in the foreground.
In didFinishLaunchingWithOptions, add the delegate
UNUserNotificationCenter.current().delegate = self
then create an appDelegate extension and add this.
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert,.sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
print("tap on on forground app",userInfo)
completionHandler()
}
}
For details:
Read This Tutorial
I am trying to show the Banner notification when the app is active.
I used given method but there is no result , Banner notification are appearing only when the app is closed :
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("Push notification received: \(userInfo)")
if application.applicationState == .active {
print("active")
let localNotification = UILocalNotification()
localNotification.userInfo = userInfo
localNotification.alertAction = "Test"
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = "Notification test!!"
localNotification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(localNotification)
}
}
It prints "active" but the notification is not showing. Am i missing any step ?
Thank you.
If the application is running in the foreground, iOS won't show a notification banner/alert. You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground.
Or you can use popular Third party library : github.com/bryx-inc/BRYXBanner
Use it like below
import BRYXBanner // import in your class
// Put this code where you are getting notification
let banner = Banner(title: "title", subtitle: "subtitle", image: UIImage(named: "addContact"), backgroundColor: UIColor(red:137.0/255.0, green:172.0/255.0, blue:2.0/255.0, alpha:1.000))
banner.dismissesOnTap = true
banner.show(duration: 1.0)
But if You are using iOS 10.0+ then you can approach goal for displaying banner message while app is in foreground, use the following method.
// This method will be called when app received push notifications in foreground for iOS 10+
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
To show notification in foreground. you need to write delegate methods\
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
//Called when a notification is delivered to a foreground app.
let userInfo = notification.request.content.userInfo as? NSDictionary
print("\(userInfo)")
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// Called to let your app know which action was selected by the user for a given notification.
let userInfo = response.notification.request.content.userInfo as? NSDictionary
print("\(userInfo)")
}
Add this code. You need to parse userInfo.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
let notification = JSON(userInfo)
print(notification)
}
In iOS 10 , there is an option for presenting the notification when the app is in foreground using UNNotificationPresentationOptions,
but i couldn't find any sample on how to use this, please suggest some idea about how to implement this feature
I have implemented the foreground notification by
Adding the below code in my viewController
extension UIViewController: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler( [.alert, .badge, .sound])
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void) {
print("Do what ever you want")
}
}
In my Appdelegate on didFinishLaunchingWithOptions
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) {(accepted, error) in
if !accepted {
print("Notification access denied")
}
}
The new iOS 10 UNUserNotificationCenterDelegate now has a single set of methods for handling both remote and local notifications.
UNUserNotificationCenterDelegate protocol:
userNotificationCenter(_:didReceive:withCompletionHandler:)
Called to let your app know which action was selected by the user for a given notification.
userNotificationCenter(_:willPresent:withCompletionHandler:)
Delivers a notification to an app running in the foreground.
Two methods. And what’s better, is that now that they are moved into their own protocol, the iOS 10
UNUserNotificationCenterDelegate so this will help clean up your existing UIApplicationDelegate by being able to refactor all that old notification handling code into a shiny, new, cohesive protocol of it’s own.
Here’s an example:
extension NotificationManager: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
switch response.actionIdentifier {
// NotificationActions is a custom String enum I've defined
case NotificationActions.HighFive.rawValue:
print("High Five Delivered!")
default: break
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
// Delivers a notification to an app running in the foreground.
}
}