2014-12-07 96 views
1

我想在iOS8的應用程序處於後臺模式時運行週期性任務。我很快就寫了下面的代碼,但是失敗了。有人能指出什麼是錯的嗎?在iOS8上以後臺模式運行週期性任務

這裏是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) 
} 

回答

0

你嘗試使用:

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

我不知道,如果這是這樣的,但在迅速傳遞函數求作爲參數通常是這樣的。

+0

這不是重點,但無論如何感謝。 – anonaka 2014-12-09 07:03:32

1

有人告訴我調用「beginBackgroundTaskWithName」就是答案。

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) 
}