In Swift, how to ivalidate NSTimer in AppDelegate on app startup?

I need to translate an iOS app from obj-c to swift. I have NStimer

a ViewController

one that downloads metadata from shoutcast every 30 seconds, but when the app cancels the action, it stops, when it enters the foreground, it starts up again.

Edit: OK. The problem is solved! I added two observers to viewDidLoad named UIApplicationWillResignActiveNotification

and UIApplicationWillEnterForegroundNotification

as shown below:

override func viewDidLoad() {
    NSLog("System Version is \(UIDevice.currentDevice().systemVersion)");
    super.viewDidLoad()
    self.runTimer()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "invalidateTimer", name: UIApplicationWillResignActiveNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "runTimer", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

      

and I did two functions. The first is for the start timer:

func runTimer(){
    loadMetadata()
    myTimer.invalidate()
    NSLog("timer run");
    myTimer = NSTimer.scheduledTimerWithTimeInterval(30.0, target: self, selector: "loadMetadata", userInfo: nil, repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()
    mainLoop.addTimer(myTimer, forMode: NSDefaultRunLoopMode)
}

      

and the second one to stop it:

func invalidateTimer(){
    myTimer.invalidate()
    NSLog("timer invalidated %u", myTimer);
}

      

Hope this helps someone. :)

+3


source to share


1 answer


I suggest you use the appropriate system for your task: https://developer.apple.com/library/ios/documentation/iphone/conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4- SW56



Applications that periodically check for new content can request to wake them up so that they can initiate a fetch operation for that content. To support this mode, enable the Background fetch option from the Background Modes section of the Features tab in your Xcode Project. (You can also enable this support by including the UIBackgroundModes key with the fetch value in your applications Info.plist file.) ...

When a good opportunity arises, the system wakes up or runs your application in the background and calls the application delegates application:performFetchWithCompletionHandler:

. Use this method to check for new content and initiate a download operation if content is available.

0


source







All Articles