2016-12-06 71 views
0

Theres任何方式来保持应用程序运行,而用户不杀死应用程序?我发现这可以通过RunLoop.current.run()完成,但是当在应用程序中像应用程序完全冻结一样击中应用程序时,我有一个Timer,它在RunLoop之前声明,似乎是正确初始化的,但是计时器未PROC,继承人一个简单的例子Swift保持cli应用程序运行

import Foundation 

print("start") 

let _ = Timer.init(timeInterval: 1, repeats: true) { _ in 
    print("proc") 
} 

RunLoop.current.run() 

print("end") 

看来,我不抓是如何工作的。

问候

回答

2

的问题仅仅是你不知道如何使用定时器。它是不够的,以init它。你必须时间表它。不要致电init...,请致电Timer.scheduledTimer...,整个事情将为你而生。然后你会看到,实际上你的进程正在运行。

我把这个(因为我没有使用塞拉利昂我不能使用基于块的定时器),它工作得很好:

进口基金会

class TimerHolder:NSObject { 
    var timer : Timer? 
    func timerFired(_:Timer) { print("fired") } 
    override init() { 
     super.init() 
     self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, 
      selector: #selector(timerFired), 
      userInfo: nil, repeats: true) 
    } 
} 

print("start") 

_ = TimerHolder() 

RunLoop.current.run() 

print("end") 
+0

的感谢!我的糟糕,很长一段时间没有使用定时器...... – norman784

+0

即使没有计时器作为测试,''end''从不打印,所以你可以看到你的命令行工具_is_仍在运行。 – matt

相关问题