Apple has approve my request for an entitlement to use critical alerts. I attached my entitlement to my bundle identifier and created a provisioning profile and manually signed my app according to Apple's instructions: https://help.apple.com/developer-account/#/dev38c81d4cd
I also added a properties.entitlements file with the correctly modified bundle identifier and boolean "YES". My "Build Settings" does not have a "Code Signing Entitlements" within "Signing".
When I run the code below, I get the prompt to accept alerts, but then no critical alert. Any suggestions? Thanks!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var authOptions: UNAuthorizationOptions?
if #available(iOS 12.0, *) {
authOptions = [.alert, .badge, .sound, .criticalAlert]
} else {
authOptions = [.alert, .badge, .sound]
}
UNUserNotificationCenter.current().requestAuthorization(options:
authOptions!) { (granted, error) in
if !granted {
print("The application requires Notifications permission to display push notifications. Please enable it in settings.")
} else {
let userNotificationCenter = UNUserNotificationCenter.current()
var contentTitle:String?
var contentMessage:String?
var contentSound:UNNotificationSound?
contentTitle = "Message:"
contentMessage = "Critical Alert!"
contentSound = .defaultCritical
let content = UNMutableNotificationContent()
content.title = contentTitle!
content.subtitle = contentMessage!
content.sound = contentSound
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
userNotificationCenter.add(request)
}
}
}
}
Related
I am trying to add badge and sound to local notification in my app but I get none.
I see the notification when it supposed to appear but without any sound or badge...
Can anyone please tell me what I am doing wrong?
func requestUserPermissionForNotifications(){
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
if (error != nil) {
print("Error authorzing notifications")
} else {
if (didAllow) {
self.setDailyNotifications()
print("User allowed to Push notifications")
} else {
print("User did not allow to Push notifications")
}
}
})
}
func setDailyNotifications() {
var sunday = DateComponents()
sunday.hour = 11
sunday.minute = 00
sunday.weekday = 1
timeNotification(id: "Sunday", notificationTitle: "Daily reward is waiting", notificationText: "Log in and get your daily reward", timeOfNotification: sunday)
}
func timeNotification(id: String, notificationTitle: String, notificationText: String, timeOfNotification: DateComponents) {
let trigger = UNCalendarNotificationTrigger(dateMatching: timeOfNotification, repeats: true)
let content = UNMutableNotificationContent()
content.title = notificationTitle
content.body = notificationText
content.sound = UNNotificationSound.default()
content.badge = 1
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if (error != nil) {
print("Error adding notification \(id) --- \(String(describing: error))")
}
}
}
The issue was that I called my setDailyNotifications() function from the requestAuthorization() method. All I did was to call setDailyNotifications() from viewDidLoad if the user approved push notifications.
I am trying to learn how to use local notifications and currently I am just trying to let a notification pop up when a certain time has passed (for the sake of learning just 5 seconds).
I register the notification in this function, which is used at the end of an onBoarding screen:
func registerNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Granted.")
} else {
print("Not granted.")
}
}
}
Now to test the notification I just add the function set() to a button:
set() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Test Notification"
content.body = "It works!"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
But when the button is pressed and 5 seconds passed, no notification is shown, but also no error in Xcode, so I suppose this should all work?
What am I missing here? As far as I understand from various sources on the net this is the easiest way to display a local notification?
So to register a UserNotification and call the function at an appropriate
place:
func registerNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Granted.")
} else {
print("Not granted.")
}
}
}
This functions sets a notification with a time interval of 5 seconds. When the app is closed the notification will be displayed:
set() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Test Notification"
content.body = "It works!"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
I have a Firebase listener that launches a notification when it fires like so:
chat.ref.child("lastMessage").observe(.value, with: { snapshot in
let lastMessage = snapshot.value as! String
chat.lastMessage = lastMessage
self.tableView.reloadData()
chat.lastMessageText = "New Message!"
let content = UNMutableNotificationContent()
content.title = "You have a new Message!"
content.subtitle = chat.title
content.body = chat.lastMessage
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger (timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Also have:
override func viewDidLoad() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })
}
The problem I am having is, although the HomeScreen notifications are working in the simulator, they are not showing on the device. All permissions are granted on the device. Reading some questions here I found some answers that suggested I add the following in the app delegate:
application.beginBackgroundTask(withName: "showNotification", expirationHandler: nil)
but this actually disabled notifications on the simulator too. The notifications did work on the device before but stopped very suddenly. Any thoughts?
We are using the UNUserNotification framework provided by WatchOS 3.0 to create local notification to notify user at a predefined moment. However, the notification is not shown when the watch is not being worn on the wrist. It does work well when someone is wearing it.
We cannot find this description on any documentation. Is that normal? If yes, how to help the user to avoiding missing some notifs ?
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Enable or disable features based on authorization.
if granted {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()
content.userInfo = userInfo
let trigger = UNTimeIntervalNotificationTrigger.init(
timeInterval: interval,
repeats: false)
let identifier = stringWithUUID()
let request = UNNotificationRequest.init(
identifier: identifier,
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
completion?(true, nil)
}
else {
completion?(false, error)
}
}
This is normal, Apple Watch automatically locks when you take it off your wrist and notifications go to your iPhone instead.
I'm struggling to get push notifications to work with Swift with iOS 10. Registering seems to be going through successfully, but creating a notificaiton does nothing on the device and returns a nil error. Any ideas what I'm missing?
import Foundation
import UIKit
import UserNotifications
class SPKPushNotifications
{
class func register(application:UIApplication){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
application.registerForRemoteNotifications()
}
} else {
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
}
}
class func unregister(application:UIApplication){
application.unregisterForRemoteNotifications()
}
class func create(title:String, body:String, delay:Double, repeats:Bool){
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default() //idk if we're gonna want something else
content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats)
let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger)
let center = UNUserNotificationCenter.current()
center.add(request){ (error) in
print(error)
}
} else {
// Fallback on earlier versions
}
}
class func delete(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications()
} else {
// Fallback on earlier versions
}
}
}
You won't see the notification if the application is in the foreground. Try adding the request to the notification center when the application is in the background.
You can do (for this test only) that by adding a few second sleep and moving your application to the background. Or scheduling the notification to a later time when the application is not running in the foreground.