当我调用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:主线程并将时间间隔设置为5秒时,下面的代码被执行,并且在5秒后调用定时器选择器.
但是如果我在某个后台线程中尝试相同,下面的代码scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:将不会被执行,它将等待定时器触发然后执行.当然,为了在后台线程中运行计时器,我首先得到了一个实例NSRunLoop并运行它.
有没有办法在后台线程中设置定时器并使其无阻塞,所以代码在它立即执行后?
我根本不明白它,但NSTimer在我的应用程序肯定是在后台运行.我有一个NSLog由计时器运行的mehod,它在后台进行记录.它位于带有iOS 4.2.1的iPhone 4上.我在Info.plist中声明了位置背景支持.
我在这里和其他地方阅读了文档和许多讨论,这是不可能的.这是一个iOS错误吗?还是没有文档的功能?我不想使用它并在不久的将来发现,例如随着iOS 4.3的出现,Apple默默地"修复"它并且应用程序无法正常工作.
有人知道更多吗?
我试过这个但是在iOS 7和Xcode 4.6.2中的工作时间不超过180秒.请帮我
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
-(void) timerMethod{
NSLog(@"in timerMethod");
}
Run Code Online (Sandbox Code Playgroud) class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
println("Something cool")
}
}
Run Code Online (Sandbox Code Playgroud)
对于模拟器来说没关系,我会通过点击主页按钮获得连续的"Something cool".但是当我用我的iPhone调试应用程序时,它就解决了.当我点击主页按钮并使我的应用程序运行背景时,我没有得到任何东西.有人告诉我,我可以播放一段很长的空白音乐,让我的应用程序在后台运行.但我不知道如何用swift @matt在后台播放音乐
nstimer ×4
ios ×3
background ×2
cocoa-touch ×1
ios5 ×1
nsthread ×1
runloop ×1
swift ×1
timer ×1