美文网首页
iOS 后台保活和后台扫描ibeacon实现

iOS 后台保活和后台扫描ibeacon实现

作者: smallLabel | 来源:发表于2019-10-25 16:35 被阅读0次

后台保活有各种各样的方案,我采用的是后台定位方法,根据自己的APP类型自己选择吧。
直接进入主题:

  1. 引入#import <CoreLocation/CoreLocation.h>框架

  2. plist文件中添加定位所需的隐私权限Privacy - Location Always and When In Use Usage DescriptionPrivacy - Location When In Use Usage Description

  3. 开启后台模式


    1571993330762.jpg
  4. 在前台打开定位,同时开启了一个后台计时器任务

下面直接附上AppDelegate的代码


#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <CLLocationManagerDelegate>

@property (nonatomic) dispatch_source_t badgeTimer;
@property(nonatomic, strong) CLLocationManager *appleLocationManager;
@property(nonatomic, strong) CLBeaconRegion *beaconRegion;
@property(nonatomic, assign) __block UIBackgroundTaskIdentifier bgTask;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 写日志到本地文件,可以将控制台输出直接写入本地沙盒路径
    [self redirectNSlogToDocumentFolder];
    //注册推送
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];
    //  启动就直接开启定位
    [self startLocation];
    
  
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
   
    [self.window makeKeyAndVisible];
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self stratBadgeNumberCount];
    [self startBgTask];
}


- (void)startLocation {
    self.appleLocationManager = [[CLLocationManager alloc] init];
    self.appleLocationManager.allowsBackgroundLocationUpdates = YES;
    if (@available(iOS 11.0, *)) {
        self.appleLocationManager.showsBackgroundLocationIndicator = YES;
    }
    self.appleLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    self.appleLocationManager.distanceFilter = kCLDistanceFilterNone;
    self.appleLocationManager.delegate = self;
    [self.appleLocationManager requestAlwaysAuthorization];
    self.appleLocationManager.pausesLocationUpdatesAutomatically = NO;
    [self.appleLocationManager startUpdatingLocation];
    NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"FDA50693-A4E2-4FB1-AFCF-C6EB07647825"];
       if (@available(iOS 13.0, *)) {
           _beaconRegion = [[CLBeaconRegion alloc] initWithUUID:uuid identifier:@"beacon"];
       } else {
           _beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"beacon"];
       }
       
       _beaconRegion.notifyEntryStateOnDisplay = YES;
    _beaconRegion.notifyOnEntry = YES;
    [self.appleLocationManager startRangingBeaconsInRegion:self.beaconRegion];
//    [self.appleLocationManager startMonitoringForRegion:self.beaconRegion];
}

- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray<CLBeacon *> *)beacons inRegion:(CLBeaconRegion *)region {
//    for (CLBeacon *beacon in beacons) {
//        NSLog(@"\nUUID: %@\nMajor:%ld\nminor:%ld\n精度:%.4f\nrssi:%ld", beacon.proximityUUID.UUIDString, (long)beacon.major.integerValue, (long)beacon.minor.integerValue, beacon.accuracy, (long)beacon.rssi);
//    }
    NSLog(@"扫描到beacon");
    
}

- (void)startBgTask{
    UIApplication *application = [UIApplication sharedApplication];
    self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        //这里延迟的系统时间结束
        [application endBackgroundTask:self.bgTask];
        NSLog(@"%f",application.backgroundTimeRemaining);
    }];

}


- (void)stratBadgeNumberCount{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    _badgeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_badgeTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_badgeTimer, ^{

        [UIApplication sharedApplication].applicationIconBadgeNumber++;
        //如果系统给的剩余时间小于60秒 就终止当前的后台任务,再重新初始化一个后台任务,重新让系统分配时间,这样一直循环下去,保持APP在后台一直处于active状态。
        if ([UIApplication sharedApplication].backgroundTimeRemaining < 60) {
            [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
             self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
                self.bgTask = UIBackgroundTaskInvalid;
            }];
        }

    });
    dispatch_resume(_badgeTimer);
}

/** 苹果_用户位置更新后,会调用此函数 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
//    [self.appleLocationManager stopUpdatingLocation];
//    self.appleLocationManager.delegate = nil;
//    [self.appleLocationManager startMonitoringForRegion:self.beaconRegion];
    [manager startRangingBeaconsInRegion:self.beaconRegion];
    
    NSLog(@"success");
}

/** 苹果_定位失败后,会调用此函数 */
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//    [self.appleLocationManager stopUpdatingLocation];
//    self.appleLocationManager.delegate = nil;
    NSLog(@"error");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - 日志收集
- (void)redirectNSlogToDocumentFolder
{
    NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
    NSString *fileName = [NSString stringWithFormat:@"LOG-%@.txt",[dateformat stringFromDate:[NSDate date]]];
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];

    // 先删除已经存在的文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    [defaultManager removeItemAtPath:logFilePath error:nil];

    // 将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);

    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}

@end

相关文章

  • iOS 后台保活和后台扫描ibeacon实现

    后台保活有各种各样的方案,我采用的是后台定位方法,根据自己的APP类型自己选择吧。直接进入主题: 引入#impor...

  • iOS app进入后台后 应用保活 后台保活

    iOS app进入后台后 应用保活 后台保活

  • iOS后台保活

    iOS后台保活按时间可分为短时保活和长时间保活 短时保活的方式通过beginBackgroundTaskWithN...

  • iOS App后台保活

    级别:★☆☆☆☆标签:「iOS App 后台保活」「BackgroundTasks」「后台下载资源」作者: WYW...

  • 2020 Android后台保活进程

    Android安卓后台运行白名单实现优雅保活(转载) 简书|Android 后台运行白名单,优雅实现保活 知乎|A...

  • iOS 后台收到推送语音播报

    iOS App后台保活[http://www.cocoachina.com/articles/896173]iOS...

  • ios 后台保活

    后台保活就是在给APP添加了后台播放音乐的功能,需要在info.plist里面配置UIBackgroundMode...

  • iOS - 后台保活

    一、正常延长版保活(时间3min-40min不等) 二、永久版保活

  • iOS 后台保活

    一想到后台保活,我们最常见的就是音乐播放软件了,那在我们不是音乐软件的情况下我们要如何后台保活呢? 首先我们就要在...

  • ios后台保活

    原理:1.开启后台任务权限,播放音乐 2.app后台后,开启后台任务,定时轮询后台剩余时间,低于20秒时候再申请新...

网友评论

      本文标题:iOS 后台保活和后台扫描ibeacon实现

      本文链接:https://www.haomeiwen.com/subject/kgtevctx.html