I have an set of Local Notifications that I have scheduled to be sent out by setting a fire date on each one from iterating through an array. The problem is for some reason the first notification is not being sent, all the others are set and sent fine. This is the code:
var notifi = 0
var firstDate = NSDate()
let dateArrays = Array(1...3)
for _ in dateArrays{
if notifi < 64 {
firstDate = firstDate.dateByAddingTimeInterval(10)
notification.category = "FIRST_CATEGORY"
notification.alertBody = "It's time to look away now!"
notification.fireDate = firstDate
UIApplication.sharedApplication().scheduleLocalNotification(notification)
notifi = notifi + 1
}else {
print("local notifications limit has been reached")
}
}
Related
enter image description here
I want to send local notifications between 10A.M to 10P.M repeating every 2hours(user input) for the user selected days.
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponents.minute = 00
let userCalendar = Calendar.current
var dateStart = userCalendar.date(from: dateComponents)
var dateComponent = DateComponents()
dateComponent.hour = 22
dateComponent.minute = 00
var dateEnd = userCalendar.date(from: dateComponent)
while dateStart < dateEnd {
//Add repeating hours start time
UserDefaults.standard.set(self.txtField.text, forKey: "hoursSendary")
let Nohours = UserDefaults.standard.integer(forKey: "hoursSendary")
dateStart = dateStart?.addingTimeInterval(TimeInterval(Nohours * 60 * 60))
//Schedule notification With body and title.
scheduleNotification(body: "Free your eyes", titles: "Screen Alarm",day: 1)
}
func scheduleNotification( body: String, titles:String,day:Int) {
UserDefaults.standard.set(self.txtField.text, forKey: "hoursSendary")
let Nohours = UserDefaults.standard.integer(forKey: "hoursSendary")
let date = Date(timeIntervalSinceNow:TimeInterval(Nohours * 60 * 60) )
var components = DateComponents()
components.weekday = day// sunday = 1 ... saturday = 7
components.weekdayOrdinal = 10
components.timeZone = .current
components.hour = Nohours
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default
content.categoryIdentifier = "ScreenAlarm"
let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
How can I pass the user selcted days, I have a collection view with days and I'm doing this stuff inside the didselect method.
I have this function that calculate the amount of time from the current minute of the phone. I am trying to have a timer go off after this specific amount of time. The way this function is called is through a switch that the user flips in the app and the time should reset it self. Well Im having trouble with my NSDate object getting old values when the switch was flipped before. Is there a way to reset the NSDate object to zero?
Here is my code for the calculating the current time of the phone.
func GetInitialTime(){
finalTime = 0
firstTimeCounter = 0
timeInSeconds = 0
let calendar = NSCalendar.current
var minutes = calendar.component(.minute, from: date)
var timeDifference = Int()
if(minutes == 00 || minutes == 30) {
print("The minute hand is at zero or thirty.")
}
else {
print("The minute hand is NOT ar zero or thirty")
print("The minute hand ia at:")
if minutes < 30 {
while (!(minutes == 30)) {
minutes += 1
timeDifference += 1
}
print("Therefore we make the minute hand at zero or thiry: ", minutes)
print("The time difference we add to the minute is: ", timeDifference)
}
else {
var i = minutes
while i < 60 {
i += 1
minutes += 1
timeDifference += 1
}
print("Therefore we make the minute hand at zero or thirty: ", minutes)
print("The Time difference we add to the minute is: ", timeDifference)
}
}
finalTime = Double(timeDifference * 60)
print("The time difference in seconds is:", finalTime)
}
And I declare the Date() object here
let center = UNUserNotificationCenter.current()
let button = UIButton(type: UIButtonType.custom)
let date = Date()
var timeInSeconds = Int()
var finalTime = Double()
var halfHour = Double(1800)
var firstTimeCounter = Int()
var firstTimer = Timer()
var repeatingTimer = Timer()
var backgroundTask = BackgroundTask()
let dispatchGroup = DispatchGroup()
var urlWeb = "http://morrowrenewablesflowdata.com/iOSConnections/Notifications.php"
var downtimes = [String]()
var flows = [String]()
Your code is using an instance variable date that is a let constant. You don't show the context in which it's set, but I'm assuming it's an instance variable of your class. The fact that it's a let constant means it will never change in the scope in which it's declared. That's almost certainly your problem.
My question is the same question that I linked below but I want to do that in swift 2, not in objective-c
Fire a notification at a specific day and time every week
The problem is that the date that I'm using is by default 1st January, because I haven't specified the month, the day of the month and the year, But if I specified them it would be useless because my app wouldn't work next year, or next month
Is very simple what I want.. Set a notification weekly on Sunday (For example)
but is not practical to specify the year or the month, because it should work any Sunday or any Saturday
please help me :( I've already tried a lot
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 2
components.minute = 54
components.weekday = 6
var newDate = calendar.dateFromComponents(components)
let notification = UILocalNotification()
notification.fireDate = newDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)
UPDATE:
I know it will only work on Mondays but I can fix later.
The problem here is that I set the hour and minute in 0 and then it returns the current time and I do not know how to set up the hour that I want.
var pickerDate = NSDate()
print(pickerDate)
var dateComponents: NSDateComponents? = nil
var calendar = NSCalendar.currentCalendar()
dateComponents = calendar.components(NSCalendarUnit.NSWeekdayCalendarUnit, fromDate: pickerDate)
var firstMondayOrdinal = 9 - dateComponents!.weekday
dateComponents = NSDateComponents()
dateComponents!.day = firstMondayOrdinal
dateComponents?.hour = 0
dateComponents?.minute = 0
var firstMondayDate = calendar.dateByAddingComponents(dateComponents!, toDate: pickerDate, options: NSCalendarOptions(rawValue: 0))
dateComponents = NSDateComponents()
dateComponents?.weekdayOrdinal = 1
let notification = UILocalNotification()
notification.fireDate = firstMondayDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Get the next Sunday or Monday date (SO answer), use calendar method dateBySettingHour to set the desired time to that date and use it as the firedate using the weekofyear repeat interval.
I'm trying to trigger notification on specific saved time in database and on specific day which is Friday as shown below, but every time I try to save new reminder it tells me unexpectedly found nil while unwrapping an Optional value and I'm sure it contains data and it's not nil even though I tried to handle nil, still the app crash, however when I try to fire notification without combining dates like this localNotification.fireDate = reminders.time! the app is not crashed and it works just fine.
I guess the problem in combineDate function, how I can solve this problem?
func combineDate(time: NSDate?) -> NSDate{
let gregorianCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let time: NSDateComponents = gregorianCalendar.components([.Hour, .Minute, .Second], fromDate: time!)
time.timeZone = NSTimeZone.systemTimeZone()
let timeCombiner: NSDateComponents = NSDateComponents()
timeCombiner.timeZone = NSTimeZone.systemTimeZone()
timeCombiner.hour = time.hour
timeCombiner.minute = time.minute
timeCombiner.second = 00
timeCombiner.weekday = 6
let combinedDate: NSDate = gregorianCalendar.dateFromComponents(components3)!
return combinedDate
}
func createLocalNotification(){
let localNotification = UILocalNotification()
localNotification.timeZone = NSTimeZone.systemTimeZone()
localNotification.fireDate = combineDate(reminders.time!)
localNotification.alertBody = reminders.name!
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
still the reason of causing all this mass unknown however I solved it by checking if reminder managed object is not equal to nil then try to fire notification
func createLocalNotification(){
let localNotification = UILocalNotification()
localNotification.timeZone = NSTimeZone.systemTimeZone()
if reminder != nil{
localNotification.fireDate = combineDate(reminders.time!)
}
localNotification.alertBody = reminders.name!
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
How can I make a user choose a time by using a date picker and then send the user a local notification?
here is a simple code to schedule a local notification in swift:
let calendar: NSCalendar = NSCalendar.currentCalendar()
let fireDateOfNotification: NSDate = //The date which was picked from the picker
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.localTimeZone()
notification.alertBody = "ALERT STRING"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = fireDateOfNotification
notification.userInfo = ["UUID": "NotificationID"] //id for the local notification in case you want to cancel it
UIApplication.sharedApplication().scheduleLocalNotification(notification)
and if you want to cancel a local notification you should use the following function:
func cancelLocalNotificationsWithUUID(uuid: Int) {
for item in UIApplication.sharedApplication().scheduledLocalNotifications {
let notification = item as! UILocalNotification
if let notificationUUID = notification.userInfo?["UUID"] as? Int {
if notificationUUID == uuid {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
}
}
}
I hope this helps.