I am developing an app which uploads a product (JSON) to server. Now, every product object consists of many images. A product is only uploaded to server if all images associated with that product have already been uploaded. In case all images for the product have not been uploaded, the product should be stored in 'PENDING' state in the mobile database (I am using Realm).
I want a background task to periodically (every 15 minutes) check the DB for such failed product uploads, check if all images associated with the product have now been uploaded and queue the product for upload to server.
This background task will execute ONLY when the app is running, not otherwise. The task should be launched at boot and killed on app close.
I found some relevant solutions (relating to NSTimer and background modes in iOS, etc.) but nothing addresses my problem directly. Please direct me in the right direction! Thanks!
Background modes are helpful when you need background tasks get executed when app is not running so thats not what you want. NSTimer can do a job here and you need to schedule it after application becomes active in app delegate and invalidate just after application enter background. A simple example might look like this:
var timer:NSTimer!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
timer = NSTimer.scheduledTimerWithTimeInterval(60 * 15, target: self, selector: "uploadData", userInfo: nil, repeats: true)
return true
}
func applicationDidEnterBackground(application: UIApplication) {
timer.invalidate()
}
func applicationWillEnterForeground(application: UIApplication) {
timer = NSTimer.scheduledTimerWithTimeInterval(60 * 15, target: self, selector: "uploadData", userInfo: nil, repeats: true)
}
func uploadData(){
// Query unsychronzied data and send them to server here
}