Reputation: 271
I did this code in swift (2.0)
var timer: dispatch_source_t!
var a = 0
func startTimer() {
let queue = dispatch_queue_create("com.domain.app.timer", nil)
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC) // every 60 seconds, with leeway of 1 second
dispatch_source_set_event_handler(timer) {
self.a = self.a+1
print( self.a)
}
dispatch_resume(timer)
}
func stopTimer() {
dispatch_source_cancel(timer)
timer = nil
}
the problem is that this code work well on the emulator , I see in the consol a number incrementing every second, and when I go the the home page of the emulator the number is still incrementing , On the device, the number stop incrementing as soon as we quit the application context . so how can I make it keep incrementinf on the device ?
Upvotes: 0
Views: 512
Reputation: 27345
By default iOS applications do not support background execution. You can start execute finite-length background tasks with beginBackgroundTaskWithName
method or you have to enable special background modes like voip, location, remote notifications to run in background. (The use of those modes are reviewed by Apple when you submit app to Appstore)
More info: Background execution documentation
I agree that it is quite misleading that it works on simulator, when it is not supposed to.
Upvotes: 1