本文實現iOS無限後臺的原理是:開機iOS允許的後臺定位實現APP在後臺無限運行。
具體步驟如下
在plist文件裏添加:NSLocationWhenInUseUsageDescription,NSLocationAlwaysUsageDescription,Required background modes 數組添加:App registers for location updates值
然後在AppDelegate.m文件裏實現如下代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = [[RootViewController alloc] init];
[self initData];
[self.window makeKeyAndVisible];
return YES;
}
// 進入前臺
- (void)applicationWillResignActive:(UIApplication *)application
{
}
// 進入後臺
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
#pragma mark ---- 私有方法
// 初始化數據
-(void)initData
{
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.pausesLocationUpdatesAutomatically = NO;
[_locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// 成功回調
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// 失敗回調
}