How to use UNNotificationPresentationOptions - ios

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.
}
}

Related

How to save push notification data into local db when application closed in iOS swift

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 ?

Disable push notification in specific view controller in foreground?

I am implementing a chat feature in an app. Right now every push I am using this to show notification while using app:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
I am wondering if it is possible to disable push notification from showing at top, while maintaining the buzzer for a specific view controller?
If yes, what should I do to create it?
Implement it like this:
UNUserNotificationCenter.current().delegate = self
...
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
if wantToShow {
completionHandler([.alert, .sound])
} else {
completionHandler([])
}
}
Then change wantToShow according to the current state.

How to show firebase notifications when application is in foreground

I am using firebase for push notification. I want to show a notification to the user when the application is in the foreground.
Notifications are working fine when the application is closed. But I want to display a stock iOS notification banner even if the application is active.
I have referred below link:
Displaying a stock iOS notification banner when your app is open and in the foreground?
I want to show notification exactly the same way as shown in above link.
I have already implemented these two methods:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
completionHandler()
}
Can someone please give me a sample of code for showing push notifications when the application is in the foreground?
You can try
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
}
For more info check here Notifications
You can call this function, for push notification:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
print("\(userInfo)")
}

Push Notifications Not Working Swift

So when my app is not currently open and it receives a push notification, the "didrecieveremotenotification" works perfectly fine when the banner appears and you press it. But when the app is open, no banner at all appears. I want the push notification to work when the app is open aswell.
I tried using UNNotificationCenter but lost push notifications in general.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted) {
UIApplication.shared.registerForRemoteNotifications()
} else{
print("Notification permissions not granted")
}
})
}
//Called when a notification is delivered to a foreground app.
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler([.sound, .alert, .badge])
}
//Called to let your app know which action was selected by the user for a given notification.
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void) {
completionHandler()
}
Update: UNUserNotificationCenter.current().requestAuthorization runs
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
when permission is granted.
however when I don't use UNNotificationCenter and use old method it doesn't fail.
Why would one method fail to register for remote notifications but the other not?
Update 2: Was working in simulator lol, that's why it was failing. However now when I run the
UNUserNotificationCenterDelegate
methods only the
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive method works and not the
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent
Update 3: I've ran out of possible things to try. What would be stopping the code from firing willPresent but not didReceive. This is brutal. Has anyone ever had this issue before?
Update 4: SOLVED. The service I'm using for the push notifications requires the user to be disconnected from the service to send the push notification. It automatically disconnects you when you're in the background, which is why that was working and it wasn't working in the foreground.
Weird way for them to configure that, I'll probably send an email.
Implement UNUserNotificationCenterDelegate delegate methods to get notification (tray at top) while app is in foreground. But it will only work with IOS 10.
In your didFinishLaunchingWithOptions method set UNUserNotificationCenterDelegate delegate like this.
UNUserNotificationCenter.current().delegate = self
Implement Delegate methods...
//Called when a notification is delivered to a foreground app.
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler([.sound, .alert, .badge])
}
//Called to let your app know which action was selected by the user for a given notification.
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void) {
completionHandler()
}

My URL isn't running after I tap on my notification action. What do I do?

In my app, I want a URL to run when my notification action is tapped on. The problem is that when I run the app it puts me into the foreground but doesn't run the URL (I added .foreground to the notification action). Here is my code:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
if response.actionIdentifier == "call" {
if let urled = URL(string: "tel://1234567891") {
UIApplication.shared.open(urled, options: [:])
}
}
}
}
Anyones help would be great:) Thanks for any answers!
For iOS 10 :
Add UserNotifications.framework to your app.
Please check that you have set delegate for push notification.
if you have already set it then try following method for iOS 10.
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
// custom code to handle push while app is in the foreground
print("\(notification.request.content.userInfo)")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("\(response.notification.request.content.userInfo)")
}
Try this:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
if response.actionIdentifier == "call" {
if let urled = URL(string: "tel://\(1234567891)") {
if UIApplication.shared.canOpenURL(urled) {
UIApplication.shared.open(urled, options: [:], completionHandler: { (completed) in
// completionHandler block
})
}
}
}
completionHandler()}
I tried the same thing and I am facing the same issue.
You can try an alternative solution if you are using Notification Content Extension.
Since we can handle the notification actions in both Extension as well as Containing App, you can try handling it in Extension using extensionContext instead of Containing App's UIApplication object.
Try this:
func didReceive(_ response: UNNotificationResponse, completionHandler completion: #escaping (UNNotificationContentExtensionResponseOption) -> Void)
{
if response.actionIdentifier == "call"
{
self.extensionContext?.open(URL(string: "tel:9555221836")!, completionHandler: { (done) in
completion(.dismiss)
})
}
//Handling other actions...
}

Resources