2016-07-13 43 views
0

我想在手机锁定时停止计时器,所以我该怎么做? 在代码中设置计时器,当他进入后台模式,所以它的工作原理,但我不知道如何使时间停止时,电话被锁定。有没有人有想法?在后台模式下锁定手机时的停止时间

var backgroundTaskIdentifier: UIBackgroundTaskIdentifier? 

override func viewDidLoad() { 
    super.viewDidLoad() 


    backgroundTaskIdentifier = UIApplication.shared().beginBackgroundTask { 
     UIApplication.shared().endBackgroundTask(self.backgroundTaskIdentifier!) 

    } 

    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(LoangeController.cosumTime), userInfo: nil, repeats: true) 
    startTime = NSDate.timeIntervalSinceReferenceDate() 




} 


func cosumTime() { 

    let currentTime = NSDate.timeIntervalSinceReferenceDate() 

    var elapsedTime: TimeInterval = currentTime - startTime 

    let hours = UInt8(elapsedTime/3600.0) 

    elapsedTime -= (TimeInterval(hours) * 3600) 

    let minutes = UInt8(elapsedTime/60.0) 

    elapsedTime -= (TimeInterval(minutes) * 60) 

    let seconds = UInt8(elapsedTime) 

    elapsedTime -= TimeInterval(seconds) 


    //add the leading zero for minutes, seconds and millseconds and store them as string constants 

    let strHours = String(format: "%02d", hours) 
    let strMinutes = String(format: "%02d", minutes) 
    let strSeconds = String(format: "%02d", seconds) 

    let counttime = "\(strHours): \(strMinutes): \(strSeconds)" 

    timeconsum = counttime 

    print("\(counttime)") 


    if timeconsum == timeout { 
     print("Remind TimeOut") 
     let UUID = Foundation.UUID().uuidString 

     Notification.addNotification(title: "TimeOut Put your Phone away", date: CurrentTime, uuid: UUID) 

    } 
} 

回答

0

卢克有正确的答案,我只是要添加更多的细节。在你的应用程序代理,您可以添加

func applicationWillResignActive(application: UIApplication) { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
} 

如果需要恢复计时器上的活动,你可以在你的应用程序代理

func applicationDidBecomeActive(application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

使用此方法欲了解更多信息停止和启动定时器,我建议此链接。祝你好运! How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?

+0

所以这个功能是当用户离开我的应用程序,但我需要一个func时,用户锁定他的手机,给它这个func? –

+0

目前还没有具体的委托方法在用户锁定手机时通知该应用程序。您只能在应用程序移至非活动状态时收到通知。幸运的是,当用户锁定手机时,应用程序会迅速转移到非活动状态,几乎完成了您所寻找的同样的事情。 – Amloelxer

+0

Oke,感谢您的帮助 –

0

您需要添加applicationWillResignActive处理程序在你的应用程序代理

func applicationWillResignActive(_ application: UIApplication) { 
    //Pause timer 
} 

每当手机被锁定或进入睡眠状态,这应该叫。

相关问题