I have created an iOS app that sends a local notification daily at 11:00 AM.
I have followed this!
and my code is...
func setNotification(){
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var dateFire=NSDate()
var fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())
if (fireComponents.hour >= 11) {
dateFire=dateFire.dateByAddingTimeInterval(86400) // Use tomorrow's date
fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())
}
fireComponents.hour = 11
fireComponents.minute = 00
dateFire = calendar.dateFromComponents(fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertTitle = "Title"
localNotification.alertBody = "Body"
localNotification.repeatInterval = NSCalendarUnit.Day
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
Now the app works good and notifications are sent at 11:00 AM daily but the problem is they are incrementing by one daily :(
Yesterday I had received 6 notifications and today I received 7 at 11:00am
Please help me to get out of this issue.
Thanks!
I tried this and its working. You are checking if condition and overwriting firecomponents so it is of no use.
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var dateFire=NSDate()
let fireComponents = calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())
fireComponents.hour = 7
fireComponents.minute = 41
fireComponents.second = 00
dateFire = calendar.dateFromComponents(fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = "Body"
localNotification.repeatInterval = NSCalendarUnit.Minute
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
For further details https://wordpress.com/post/iosmygirlfriend.wordpress.com/48
Related
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
I am getting year,month and day from a given date in this way.
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day. How can I solve this?
let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
I'm getting perfect system/local time.
You code is working,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result: day = Optional(20) hour = Optional(16) minute = Optional(35)
Get Local Date and Time
Swift 5:
let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()
As per the documentation:
If you want “date information in a given time zone” in order to
display it, you should use DateFormatter to format the date.
eg:
// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today)) // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today)) // prints "06\n"
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.
I am trying to schedule a local notification so it will occur at 9:00pm and repeat once a week. I have the following code and I keep receiving a error that says "Cannot assign value of type NSDateComponents to .fireDate. I understand .fireDate will only accept NSDate types but. I can not figure out a way to set the hour variable and minute variable for a NSDate type because I don't think it is possible to do this.
func Notification(){
let dateComponents = NSDateComponents()
dateComponents.day = 4
dateComponents.month = 7
dateComponents.year = 2016
dateComponents.hour = 21
dateComponents.minute = 00
let Notification = UILocalNotification()
Notification.alertAction = "Go Back To App"
Notification.alertBody = "Did you complete your HH and QC?"
Notification.repeatInterval = NSCalendarUnit.WeekOfYear
Notification.timeZone = NSTimeZone.defaultTimeZone()
Notification.fireDate = dateComponents
UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}
Here is how you do it.
Fully Tested on Swift 2.0
//Note I have taken date time from date picker
func scheduleLocalNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = fixNotificationDate(datePicker.date)
localNotification.alertBody = "Hey, you must go shopping, remember?"
localNotification.alertAction = "View List" // Change depending on your action
localNotification.category = "reminderCategory"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//This function will help you in generating fire date.
func fixNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponets.second = 0
let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)
return fixedDate
}
Don't forget to request permission for push notification.
Link to my project i worked on
https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms
You should get date from date components like this:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let date = calendar.dateFromComponents(dateComponents)!
Notification.fireDate = date
I have a daily notification that reminds the user to use the app. I would like the text to not be static though. I have say, 5 different strings, and I would like the string to be chosen randomly if possible.
My current code, that uses the same text everyday:
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let newDate: NSDate = cal.dateBySettingHour(22, minute: 00, second: 0, ofDate: date, options: NSCalendarOptions())!
var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "MyApp"
localNotification.alertBody = "Call to action text"
localNotification.fireDate = newDate
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
You could use a switch statement based on the day of the week. Here's an excellent NSHipster tutorial on NSDate components. Here's some sample code re: how to pull a day of the week out of an NSDate:
func getDayOfWeek(today:String)->Int {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.dateFromString(today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.CalendarUnitWeekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
}
let weekday = getDayOfWeek("2014-08-27")
println(weekday) // 4 = Wednesday
Here's Apple's documentation for switch statements.
Basically, you'll want to create a method that takes an NSDate as an input and spits out a day of the week. Once you've got the day of the week, you you can create your custom message in the switch statement.