I have problems setting a notification of type UNCalendarNotificationTrigger that is determined by DateComponents
//set content
let content = UNMutableNotificationContent()
content.title = "My Notification Management Demo"
content.subtitle = "Timed Notification"
content.body = "Notification"
content.body = "Notification pressed \(pressed) times"
content.categoryIdentifier = "message"
//set trigger possible problem
let formatted = DateFormatter()
formatted.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
formatted.date(from: "2018-01-19T02:29:50+0000")
var dateInfo = DateComponents()
dateInfo.calendar = formatted.calendar
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateInfo,
repeats: false
)
//Create the request
let request = UNNotificationRequest(
identifier: "my.notification",
content: content,
trigger: trigger
)
//Schedule the request
UNUserNotificationCenter.current().add(request) { (error : Error?) in
print("all ok")
}
And when I make a request to get the pending notifications, the array is wide.
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: {requests -> () in
print("\(requests.count) requests -------")
for request in requests{
print(request.identifier)
}
})
Related
I'm trying to trigger local notifications for every 1 minute even in terminated state and background state. But, my app should not trigger notification when time is after 06:00PM. Below is my code.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,repeats: true)
//UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}
To handle local notification, try this:
public func addLocalNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize
let center = UNUserNotificationCenter.current()
// Set its content
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
// whenever you want to notify user select time
var dateComp = DateComponents()
dateComp.calendar = Calendar.current
dateComp.hour = hour
dateComp.minute = minute
// repeat and date
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
// Initializing the Notification Request object
let req = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Add the notification to the center
center.add(req) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}
hello i want to send notification like daily reminder even the app terminated not working in background how i can do it and this my code
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.body = " "
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}
Trigger local Notification at date and time.
func scheduleNotification(at date: Date, message:String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = message
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}
I am working on a medicine reminder app. The user will input two dates and I need to schedule local notifications between those two dates. I can't find how to specify the starting and the ending date in the UNNotificationRequest.
I have tried this:
static func setAlarmWithDate (hour:Int, minutes:Int , day:Int, medicineName:String, medicineId:String) {
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "MY_MEDICINE".localizedString(), arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "This is a notification for your medicine \(medicineName)",
arguments: nil)
content.sound = UNNotificationSound.default()
var userInfo = [String:String]()
let medicine = medicineId
userInfo["medicine"] = medicine
content.userInfo = userInfo
var dateInfo = DateComponents()
dateInfo.hour = hour
dateInfo.minute = minutes
dateInfo.weekday = day
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let identifier = medicineId
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
I am new to Swift and I am really stuck.
I've set the user notification. They got deliver well but the badge on the app icon is always one.
Here's my code:
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound];
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
// ask for permission
}
}
When the use click the button i schedule the notif:
#IBAction func saveBtnPressed(sender: UIButton) {
scheduleNotif()
}
Here's the scheduleNotif function
func scheduleNotif() {
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.medium
dateformatter.timeStyle = DateFormatter.Style.short
let dateFromString = dateformatter.date(from: selectDateTextField.text!)
let fireDateOfNotification: Date = dateFromString!
//Notif are enabled
let content = UNMutableNotificationContent()
content.title = notifTitleTextField.text!
content.body = notifNoteTextView.text
content.sound = UNNotificationSound.default()
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
var trigger: UNCalendarNotificationTrigger
var triggerDate = DateComponents()
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let titleNospace = notifTitleTextField.text?.replacingOccurrences(of: " ", with: "")
var identifier = titleNospace
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: { (error) in
if let error = error {
print(error.localizedDescription)
}
})
}
Any idea why the badge will always display one and never increment as the notifications are delivered?
Thank you
I think you need to increment applicationIconBadgeNumber. So replace
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
By:
UIApplication.shared.applicationIconBadgeNumber += 1
content.badge = UIApplication.shared.applicationIconBadgeNumber as NSNumber
I'm using the WatchOS 3 beta and trying to initiate a local notification on the watch. The interface is just one button which calls the "buttonPushed" method in the code below. The app runs fine but I never get a notification. The app structure is the default from Xcode 8 for a WatchKit app.
This code is in the InterfaceController.swift file of the WatchKit extension
Am I missing something totally obvious?
#IBAction func buttonPushed() {
sendMyNotification()
}
func sendMyNotification(){
if #available(watchOSApplicationExtension 3.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "REMINDER_CATEGORY"
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
center.add(request ,withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
}
According to this. You should specify a unique and new identifier for request each time.
Mine:
let id = String(Date().timeIntervalSinceReferenceDate)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
Swift 4 simple code
let content = UNMutableNotificationContent()
content.title = "How many days are there in one year"
content.subtitle = "Do you know?"
content.body = "Do you really know?"
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
Local Notification watchOS swift 4.0
var content = UNMutableNotificationContent()
content.title = "ALERT !"
content.body = msg
content.sound = UNNotificationSound.default() as? UNNotificationSound
// Time
var trigger: UNTimeIntervalNotificationTrigger?
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
// Actions
var snoozeAction = UNNotificationAction(identifier: "Track", title: "Track", options: .foreground)
var category = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction], intentIdentifiers: [] as? [String] ?? [String](), options: .customDismissAction)
var categories = Set<AnyHashable>([category])
center.setNotificationCategories(categories as? Set<UNNotificationCategory> ?? Set<UNNotificationCategory>())
content.categoryIdentifier = "UYLReminderCategory"
var identifier: String = stringUUID()
var request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: {(_ error: Error?) -> Void in
if error != nil {
print("Something went wrong: \(error)")
}
})
Unique request identifier methods
func stringUUID() -> String {
let uuid = UUID()
let str: String = uuid.uuidString
return str
}
Objective C
// Objective-C
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = #"ALERT !";
content.body = msg;
content.sound = [UNNotificationSound defaultSound];
// Time
UNTimeIntervalNotificationTrigger *trigger;
trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1
repeats:NO];
// Actions
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"Track"
title:#"Track" options:UNNotificationActionOptionForeground];
// Objective-C
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:#"UYLReminderCategory"
actions:#[snoozeAction] intentIdentifiers:#[]
options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:category];
// Objective-C
[center setNotificationCategories:categories];
// Objective-C
content.categoryIdentifier = #"UYLReminderCategory";
NSString *identifier = [self stringUUID];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
}];
Unique request identifier methods
-(NSString *)stringUUID {
NSUUID *uuid = [NSUUID UUID];
NSString *str = [uuid UUIDString];
return str;
}