0

I can do it manually with the following code:

var myDate:NSDateComponents = NSDateComponents()
    myDate.year = 2015
    myDate.month = 04
    myDate.day = 20
    myDate.hour = 12
    myDate.minute = 38
    myDate.timeZone = NSTimeZone.systemTimeZone()

    var calendar:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    var date:NSDate = calendar.dateFromComponents(myDate)!

    var notification:UILocalNotification = UILocalNotification()
    notification.category = "First Category"
    notification.alertBody = "Hi, I'm a notification"
    notification.fireDate = date

    UIApplication.sharedApplication().scheduleLocalNotification(notification)

But how can I run it every hour or every day? Any idea?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Orkhan Alizade
  • 7,379
  • 14
  • 40
  • 79

5 Answers5

1

First: add an extension to the Date class:

    extension Date {
        func currentTimeMillis() -> Int64 {
            return Int64(self.timeIntervalSince1970 * 1000)
        }
    }

then call this function in the viewDidLoad():

    func run24HoursTimer() {

            let currentDate = Date()
            let waitingDateTimeInterval:Int64 = UserDefaults.standard.value(forKey: "waiting_date") as? Int64 ?? 0
            let currentDateTimeInterval = currentDate.currentTimeMillis()
            let dateDiffrence = currentDateTimeInterval - waitingDateTimeInterval
            if dateDiffrence > 24*60*60*1000 {
                // Call the function that you want to be repeated every 24 hours here:

                UserDefaults.standard.setValue(currentDateTimeInterval, forKey: "waiting_date")
                UserDefaults.standard.synchronize()
            }
    }
Shamrai Aleksander
  • 13,096
  • 3
  • 24
  • 31
0

There is a separate property on a local notification called repeatInterval. See reference

notification.repeatInterval = .Day

Also keep in mind to register in application delegate (didFinishLaunchingWithOptions method) for local notification (alert asking for permission will be presented for the first time). In Swift this will be (an example):

 if UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:"))
 {
     application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
 }

I would also recommend setting time zone for the notification, could be like this (example):

notification.timeZone = NSTimeZone.localTimeZone()

Not sure about "run function every...". This will create a notification fired with the specified repeat interval. I found this tutorial helpful.

Julian
  • 9,299
  • 5
  • 48
  • 65
0

Use This :-

1). save your daily time in user defaults 2). set notification on time for next day 3). check in app delegate if time is passed or not 4). if it is passed then set next day notification 5). if you change time update user defaults

   let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)


  let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger)


    UNUserNotificationCenter.current().add(request, withCompletionHandler: {
        (errorObject) in
        if let error = errorObject{
            print("Error \(error.localizedDescription) in notification \(indentifier)")
        }
    })
-1

You mean something like this?

let timer = NSTimer(timeInterval: 3600, target: self, selector: "test", userInfo: nil, repeats: false)

 func test() {
     // your code here will run every hour
 }

Put all that code in one class. Much more info at @selector() in Swift?

Community
  • 1
  • 1
emrys57
  • 6,679
  • 3
  • 39
  • 49
  • 4
    I don't think thats what he means at all. an NSTimer will be invalidated if the app is closed. the OP wants some process to wake the app up and execute some code sequence in a given interval – Daniel Galasko Apr 20 '15 at 12:00
-1

//Swift >=3 selector syntax

let timer = Timer.scheduledTimer(timeInterval: 3600, target: self, selector: #selector(self.test), userInfo: nil, repeats: true)

func test() {
     // your code here will run every hour
 }

Note: Time Interval is in seconds

Reference : How can I use NSTimer in Swift?

Kamal Trivedi
  • 239
  • 3
  • 10