第一步
需要在info.plist中添加两个权限NSLocationAlwaysAndWhenInUseUsageDescription 和 NSLocationWhenInUseUsageDescription。
第二步
在Background Models中勾选Location updates
第三步
这里我测试后台持续时间是用APP角标计数的,因为发现如果本地调试退到后台和拔出线正常跑的时间结果不一样,在UIBackgroundTaskIdentifier情况下,如果本地连线调试,也可以很久,但是拔出线设置角标也就三分钟。所以这里要用到applicationIconBadgeNumber,在iOS7中直接设置applicationIconBadgeNumber没有问题,但是在iOS8之后设置applicationIconBadgeNumber,程序没有反应,因为在iOS8之后想要设置applicationIconBadgeNumber,需要在didFinishLaunchingWithOptions进行用户授权。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//注册推送
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
return YES;
}
第四步
s#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic ,strong) CLLocationManager *locationManager;
@property (nonatomic ,assign) NSInteger number;
- (IBAction)buttonClick:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
/** 苹果_用户位置更新后,会调用此函数 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
self.number++;
[UIApplication sharedApplication].applicationIconBadgeNumber = self.number;
NSLog(@"success");
}
/** 苹果_定位失败后,会调用此函数 */
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"error");
}
- (IBAction)buttonClick:(id)sender
{
self.number = 0;
[UIApplication sharedApplication].applicationIconBadgeNumber = self.number;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.allowsBackgroundLocationUpdates = YES;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];
[self.locationManager startUpdatingLocation];
}
总结:
- 比较费电
- 审核人员会问你你想干啥(可以打电话或邮件交流,说明一下为什么需要后台持续获取位置)