您的位置:首页 > 移动开发 > IOS开发

iOS 无限后台

2015-06-05 09:40 162 查看
本文实现iOS无限后台的原理是:开机iOS允许的后台定位实现APP在后台无限运行。具体步骤如下

在plist文件里添加:NSLocationWhenInUseUsageDescription,NSLocationAlwaysUsageDescription,Required background modes 数组添加:App registers for location updates值

然后在AppDelegate.m文件里实现如下代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions {

// Override point for customization after application launch.

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
{

backgroundTask = [application
beginBackgroundTaskWithExpirationHandler:^{

NSLog(@"applicationD in Background");
}];
}

#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
{

//
失败回调
}

这样就能实现APP在后台无限运行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: