how to run a function at certain time using swift

时间:2016-08-31 17:48:50

标签: ios swift uilocalnotification recurrence

In my app, i have implemented functionality to check app version using bundleVersion String. Now, i want to run this function everyday at 8:00 a.m. This is kiosk based app which does not go into background. So, app would be active all the time.

I am using UILocalnotification to schedule a notification for that time. Now, my app has other UILocalnotification as well. I am not sure how can i identify notifications in app delegate didReceiveLocalNotification() method.

My method to schedule notification is below

func scheduleNotification() {

    //UIApplication.sharedApplication().cancelAllLocalNotifications()
    let notif = UILocalNotification()


    let calendar = NSCalendar.currentCalendar()
    let date = NSDate()

    var calendarComponents = NSDateComponents()

    calendarComponents = calendar.components([.Day,.Month,.Year], fromDate: date)

    let day = calendarComponents.day
    let month = calendarComponents.month
    let year = calendarComponents.year

    calendarComponents.day = day
    calendarComponents.month = month
    calendarComponents.year = year

    calendarComponents.hour = 8
    calendarComponents.second = 0
    calendarComponents.minute = 0
    calendar.timeZone = NSTimeZone.systemTimeZone()
    let dateToFire = calendar.dateFromComponents(calendarComponents)


    notif.fireDate = dateToFire
    notif.timeZone = NSTimeZone.systemTimeZone()
    notif.repeatInterval = NSCalendarUnit.NSWeekdayCalendarUnit


    UIApplication.sharedApplication().scheduleLocalNotification(notif)

}

Any idea would be appreciated.

1 个答案:

答案 0 :(得分:0)

Following method could help you to execute any task at regular interval , i used this method to call webservice at regular interval to provide searching functionality :

let debounceTimer : NSTimer?
func test() {

        if let timer = debounceTimer {

            timer.invalidate()

        }

        debounceTimer = NSTimer(timeInterval: 0.3, target: self, selector: Selector("putmethodnamewhichneedstocall"), userInfo: nil, repeats: false)

        NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode")

    }

For specific time daily Refer to this SO link :Repeating local notification daily at a set time with swift

Hope it helps.