同学在做一个关于gps定位的app,需要用到没间隔一定时间返回一次位置信息的功能,故收集了一些相关资料。
首先了解一苹果后台运行的机制: http://mobile.51cto.com/iphone-281284.htm
http://blog.youkuaiyun.com/ssihc0/article/details/7240495
http://www.2cto.com/kf/201312/261962.html
配置plist文件如图。
然后添加代码如下:
#pragma mark 程序需要后台运行加入的代码
- (void)applicationDidEnterBackground:(UIApplication *)application{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
});
[NSThread detachNewThreadSelector:@selector(testbackground1) toTarget:self withObject:nil];
//用这行代码测试一下能不能后台,查看能不能每10秒钟打印@“1”
}
-(void)testbackground1{
while (1) {
sleep(10);
NSLog(@"1");
}
}