iOS - How can I schedule something once a day?

独自空忆成欢 提交于 2019-12-04 19:26:37

Yes, to use NSTimer, the app has to be running either in foreground or background. But Apple is quite particular only allowing certain types of apps to continue to run in the background (in an effort to make sure we don't have apps randomly running on their own prerogative and killing our batteries in the process and/or affecting our performance while using the device).

  1. When you say "notification", do you really mean notifying the user of something?

    In that case, the alternative here is to create a UILocalNotification, which is a user notification (assuming they've granted your app permission to perform notifications), which is presented even when your app is not running.

    For example, to register for local notifications:

    let application = UIApplication.sharedApplication()
    let notificationTypes: UIUserNotificationType = .Badge | .Sound | .Alert
    let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
    

    And then to schedule the repeating notification:

    let notification = UILocalNotification()
    notification.fireDate = ...
    notification.alertTitle = ...
    notification.alertBody = ...
    notification.repeatInterval = .CalendarUnitDay
    application.scheduleLocalNotification(notification)
    

    For more information, see the Local and Remote Notification Programming Guide.

  2. Or do you mean initiating some process, such as fetching data from a remote server.

    If you want the app to fetch data even if your app isn't running, you can use background fetch. See Fetching Small Amounts of Content Opportunistically in the App Programming Guide for iOS.

    Note, with background fetch, you don't specify when data is to be retrieved, but rather the system will check for data at a time of its own choosing. It reportedly factors in considerations ranging from how often the user uses the app, how often requests to see if there is data result in there actually being new data to retrieve, etc. You have no direct control over the timing of these background fetches.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!