S. Oyen
S. Oyen

Reputation: 23

Running a function even when app is in background

I have a save function that saves values to core data every day at a specific time. But when the app is not running, or is in background - it will of course not save the values. Is there any way of solving this issue - saving the data whilst the app is running in background? Here's the function:

  func addValueDateToCore() {

// make sure data is not saved twice
    if hasBeen == 0 {

        hasBeen += 1

    let newData: SavedAwayData = NSEntityDescription.insertNewObject(forEntityName: "SavedAwayData", into: DatabaseController.getContext()) as! SavedAwayData

    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    dateFormatter.timeStyle = .none

    newData.name = dateFormatter.string(from: Date())
    newData.greenCustomer2 = veryHappyCustomer
    newData.orangeCustomer2 = happyCustomer
    newData.redCustomer2 = unHappyCustomer

    DatabaseController.saveContext()
    }


}

The hasBeen variable gets mutated to 0 by another function a couple of seconds after addValueDateToCore(), to those of whom might want to comment on that.

Upvotes: 1

Views: 1130

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70936

Apps can only run in the background in certain very specific situations like playing audio or handling background network connections. Your question doesn't sound like it fits any of Apple's background modes, but take a look at the docs and see what you think.

A better way (or at least a way that would work on iOS) might be to deal with this when your app launches. Look to see if any days were missed, and fill in the missing data.

Upvotes: 1

Related Questions