iOS 通过定位获取常驻后台

 
 

我们知道ios 的应用,大部分都是进入后台,就不会执行任何操作,但是 ,很多时候我们希望程序进入后台,也能执行一些检测操作,比如说,应用进入后台,我们仍然可以实时去获取当前的位置信息。下面我们来了解下,ios 获取后台时间的几种方式 根据苹果文档中关于后台执行的描述,任何app都有3分钟左右的后台任务执行时间。 3分钟后,app会被iOS强行挂起。 但是,有几类app允许有“无限的”后台运行时间:

  1. Audio。
  2. Location/GPS。
  3. VoIP。

你可以将任何app声明为上述3种类型以获得无限的后台运行时间,但当你提交app到App Store时,苹果会审查你的app,一旦发现你“滥用”了后台API,你的app将被拒绝。也即是说你在info.plist 设置这几种backgroundmode,你的程序必须含有这些功能,你的程序才会有审核通过,你想获取应用进入后台获取更多的后台时间,还要看苹果给不给机会了。。。

1 上面有一种方式苹果文档说到任何应用都有3分钟的后台执行任务时间。好吧先看下一段代码 (1)

- (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;
        }); 
    });
}

这种方式,是不需要再info.plist 配置就可以在申请到短时间的后台运行时间,苹果也不会对这个进行审核
2 第二种方式,也是今天想着重提到的,就是通过定位获取更多的后台使用的时间,这种适合于需要在后台收集用户的定位的场景,例如滴滴打车此类应用。
上面已经提到了这种方式,需要在info.plist 设置


C96A6568-2EEA-475D-B76E-556F05B43A7F.png


因为在苹果在info.plist 进行了设置,苹果也会对其 进行审核。
接下来是在来看下代码段

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _task = [BGTask shareBGTask];
    UIAlertView *alert;
    //判断定位权限
    if([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied)
    {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"应用没有不可以定位,需要在在设置/通用/后台应用刷新开启" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)
    {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可以定位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        _location = [[CLLocationManager alloc]init];
        _location.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//导航级别的精确度
        _location.allowsBackgroundLocationUpdates = YES; //允许后台刷新
        _location.pausesLocationUpdatesAutomatically = NO; //不允许自动暂停刷新
        _location.distanceFilter = kCLDistanceFilterNone;  //不需要移动都可以刷新
        [_location startUpdatingLocation];
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(log) userInfo:nil repeats:YES];
    }
    return YES;
}
//进入后台开启定位
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [_location startUpdatingLocation];
}

经测试而得只要这样无论在前台或者是后台,log 这个方法都是有打印的。这里必须注意一点就是

  _location.distanceFilter = kCLDistanceFilterNone;  //不需要移动都可以刷新

之前因为要这样设置,不然就各种掉坑,不移动就不会执行定位,不定位的话,那么后台进程也就挂起了,那么就不能执行任何操作
(2)其实这种后台刷新是很暴力的,导航仪不断在定位,你才可以获取后台活跃的时间,去执行你的一些想要的操作,但是不断的定位会导致,电量消耗过快,我测试一个小时奖金跑去了10%的电量,那么有没有一些更优的方案,减少定位的次数,然后又能让后台活跃呢
下面来讲解下思路


D953031F-A8AD-4223-8D22-622586039EE2.png


这个优化面临的问题,就是当程序进入了后台,如果让定位停止了,那么程序就后台就无法活跃了,就是把程序进入后台的问题解决了,那就好办了,看了上图,也可以看出,思路主要是在当前正在定位的时候,10秒后关闭当前的定位,然后此时开启后台任务backgroundtask,那么只要就会有3分钟的活跃时间,那么在这个后台任务有效时间内再次开启定位的话,程序在后台便依旧可以活跃,那么只要开启和关闭循环进行,就可以实现常驻后台了,那么这个时间间隔可以自定义,在自己需要的范围内即可,但是不能超过3分钟,那么接下来在看看主要代码实现

//定位回调里执行重启定位和关闭定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    NSLog(@"定位收集");
//正在手机定位不执行任何操作
    if (isCollect) {
        return;
    }
    [self performSelector:@selector(restartLocation) withObject:nil afterDelay:120];
    [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10];
    isCollect = YES;
}
-(void)restartLocation
{
    NSLog(@"重新启动定位");
    CLLocationManager *locationManager = [BGLogation shareBGLocation];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // 不移动也可以后台刷新回调
    if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0) {
        [locationManager requestAlwaysAuthorization];
    }
    [locationManager startUpdatingLocation];
    [self.bgTask beginNewBackgroundTask];
}
//停止后台定位
-(void)stopLocation
{
    NSLog(@"停止定位");
    isCollect = NO;
    CLLocationManager *locationManager = [BGLogation shareBGLocation];
    [locationManager stopUpdatingLocation];
}

接下来是demo 的地址
https://github.com/heysunnyboy/locationdemo.git
可以看到下面的代码 ,在delegate 里设置的定时器一直都在跑没有停止就知道这个后台常驻是有效的

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _task = [BGTask shareBGTask];
    UIAlertView *alert;
    //判断定位权限
    if([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied)
    {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"应用没有不可以定位,需要在在设置/通用/后台应用刷新开启" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)
    {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可以定位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        self.bgLocation = [[BGLogation alloc]init];
        [self.bgLocation startLocation];
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(log) userInfo:nil repeats:YES];
    }
    return YES;
}


作者:嘿晴天
链接:http://www.jianshu.com/p/d1ecc467faff
來源:简书

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在iOS开发中获取图片中二维码的定位,可以使用CoreImage框架。具体步骤如下: 1. 使用CIImage加载图片: ``` CIImage *image = [CIImage imageWithCGImage:image.CGImage]; ``` 2. 创建CIDetector并设置识别类型: ``` CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}]; ``` 3. 识别二维码: ``` NSArray *features = [detector featuresInImage:image]; ``` 4. 遍历识别结果,获取二维码定位: ``` for (CIQRCodeFeature *feature in features) { NSArray *corners = feature.corners; // 获取定位四个角的坐标 // 在图像上绘制定位 UIGraphicsBeginImageContext(imageSize); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); CGContextSetLineWidth(context, 2.0); CGContextMoveToPoint(context, corners[0].x, corners[0].y); CGContextAddLineToPoint(context, corners[1].x, corners[1].y); CGContextAddLineToPoint(context, corners[2].x, corners[2].y); CGContextAddLineToPoint(context, corners[3].x, corners[3].y); CGContextAddLineToPoint(context, corners[0].x, corners[0].y); CGContextStrokePath(context); UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } ``` 这样就可以在原图上绘制出二维码的定位了。需要注意的是,CIDetector只能识别二维码,如果要识别其他类型的码,需要设置不同的detector类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值