anonaka
anonaka

Reputation: 95

Run periodic task in background mode on iOS8

I want to run a periodic task when my application is in background mode on iOS8. I wrote a following code in swift but failing. Can some point out what is wrong?

Here is my code from AppDelegate.swift

let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND,0)

func applicationDidEnterBackground(application: UIApplication) {
    println("did enter background")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

func myBackgroundTask() {
    NSThread.sleepForTimeInterval(0.5)
    println("this is back ground task")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

Upvotes: 1

Views: 2014

Answers (2)

anonaka
anonaka

Reputation: 95

Someone told me calling "beginBackgroundTaskWithName" is the answer.

func applicationDidEnterBackground(application: UIApplication) {
    println("did enter background")
    application.beginBackgroundTaskWithName("myBgTask", expirationHandler: nil)
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

func myBackgroundTask() {
    NSThread.sleepForTimeInterval(0.5)
    println("this is back ground task")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

Upvotes: 1

Endre Olah
Endre Olah

Reputation: 955

Did you try to use:

dispatch_async(self.backgroundQueue, Selector("myBackgroundTask"))

I am not sure if this is the way, but in swift passing a func as a parameter is usually like this.

Upvotes: 0

Related Questions