问题
I need to add an NSTimer in the applicationDidEnterBackground method; I tried adding
NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("test"), userInfo: nil, repeats: true)
But it's not working.
回答1:
According to your comments, your declaration should look something like this:
NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: "test:", userInfo: nil, repeats: false)
Note two things:
- You can pass a string literal to the selector parameter directly (no need for
Selector()syntax), but this is of course optional. The NSTimer expects the selector that will fire when it hits zero to accept a parameter (of type
NSTimer) to which it will pass itself, so a colon (:) is needed at the end of the selector name to indicate that it will take a parameter.The selector should have the following signature:
timerFireMethod:(including a colon to indicate that the method takes an argument). The timer passes itself as the argument, thus the method would adopt the following pattern:- (void)timerFireMethod:(NSTimer *)timerFrom the NSTimer documentation.
Because of this, you'll also have to modify your function declaration a bit:
func test(timer: NSTimer) { // Proceed to grab location from background }
来源:https://stackoverflow.com/questions/28840510/swift-applicationdidenterbackground-timer