How to set a weekly local notification in swift - ios

I've got a problem with my code.
I want to set a local notification in xcode7, I'm developing a calendar where you can put your university's courses, the thing is that I'm getting the schedule from a json database and I want to notify 15 min before the class starts, but I do not know why my code is not working.
This is an example where I want to repeat the notification every Monday at 13:40.
Can I only set the day and the hour? or should I specify the month and the year too?
var dateComp:NSDateComponents = NSDateComponents()
dateComp.day = 01;
dateComp.hour = 13;
dateComp.minute = 40;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = calender.dateFromComponents(dateComp)!
let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)

**Weekly Local notification for swift 4
let content = UNMutableNotificationContent()
content.title = "LocalNotification"
content.subtitle = "notify"
content.body = "I am Text"
content.categoryIdentifier = "alarm"
content.badge = 1
content.sound = UNNotificationSound.default()
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3
dateComponents.hour = 13
dateComponents.minute = 10
// Create the trigger as a repeating event.
let trigger = 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.
print("************Error***************")
}
}
}

please check this function
func setLNotification(weekDay:Int , hour:Int, min:Int, second:Int, alertBody:String, type:String, isRepeate:Bool){
let calender = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let dateComp: NSDateComponents?
let components: NSDateComponents = NSDateComponents()
if weekDay > 0{
components.setValue(-50, forComponent: NSCalendarUnit.Year)
let previousDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
dateComp = calender?.components([.Year,.WeekOfMonth,.Month], fromDate: previousDate)
dateComp?.hour = hour
dateComp?.minute = min
dateComp?.second = second
dateComp?.weekday = weekDay
}else{
components.setValue(hour, forComponent: NSCalendarUnit.Hour)
components.setValue(min, forComponent: NSCalendarUnit.Minute)
components.setValue(second, forComponent: NSCalendarUnit.Second)
let notifiDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
dateComp = calender?.components([.Year,.Month,.Day,.Hour,.Minute,.Second], fromDate: notifiDate)
}
let notification = UILocalNotification()
if isRepeate == true{
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.repeatCalendar = calender
}
notification.fireDate = calender?.dateFromComponents(dateComp!)
notification.alertBody = alertBody
notification.userInfo = ["day":"\(weekDay)","type":"\(type)"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

Related

how to fire local notification on time in swift?

currently I'm working one project in swift 5. I'm trying to push local notifications on specific date & time. I have tried below code and when I set 60.0 interval then its working find but when I set specific date & time then not working.
I have searched & checked so many question but still didn't found the solution. I have checked below questions
get current date from [NSDate date] but set the time to 10:00 am
UNUserNotificationCenter Swift - Local Notification Not Firing in specific cases
let app = UIApplication.shared
let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound], categories: nil)
app.registerUserNotificationSettings(notificationSettings)
let calendar = NSCalendar.current
let date = NSDateComponents()
print("before date get ::=> \(date)")
date.hour = 16
date.minute = 52
date.month = 6
date.day = 20
date.year = 2019
date.timeZone = NSTimeZone.system
print("after custom date get ::=> \(date)")
let alarm = UILocalNotification()
alarm.fireDate = calendar.date(from: date as DateComponents)
alarm.timeZone = NSTimeZone.default
alarm.alertTitle = "Data success"
alarm.alertBody = "successfuly"
alarm.soundName = "Sound.wav"
app.scheduleLocalNotification(alarm)
app.scheduleLocalNotification(alarm)
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil)
content.sound = UNNotificationSound.default
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber;
content.categoryIdentifier = "com.elonchan.localNotification"
// Deliver the notification in 60 seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0 , repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request)
}
I expect to set specific date & time to fire local notification.
You have to use the UNCalendarNotificationTrigger not UNTimeIntervalNotificationTrigger and UILocalNotificaion is deprecated
let mutable = UNMutableNotificationContent()
mutable.body = "message"
mutable.title = "title"
var date = DateComponents()
date.hour = 16
date.minute = 52
date.month = 6
date.day = 20
date.year = 2019
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
let request = UNNotificationRequest(identifier: "key", content: mutable, trigger: trigger)
UNUserNotificationCenter.current().add(request)
This code will help you on how to send a local notification every day. You can set an hour and minute.
func setUpLocalNotification(_ hour: Int, _ minute: Int) {
print("Local Notification Setup")
let calendar = NSCalendar(identifier: .gregorian)!;
var dateFire = Date()
// if today's date is passed, use tomorrow
var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire)
if (fireComponents.hour! > hour
|| (fireComponents.hour == hour && fireComponents.minute! >= minute) ) {
dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date
fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire);
}
/// -> If you want to get tomorrow date you can use this code.
/*
dateFire = dateFire.tomorrow!
*/
// set up the time
fireComponents.hour = hour
fireComponents.minute = minute
// schedule local notification
dateFire = calendar.date(from: fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = "alert body"
localNotification.alertTitle = "alert title"
localNotification.repeatInterval = NSCalendar.Unit.day
localNotification.soundName = UILocalNotificationDefaultSoundName;
UIApplication.shared.scheduleLocalNotification(localNotification);
}
extension Date {
var tomorrow: Date? {
return Calendar.current.date(byAdding: .day, value: 1, to: self)
}
}

How to show a local agenda or local notification by hour and day

I have this array it's already populated in a table view with dynamic cells, what I want it's create a local agenda or notification or alarm or something similar to remind the user to take the medicine at the day and the hour that is displayed in the array, could you help me? please. Thanks a lot.
{“medicine”:”paracetamol”
“day”:”tuesday”
“time”:”9:00”},
{“medicine”:”aspirine”
“day”:”friday”
“time”:”16:00”},
{“medicine”:”pills”
“day”:”monday”
“time”:”22:00”}
You have to create a calendar object and set your weekday and time values in comps.weekday, comps.hour and comps.minute properties.
And for your message, set in notification content.body property.
import UserNotifications
let calendar = NSCalendar.init(calendarIdentifier: .gregorian)
calendar?.locale = NSLocale.current
let year = calendar?.component(.year, from: date)
let month = calendar?.component(.month, from: date)
let cal = Calendar.current
var comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: date)
comps.weekday = i // Monday - Friday
comps.hour = j
comps.minute = minute
comps.year = year
comps.month = month
let notificationDate = cal.date(from: comps)!
let interval = String.init(format: "%d%d%d", i,j,minute)
if #available(iOS 10.0, *) {
let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: notificationDate as Date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
repeats: true)
let content = UNMutableNotificationContent()
content.title = DataManager.sharedInstance.notificationTitle
content.body = String.init(format: "%#", DataManager.sharedInstance.notificationMessage)
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: String(interval), content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print(error)
}
}
} else {
// ios 9
// Fallback on earlier versions
let notification = UILocalNotification()
/* Time and timezone settings */
notification.fireDate = date
notification.repeatInterval = NSCalendar.Unit.weekday
notification.timeZone = NSCalendar.current.timeZone
notification.alertBody = "message"
notification.userInfo = [ "title" : String(interval)]
/* Schedule the notification */
UIApplication.shared.scheduleLocalNotification(notification)
}
UPDATED ANSWER
Convert your json to NSArray of NSDictionary objects. using NSJSonSerialisation class.
Run a for loop with the NSArray instance and access NSDictionary objects one by one.
Use NSDictionary valueForKey method. Pass the key name and get the value from dictionary.

swift how to set Notification at specific time

func setUpLocalNotification(){
let calendar = NSCalendar(identifier: .gregorian)!
var dateFire = Date()
var fireComponents = calendar.components([NSCalendar.Unit.day,NSCalendar.Unit.month,NSCalendar.Unit.year,NSCalendar.Unit.hour,NSCalendar.Unit.minute], from: dateFire)
fireComponents.year = addAlarm.year
fireComponents.month = addAlarm.month
fireComponents.day = addAlarm.day
fireComponents.hour = addAlarm.hour
fireComponents.minute = addAlarm.minute
dateFire = calendar.date(from: fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = addAlarm.msg
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = ["Uid" : addAlarm.id]
UIApplication.shared.scheduleLocalNotification(localNotification)
}
I want fire notification at date in addAlarm with msg.
I did this in main.swift and not work
What should i do to work this? add this at appdelegate?
I am beginner at swift. please help...
let localNotification = UILocalNotification()
localNotification.alertBody = "Push Message"
if #available(iOS 8.2, *) {
localNotification.alertTitle = "Title"
} else {
// Fallback on earlier versions
}
let sec = 60
localNotification.fireDate = NSDate(timeIntervalSinceNow: Double(sec))
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
Here, you can put the required time at which you want to set the local push for example : sec = 60 (60 seconds).
Thank You.
let calendar = Calendar.current
let components = DateComponents(year: 2018, month: 05, day: 06, hour: 20, minute: 22) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true

How to trigger a local notification at particular time daily in swift 3

I am new to iOS development, but have created the app and I am trying to create a daily notification for specific time like (10AM). Now notification are coming too many if i se my mobile device time to 10AM. I want to trigger a local notification only once at given specific time that is at 10 AM , and I want to repeat this daily. What is the best method to repeat the notification daily ?
Here is my code
func fire(){
let dateComp:NSDateComponents = NSDateComponents()
dateComp.hour = 10
dateComp.minute = 00
dateComp.timeZone = NSTimeZone.systemTimeZone()
let calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierIndian)!
let date:NSDate = calender.dateFromComponents(dateComp)!
let localNotificationSilent = UILocalNotification()
localNotificationSilent.fireDate = date
localNotificationSilent.repeatInterval = NSCalendarUnit.Day
localNotificationSilent.alertBody = "Started!"
localNotificationSilent.alertAction = "swipe to hear!"
localNotificationSilent.timeZone = NSCalendar.currentCalendar().timeZone
localNotificationSilent.category = "PLAY_CATEGORY"
UIApplication.sharedApplication().scheduleLocalNotification(localNotificationSilent)
}
Working in Swift 3, iOS 10:
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .sound, .badge], completionHandler: {userDidAllow, error in
//if userDidAllow : do something if you want to
})
//Set notification to trigger 11:30AM everyday
var dateComponents = DateComponents()
dateComponents.hour = 11
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
//Set your content
let content = UNMutableNotificationContent()
content.title = "Your notification title"
content.body = "Your notification body"
let request = UNNotificationRequest(
identifier: "yourIdentifier", content: content, trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
your problem is fire date which is not proper
you can create fire date like this way
let today = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.day, .month, .year], from: today)
var dateComp:DateComponents = DateComponents()
dateComp.day = components.day
dateComp.month = components.month
dateComp.year = components.year
dateComp.hour = 10
dateComp.minute = 00
let date = calendar.date(from: dateComp)
if you want to verify fire date then you can check like this way
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM yyyy hh:mm:ss"
let fireDate = dateFormatter.string(from: date!)
print("fireDate: \(fireDate)")
Now it's time to set fire date to local notification
localNotificationSilent.fireDate = date
// no need to set time zone Remove bellow line
localNotificationSilent.timeZone = NSCalendar.currentCalendar().timeZone
Notification code
let localNotificationSilent = UILocalNotification()
localNotificationSilent.fireDate = date
localNotificationSilent.repeatInterval = .day
localNotificationSilent.alertBody = "Started!"
localNotificationSilent.alertAction = "swipe to hear!"
localNotificationSilent.category = "PLAY_CATEGORY"
UIApplication.shared.scheduleLocalNotification(localNotificationSilent)
I hope it will help you.

Scheduling weekly repeatable local notification with fire date from date picker in Swift 3

So I'm currently building a schedule app and I'm trying to create a local notification to fire on specific time on specific day of the week, every week. So the first thing I do is get the date value of the start time of the event, then I subtract 5 minutes from the start time value and then schedule the notification. Previously it was very easy just had to type:
notification.repeatInterval = CalendarUnit.WeekOfYear but now the command is deprecated in Swift 3 and yeah, so the only way I found is:
let someMinutesEarlier = Calendar.current.date(byAdding: .minute, value: -5, to: startTimePicker.date)
let contentOfNotification = UNMutableNotificationContent()
let interval = someMinutesEarlier?.timeIntervalSinceNow
contentOfNotification.title = "Event starting"
contentOfNotification.body = "Some notes"
contentOfNotification.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval!, repeats: true)
let request = UNNotificationRequest.init(identifier: notificationIdentifier, content: contentOfNotification, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
print(error as Any)
}
but this only schedules the notification only once (no matter that the repeat boolean is set to true), because of the year in the someMinutesEarlier...or it's may be something else? Any idea?
As McNight mentionned, you can use UNCalendarNotificationTrigger like so:
let interval = 60 * 60 * 24 * 7 - 300 // One week minus 5 minutes.
let alarmTime = Calendar.current.date(byAdding: .second, value: interval, to: Date())!
let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: alarmTime)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
(I haven't tested this code, but this should get you on the right path).
More information here.
Edit: Fixed time interval calculation suggested by SwiftyCruz.
Edit 2: Updated to use a Calendar to perform the time shift as suggested by RickiG.
// Swift2.3
func setLNotification(weekDay:Int , hour:Int, min:Int, second:Int, alertBody:String, type:String, isRepeate:Bool){
let calender = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let dateComp: NSDateComponents?
dateComp = calender?.components([.Year,.WeekOfMonth,.Month], fromDate: NSDate())
dateComp?.hour = hour
dateComp?.minute = min
dateComp?.second = 00
dateComp?.weekday = weekDay
dateComp!.timeZone = NSTimeZone.localTimeZone()
print(calender?.dateFromComponents(dateComp!))
let SetCustomDate = calender?.dateFromComponents(dateComp!)
print(SetCustomDate)
let notification = UILocalNotification()
if isRepeate == true{
switch type {
case "Weekly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*7)
notification.repeatInterval = NSCalendarUnit.Weekday
case "2 Weekly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*14)
notification.repeatInterval = NSCalendarUnit.Day
case "Monthly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*28)
notification.repeatInterval = NSCalendarUnit.Day
default:
break;
}
notification.soundName = UILocalNotificationDefaultSoundName
notification.repeatCalendar = calender
}
notification.alertTitle = "STATS"
notification.alertBody = "Please update your Stats detail"
notification.userInfo = ["uid":"reminder"]
print(notification)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

Resources