0

Hello

I'm trying to execute a task in background because I need to while the application is running being pulling data from the server. I write the code in the AppDelegate.swift, this is the code that i wrote:

 class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? let manager = AppManager.manager var timer: NSTimer? = nil func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.timer = NSTimer(timeInterval: 1.0, target: self, selector: "UpdateDeviceData:", userInfo: nil, repeats: true) return true } func UpdateDeviceData(timer:NSTimer) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in print("do some background task") dispatch_async(dispatch_get_main_queue(), { () -> Void in print("update some UI") }) }) } } 

I put a breakpoint in the line "print" and it never being executed.

Please any idea about what could be the problem?

Note:I'm using Xcode 7 beta and Swift

0

1 Answer 1

2

You need to schedule the timer on a run loop - you're just assigning it to a variable. Try using the class method + scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: -

so

NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "UpdateDeviceData:", userInfo: nil, repeats: true) 
Sign up to request clarification or add additional context in comments.

9 Comments

thank you @RichTolley, do you have any example of using this method?
WARNING: @JoseRaulPerera It's important to note that using the class method will cause the target to be retained by the timer. This means that the target will not be dealloc'ed until the NSTimer instance resulting from this class method is invalidated via the timer's invalidate method. Though it won't matter in this specific context, it's a common mistake for those that are new to using scheduled NSTimer instances.
UpdateDeviceData: If you miss the : it's a different method
@ThuggishNuggets, thank you you're right but this is what I need, to be continue until I stopped with timer.invalidate()
@Thuggish Nuggests is definitely right that to say that you need to be careful with the class method though, otherwise you can inadvertently end up with multiple timers and memory issues. But as long as you remember to invalidate it you'll be ok
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.