后台运行之定位服务

第一步

需要在info.plist中添加两个权限NSLocationAlwaysAndWhenInUseUsageDescription 和 NSLocationWhenInUseUsageDescription。

第二步

在Background Models中勾选Location updates


后台运行之定位服务_第1张图片
513887BAF82D32D3B35A3784D2C54A89.jpg
第三步

这里我测试后台持续时间是用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 

@interface ViewController ()

@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 *)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];
}

总结:

  • 比较费电
  • 审核人员会问你你想干啥(可以打电话或邮件交流,说明一下为什么需要后台持续获取位置)

你可能感兴趣的:(后台运行之定位服务)