How to Run a Task in Swift on a Particular Date-Time in Background Either Application Is on or Off

How to Run a Task in swift on a particular date-time in background either application is on or off

Waking up an app through a local notification is not possible, this is available only for remote notifications. According to the Notification Programming Guide:

When a remote notification arrives, the system handles user
interactions normally when the app is in the background. It also
delivers the notification payload to the
application:didReceiveRemoteNotification:fetchCompletionHandler:
method of the app delegate in iOS and tvOS

But there is still a catch; even then it is not guaranteed that the app will be launched since, according to didReceiveRemoteNotification:fetchCompletionHandler: documentation:

However, the system does not automatically launch your app if the user
has force-quit it
. In that situation, the user must relaunch your app
or restart the device before the system attempts to launch your app
automatically again.

I don't think there is a guaranteed way to schedule a block for execution in some later moment, independently from the state of the app at that time. Depending on your specific requirements and frequency, you could perhaps register for the fetch background mode and implement application:performFetchWithCompletionHandler: to opportunistically fetch and validate server data. Last note: make sure that you are a responsible background app (from my experience Apple takes this requirement seriously)

Perform Function on Specific Date

Based off of Get current date in Swift 3?

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year = components.year
let month = components.month
let day = components.day

if(month == 6 && day == 5 && year == 2017) { //June 5 2017
//Code
}else{
//Code
}

Make sure to use lets for performance since you don't need to change those variables.

Run a task at fixed time everyday

There is no way to achieve your goals without using push notifications. Timer's are using run loops and hence aren't working in the background. There's no background mode for making API calls at regular intervals either.

The only option is to send out push notifications from your server at the specified times every day and in response to receiving the push notification in your app, make the API call. Of course you'll need internet connection for push notifications to work, but since you want to make API calls, this won't make a difference as you'd need internet connection for the API calls to succeed anyways.

Perform background tasks when app is terminated

You have two options

  1. Background App Refresh
  2. Silent push notifications

Easiest one is Background App Refresh. Because later one needs a server to send the notification. You can check following API for the usage. Basically you set Background Fetch capability on Capabilities/Background Modes of your app. Then from time to time, iOS will wake up your app and call application(_:performFetchWithCompletionHandler:) delegate. You will have around 30-45 seconds to call your function and call completion handler. If you don't finish it on time, iOS will kill your app. If you don't obey the rules, iOS will give you less chances to wake up. For more detailed usage of Background Modes, you may check following tutorial

iOS Run Code Once a Day

Here's the situation regarding background execution and notifications and timers etc. in relation to an app scheduling some activity to happen periodically.

  1. An app cannot execute in the background unless:

    1. It requests extra time from the OS to do so. This is done using beginBackgroundTaskWithExpirationHandler. It is not specified (intentionally) by Apple how long this extra time is, however in practice it is around 10 minutes.

    2. An app has a background mode, the modes are: voip, audio, location, newstand. Even if it has one of these types an app cannot execute without some restrictions. The rest of this discussion assumes the app does not have a background mode.

  2. When an app is suspended it cannot do ANYTHING to rouse itself directly. It cannot previously have scheduled an NSTimer, it cannot make use of something like performSelector:afterDelay. etc.

    The ONLY way the app can become active again is if the USER does something to make it active. The user can do this from via of the following:

    1. Launch the app directly from its icon

    2. Launch the app in response to a local notification that was previously scheduled by the app while it was active.

    3. Launch the app in response to a remote notification sent by a server.

    4. A few others: such as URL launching if the app is registered to deal with launching via a url; or if its registered to be capable of dealing with a certain type of content.

If an app is in the foreground when a local/remote notification fires then the app receives it directly.

If the app is not currently in the foreground when a local/remote notification fires then the app DOES NOT receive it. There is no code that is executed when the notification fires!

Only IF the user selects the notification will the app become active and it can execute.

Note that the user can disable notifications, either for the entire device, or just for a specific application, in which case the user will never see them. If the device is turned off when a notification is due to fire then it is lost.

iOS - How can I schedule something once a day?

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.



Related Topics



Leave a reply



Submit