您好
我正在尝试在后台执行任务,因为我需要在应用程序运行时从服务器中提取数据。我在AppDelegate.swift中编写代码,这是我写的代码:
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")
})
})
}
}
我在“print”行中设置了断点,但它从未执行过。
请问可能出现什么问题?
注意:我正在使用Xcode 7 beta和Swift
答案 0 :(得分:2)
您需要在运行循环上安排计时器 - 您只需将其分配给变量即可。尝试使用类方法+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
-
所以
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "UpdateDeviceData:", userInfo: nil, repeats: true)