在Swift中每天或每小时运行一个函数

时间:2015-04-20 08:56:44

标签: ios iphone swift ios8

我可以使用以下代码手动完成:

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)

但我怎样才能每小时或每天运行它?有什么想法吗?

5 个答案:

答案 0 :(得分:0)

你的意思是这样的吗?

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

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

将所有代码放在一个类中。更多信息来自@selector() in Swift?

答案 1 :(得分:0)

在名为repeatInterval的本地通知上有一个单独的属性。见reference

notification.repeatInterval = .Day

还要记住在应用程序委托(didFinishLaunchingWithOptions方法)中注册本地通知(第一次提出请求权限的警报)。在Swift中,这将是一个例子:

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

我还建议为通知设置时区,可以是这样的(示例):

notification.timeZone = NSTimeZone.localTimeZone()

不确定“每次运行功能......”。这将创建使用指定的重复间隔触发的通知。我发现这tutorial有帮助。

答案 2 :(得分:0)

使用此: -

1)。将您的每日时间保存在用户默认值中 2)。第二天按时设置通知 3)。如果时间过去,请签入app delegate 4)。如果通过则设置第二天通知 5)。如果您更改时间更新用户默认值

   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)")
        }
    })

答案 3 :(得分:0)

首先:向Date类添加一个扩展名:

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

然后在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()
            }
    }

答案 4 :(得分:-1)

// Swift> = 3选择器语法

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
 }

注意:时间间隔以秒为单位

参考:How can I use NSTimer in Swift?