首页 > 其他分享 >iOS开发基础102-后台保活方案

iOS开发基础102-后台保活方案

时间:2024-07-16 16:30:33浏览次数:10  
标签:后台 end self iOS 保活 application Background 102 UIApplication

iOS系统在后台执行程序时,有严格的限制,为了更好地管理资源和电池寿命,iOS会限制应用程序在后台的运行时间。然而,iOS提供了一些特定的策略和技术,使得应用程序可以在特定场景下保持后台运行(即“后台保活”)。以下是iOS中几种常见的后台保活方案,并附上示例代码:

一、后台任务

利用beginBackgroundTaskendBackgroundTask来执行后台任务。后台任务将在应用程序进入后台时仍能保持有限的时间执行任务。

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTask;

@end

@implementation AppDelegate

- (void)applicationDidEnterBackground:(UIApplication *)application {
    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 在这里执行你的后台任务
        for (int i = 0; i < 100; i++) {
            NSLog(@"Background task running %d", i);
            [NSThread sleepForTimeInterval:1];
        }
        
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    });
}

@end

二、使用Background Fetch

利用Background Fetch,系统会间歇性地唤醒应用程序,以便它可以执行任务或获取数据。需要在Xcode的“Capabilities”中开启Background Modes,并勾选“Background fetch”。

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    return YES;
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 在这里执行你的后台数据获取任务
    NSLog(@"Background fetch started");

    // 模拟数据获取
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"Background fetch completed");
        completionHandler(UIBackgroundFetchResultNewData);
    });
}

@end

三、使用远程通知(Silent Push Notification)

利用远程通知,在接收到通知时,系统会唤醒应用程序执行指定的任务。需要开启Remote notifications,在Application Capabilities中勾选“Remote notifications”。

#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
    }];
    return YES;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 在这里处理收到的远程通知
    NSLog(@"Received remote notification");

    // 模拟处理任务
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"Handled remote notification");
        completionHandler(UIBackgroundFetchResultNewData);
    });
}

@end

四、使用特定的后台模式(Background Modes)

iOS提供了一些特定的后台模式,允许程序在后台持续运行。常见的后台模式包括:

  • Audio: 允许应用程序在后台播放音频。
  • Location: 允许应用程序在后台持续获取位置更新。
  • VoIP: 允许应用程序在后台侦听VoIP事件。
  • Bluetooth: 允许应用程序与蓝牙设备通信。

1. Audio后台模式

需要在Xcode的“Capabilities”中开启Background Modes,并勾选“Audio, AirPlay, and Picture in Picture”。

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate ()

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSError *error = nil;
    NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"audioFileName" withExtension:@"mp3"];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
    [self.audioPlayer prepareToPlay];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    [audioSession setActive:YES error:&error];
    
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self.audioPlayer play];
}

@end

2. Location后台模式

需要在Xcode的“Capabilities”中开启Background Modes,并勾选“Location updates”。

#import <CoreLocation/CoreLocation.h>

@interface AppDelegate () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"Background location: %@", location);
}

@end

五、使用后台URLSession

使用NSURLSession来执行后台下载和上传任务。需要在后台配置中开启Background Modes,并勾选“Background fetch”和“Remote notifications”。

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, NSURLSessionDelegate, NSURLSessionDownloadDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) NSURLSession *backgroundSession;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.example.background"];
    self.backgroundSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSURL *url = [NSURL URLWithString:@"http://example.com/largefile.zip"];
    NSURLSessionDownloadTask *downloadTask = [self.backgroundSession downloadTaskWithURL:url];
    [downloadTask resume];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"Download completed: %@", location);
    // 处理下载结果,比如保存文件
}

@end

通过上述几种方案,我们可以在iOS应用程序中实现各种场景下的后台保活。每种方案都有其适用的场景和限制,开发者需要根据应用的实际需求和系统提供的特性,选择合适的后台保活方案。

标签:后台,end,self,iOS,保活,application,Background,102,UIApplication
From: https://www.cnblogs.com/chglog/p/18305545

相关文章

  • iOS开发基础101-指纹和面部识别
    在iOS开发中,使用FaceID和TouchID可以为用户提供安全的生物识别认证,而手势识别(GestureRecognition)可以增加用户交互的便利性和灵活性。下面将详细介绍这三种技术,并给出如何封装一个统一的工具类来供外部使用。一、FaceID与TouchID1.设置与配置在使用FaceID和TouchID之前,需要在......
  • vue项目中使用axios(自用)
    ————流程参考 在vscode的集成终端中输入npminstallaxios回车安装重启项目(重新运行) 在script中导入axiosimportaxiosfrom'axios'; 在default中的data同级mounted()中按如下获取数据mounted(){//发送异步请求,获取数据//输入thenc......
  • 代码随想录算法训练营第十三天 | 144.二叉树的前序遍历、94、二叉树的中序遍历、145、
    144.二叉树的前序遍历题目:.-力扣(LeetCode)思路:有递归法和使用栈来模拟递归的迭代法。代码:1.递归/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode():val(0),left(nu......
  • #BAS3102. 练18.2 苹果和虫子
    3102:练18.2苹果和虫子【题目描述】你买了一箱......
  • STM32H750XBH6使用LTDC点亮7英寸LCD(1024*600)
    起因最近画的板子回来了,正好试验一下画的LCD接口是否有问题,买的正点原子的7寸lcd屏幕,使用Cubemx去配置LTDC点亮lcd。工程配置首先打开Cubemx,选好芯片型号(我用的是STM32H750XBH6),配置高速外部时钟;时钟树配置主频为400MHz(时钟速度按照自己需求来,我一般开到400M完全够用);打开......
  • Ajax和Axios
    1.1Ajax介绍1.1.1Ajax概述我们前端页面中的数据,如下图所示的表格中的学生信息,应该来自于后台,那么我们的后台和前端是互不影响的2个程序,那么我们前端应该如何从后台获取数据呢?因为是2个程序,所以必须涉及到2个程序的交互,所以这就需要用到我们接下来学习的Ajax技术。Ajax:全......
  • MBR10200CT-ASEMI智能AI应用MBR10200CT
    编辑:llMBR10200CT-ASEMI智能AI应用MBR10200CT型号:MBR10200CT品牌:ASEMI封装:TO-220批号:最新恢复时间:35ns最大平均正向电流(IF):10A最大循环峰值反向电压(VRRM):200V最大正向电压(VF):0.70V~0.90V工作温度:-65°C~175°C芯片个数:2芯片尺寸:mil正向浪涌电流(IFMS):150AMBR10200CT特性:......
  • VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS Huawei (华为) 定制版
    VMwareESXi8.0U3macOSUnlocker&OEMBIOSHuawei(华为)FusionServer定制版ESXi8.0U3标准版,Dell(戴尔)、HPE(慧与)、Lenovo(联想)、Inspur(浪潮)、Cisco(思科)、Hitachi(日立)、Fujitsu(富士通)、NEC(日电)、Huawei(华为)、xFusion(超聚变)OEM定制版......
  • Vue.js Ajax(axios)
     Vue.js2.0版本推荐使用axios来完成ajax请求。Axios是一个基于Promise的HTTP库,可以用在浏览器和node.js中。Github开源地址: https://github.com/axios/axios安装方法使用cdn:<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>或<scri......
  • Vue.js Ajax(axios)
    Vue.js2.0版本推荐使用axios来完成ajax请求。Axios是一个基于Promise的HTTP库,可以用在浏览器和node.js中。Github开源地址: https://github.com/axios/axios安装方法使用cdn:<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>或<script......