I want to send a notification to a user at the first day of the month. How can I do that? It is a notification that is only local not remote.
you should have this code for notification on a specific date.
let alarmTime = Date().addingTimeInterval(60 * 60 * 24 * 7 - 300) /// you should make changes here according to your requirement.
let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: alarmTime)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Notification Demo"
content.subtitle = "Demo"
content.body = "Notification on specific date!!"
let request = UNNotificationRequest(
identifier: "identifier",
content: content,
trigger: trigger
)
first you have to register the notification swift as
func registerLocal(sender: AnyObject) {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
}
then schedule as
func scheduleLocal(sender: AnyObject) {
let notification = UILocalNotification()
notification.fireDate = // give the next first date
notification.alertBody = "this is your notification"
notification.alertAction = "be awesome!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.repeatInterval = NSCalendarUnit.NSCalendarUnitMonth
notification.userInfo = ["CustomField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Related
I'm trying to change the sash color of a local notification in my WatchKit app:
import SwiftUI
import UserNotifications
class myHostingController: WKUserNotificationHostingController<NotificationView> {
let sashColor = sashColor
}
func addNotification() {
let center = UNUserNotificationCenter.current()
let sashColor = myHostingController.sashColor
let addRequest = {
let content = UNMutableNotificationContent()
content.title = "Title content"
content.sound = UNNotificationSound.default
sashColor?.foregroundColor(.blue)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
I get the error message
Result of call to 'foregroundColor' is unused
I can't figure out how to call sashColor. Any insights would be greatly appreciated.
Customizing the sash color should be possible according to the documentation:
https://developer.apple.com/documentation/swiftui/wkusernotificationhostingcontroller/sashcolor?changes=latest_beta
https://developer.apple.com/design/human-interface-guidelines/components/system-experiences/notifications
please i have an issue about how can i trigger the local notification at specific time ? without user trigger it and need the app at specific time fired local notification
the following my code :
this is for get permission from the user
func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
}
// this i schedule local notification
func scheduleLocal() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.hour = 3
dateComponents.minute = 19
dateComponents.day = 3
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
center.removeAllPendingNotificationRequests()
}
// her i call theses methods
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerLocal()
scheduleLocal()
return true
}
and when i close my app i have no receive the notification , please help about how can i trigger the local notification at specific time
thanks
You should not call center.removeAllPendingNotificationRequests() after adding your notification, since it will cancel the previously added pending notification as well. You should rather check after calling center.addRequest(request) whether your request has actually been added or not by
center.getPendingNotificationRequests(completionHandler: { pendingRequest in
print("Pending notifications: \(pendingRequest)") //Just for debugging
})
Or you can also specify a completion handler to addRequest, which will return an error if the request hasn't been added succesfully:
center.add(request, withCompletionHandler: { error in
print(error)
})
I want to add local notification in my app. I am filling information in textfields and set date, time and reminder before particular date selected for the exam. Anyone implement such a demo then please suggest me what to do.
Answer is based on what ever i understood, Please change the time and reminder string as per your requirement.
func scheduleNotification(InputUser:String) {
let now: NSDateComponents = NSCalendar.currentCalendar().components([.Hour, .Minute], fromDate: NSDate())
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let date = cal.dateBySettingHour(now.hour, minute: now.minute + 1, second: 0, ofDate: NSDate(), options: NSCalendarOptions())
let reminder = UILocalNotification()
reminder.fireDate = date
reminder.alertBody = InputUser
reminder.alertAction = "Cool"
reminder.soundName = "sound.aif"
reminder.repeatInterval = NSCalendarUnit.Minute
UIApplication.sharedApplication().scheduleLocalNotification(reminder)
print("Firing at \(now.hour):\(now.minute+1)")
}
Set up Daily basic Local Notification 1 Day before or you can be modified it with the help of specific date in Swift 3.1
import UIKit
import UserNotifications
fileprivate struct AlarmKey{
static let startWorkIdentifier = "com.Reminder.Notification" //Add your own Identifier for Local Notification
static let startWork = "Ready for work? Toggle To \"Available\"."
}
class AlarmManager: NSObject{
static let sharedInstance = AlarmManager()
override init() {
super.init()
}
//MARK: - Clear All Previous Notifications
func clearAllNotifications(){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
}
func addReminder(with _ hour: Int, minutes: Int){
clearAllNotifications()
var dateComponent = DateComponents()
dateComponent.hour = hour // example - 7 Change you time here Progrmatically
dateComponent.minute = minutes // example - 00 Change you time here Progrmatically
if #available(iOS 10.0, *) {
dateComponent.timeZone = TimeZone.autoupdatingCurrent
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false) //Set here **Repeat** condition
let content = UNMutableNotificationContent()
content.body = AlarmKey.startWork //Message Body
content.sound = UNNotificationSound.default()
let notification = UNNotificationRequest(identifier: AlarmKey.startWorkIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(notification) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
} else {
//iOS *9.4 below if fails the Above Condition....
dateComponent.timeZone = NSTimeZone.system
let calender = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let date = calender.date(from: dateComponent)!
let localNotification = UILocalNotification()
localNotification.fireDate = date
localNotification.alertBody = AlarmKey.startWork
localNotification.repeatInterval = NSCalendar.Unit.day
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.shared.scheduleLocalNotification(localNotification)
}
}
}
//This is optional method if you want to show your Notification foreground condition
extension AlarmManager: UNUserNotificationCenterDelegate{
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void){
completionHandler([.alert,.sound])
}
}
I have created different local notifications to set for weekdays and weekends to repeat continuously
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.body = "TIME_TO_STEP_SHAPA".localized
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "\(notificationType)-\(reminderType)-\(day)", content: content, trigger: trigger)
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
print("Local notifications are not authorized by the user")
}
}
UNUserNotificationCenter.current().add(request) {(error) in
if error != nil {
print("Error: \(error?.localizedDescription)")
}
}
and cancelling particular notification verifying with notifications based on proper conditions and updating the same notification for next week.
if (type == notificationType && notificationWeekDay == currentWeekDay) {
//Cancelling local notification
app.cancelLocalNotification(notif)
let fireDate = self.getUpdatedNotification(currentDate: currentLocalDate!, fireDate: notificationFireDate!)
HikeCommonUtils.setUpLocalNotification(fireDate, type: notificationType, reminderType: reminderType)
}
and updating the next fire date using
func getUpdatedNotification(currentDate: Date, fireDate : Date) ->Date {
let calendar = Calendar.autoupdatingCurrent
let dateComponents = (calendar as NSCalendar).components(([.year, .month, .day]), from: currentDate)
let timeComponents = (calendar as NSCalendar).components(([.hour, .minute, .second]), from: fireDate)
var dateComps = DateComponents()
dateComps.day = dateComponents.day! + 7
dateComps.month = dateComponents.month
dateComps.year = dateComponents.year
dateComps.hour = timeComponents.hour
dateComps.minute = timeComponents.minute
dateComps.second = timeComponents.second
let itemDate = calendar.date(from: dateComps)
return itemDate!
}
Even after removing notification firing for the removed date because of repeat 'true'.
Is there any option for adding start date in local notifications in iOS 10?
Thanks in advance!!
Updating notification trigger details with
var triggerWeekly = calendar.dateComponents([.hour, .minute, .second], from: fireDate)
triggerWeekly.weekday = day
Instead of
let triggerWeekly = calendar.dateComponents([.weekday, .hour, .minute, .second], from: fireDate)
Worked for firedate update
You can add logic to nextTriggerDate()
func nextTriggerDate()
The next date at which the trigger conditions will be met.
Discussion
Use this property to find out when a notification associated with this trigger will next be delivered.
I have notification that works well with only one time item. I need show my notification: 10:00 PM and 10:30 PM. How i can do that? Please tell me
My code:
NotificationManager.swift:
import UIKit
import UserNotifications
class NotificationManager
{
static let shared = NotificationManager()
let center = UNUserNotificationCenter.current()
func registerNotifications()
{
center.requestAuthorization(options: [.sound,.alert], completionHandler: {( granted, error) in })
}
func addNotificationWithCalendarTrigger(hour: Int, minute: Int)
{
let content = UNMutableNotificationContent()
content.title = "Hi"
content.body = "It,s new notification!"
content.sound = UNNotificationSound.default()
var components = DateComponents()
components.hour = hour
components.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger)
center.add(request) { (error) in
//handle error
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
timeForNotifications()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func timeForNotifications()
{
NotificationManager.shared.addNotificationWithCalendarTrigger(hour: 22, minute: 00)
}
}
might be a bit late but I think this is what you're looking for. You can set the notification to show up at 10:00 with the following code:
var components = DateComponents()
components.hour = 22
components.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger)
What I always do is replace components with date, but I think your option works as well.
var date = DateComponents()
date.hour = 22
date.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
Hope this helped you out!