当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

iOS后台模式教程 (一) - 代码与哲学

作者:小梦 来源: 网络 时间: 2024-06-03 阅读:

Background Modes Tutorial: Getting Started

iOS后台模式教程 (一)

原文

使用场景

在iOS7之前的系统中,当应用被挂起,拥有连续的10分钟时间来处理之前的任务,然后才会被系统终止。

所以,后台模式有一些特殊的使用场景。例如,更新位置,播放视频音频,和更新服务器请求。

开始

第一步设置工程中的Capabilities标签栏,打开Background Modes服务。

出现的Modes选项有

  • Audio,AirPlay and Picture in Picture 视频音频播放

  • Location updates 位置更新

  • Voice over IP IP电话

  • Newsstand downloads 杂志下载

  • External accessory communication 外部附件通信,包括App Watch

  • Uses Bluetooth LE accessories 蓝牙LE配件

  • Acts as a Bluetooth LE accessory 作为蓝牙LE配件

  • Background fetch 后台抓取服务

  • Remote notifications 远程通知

这里介绍几个模式的用法。

播放音频

下面这段代码加入viewDidLoad中,程序开始时会按顺序播放两个mp3文件。在勾选Audio,AirPlay and Picture in Picture后,挂起程序时,音乐还是会继续播放 。

引用

#import <AVFoundation/AVFoundation.h>

参数

@property (nonatomic, strong) AVQueuePlayer *player;

viewDidLoad

 NSError *sessionError = nil;    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];    NSArray *queue = @[           [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"music" withExtension:@"mp3"]],[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"pop" withExtension:@"mp3"]]];    self.player = [[AVQueuePlayer alloc] initWithItems:queue];self.player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;    [self.player play];

位置服务

参数

@property (nonatomic, strong) CLLocationManager *locationManager;@property (nonatomic, strong) NSMutableArray *locations;

初始化LocationManager

self.locations = [[NSMutableArray alloc] init];self.locationManager = [[CLLocationManager alloc] init];self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;self.locationManager.delegate = self;

启动位置更新服务

[self.locationManager startUpdatingLocation];

记录新位置

- (void)locationManager:(CLLocationManager *)manager    didUpdateToLocation:(CLLocation *)newLocation           fromLocation:(CLLocation *)oldLocation{    // Add another annotation to the map.     if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive)    {           //前台运行    else    {//后台运行        NSLog(@"App is backgrounded. New location is %@", newLocation);    }}

代码解析

根据 UIApplication.sharedApplication.applicationState == UIApplicationStateActive 可以判断回调过程中,程序是否挂起。记住要勾选Location updates ,当你在制作一个跑步或骑车软件时,需要用到这项功能。

一般性有限长度任务

这个宽泛的功能包括上传或者下载任务等。

@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{//        NSLog(@"Background handler called. Not running background tasks anymore.");        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];        self.backgroundTask = UIBackgroundTaskInvalid;    }];

您也可以在任务完成的时候,主动调用 [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; 终止任务。
程序会在后台运行,但并不是无限时间。

热点阅读

网友最爱