Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to run iOS for a long time in the background

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how iOS can run for a long time in the background, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

Preface

Generally speaking, after APP is suspended by pressing the Home key, the backgroundTimeRemaining of APP, that is, the background running time, is only about 3 minutes. If you exit APP and return to APP,APP in more than ten or 22 minutes or more, you will return to the state you first opened, that is, the home page. Some projects need to run in the background for a period of time after being suspended, so that there is enough time to complete the operation of docking with the server, or the need to run all the time; if necessary, after the APP is suspended, apply for the background to extend the background running time.

There are several ways to apply for APP to run in the background:

Play music

Positioning

Newsstand downloads

Fetch et al.

Here we mainly talk about how to play silent music in the background (actually it is not) and which method to use, check the above picture. If there is a need for audio playback in my project, if not, find a reason to play audio, or do it in other ways.

Realize

Here, two singletons are used: telephone monitoring (XKTelManager) and background operation (XKBGRunManager). Telephone monitoring can be ignored and used according to the situation; the singleton is used to facilitate management.

XKTelManager.h

# import @ interface XKTelManager: whether NSObject/// runs @ property (nonatomic,assign) BOOL inBackgroundRun;+ (XKTelManager *) sharedManager;/** call monitoring * /-(void) startMonitor;@end in the background

XKTelManager.m

# import "XKTelManager.h" # import "XKBGRunManager.h" # import # import static XKTelManager * _ sharedManger;@interface XKTelManager () @ property (nonatomic, strong) CTCallCenter * callCenter;@end@implementation XKTelManager+ (XKTelManager *) sharedManager {static dispatch_once_t onceTelSingle; dispatch_once (& onceTelSingle, ^ {if (! _ sharedManger) {_ sharedManger = [[XKTelManager alloc] init];}}); return _ sharedManger;}-(instancetype) init {self = [super init]; if (self) {_ inBackgroundRun = NO;} return self } # pragma mark-* related to phone monitoring-(void) startMonitor {_ weak typeof (self) weakSelf = self; _ callCenter = [[CTCallCenter alloc] init]; _ callCenter.callEventHandler = ^ (CTCall * call) {/ if you have entered the background, do nothing if (weakSelf.inBackgroundRun) {return } / / APP is not in the background if ([call.callState isEqualToString:CTCallStateDisconnected]) {NSLog (@ "phone-disconnected"); [[XKBGRunManager sharedManager] stopBGRun];} else if ([call.callState isEqualToString:CTCallStateConnected]) {NSLog (@ "phone-connected");} else if ([call.callState isEqualToString:CTCallStateIncoming]) {NSLog (@ "phone-to be connected"); [[XKBGRunManager sharedManager] startBGRun] } else if ([call.callState isEqualToString:CTCallStateDialing]) {NSLog (@ "phone-dialing"); [[XKBGRunManager sharedManager] startBGRun];} else {NSLog (@ "phone-No operation");}};} @ end

XKBGRunManager.h

# import @ interface XKBGRunManager: NSObject+ (XKBGRunManager *) sharedManager;/** enables background operation * /-(void) startBGRun;/** closes background operation * /-(void) stopBGRun;@end

XKBGRunManager.m

# import "XKBGRunManager.h" / cycle time static NSInteger _ circulaDuration = 60 is static XKBGRunManager * _ sharedManger;@interface XKBGRunManager () @ property (nonatomic,assign) UIBackgroundTaskIdentifier task;/// background playback @ property (nonatomic,strong) AVAudioPlayer * playerBack;@property (nonatomic,strong) NSTimer * timerAD;/// is used to print the test @ property (nonatomic,strong) NSTimer * timerLog;@property (nonatomic,assign) NSInteger count;@end@implementation XKBGRunManager {CFRunLoopRef _ runloopRef; dispatch_queue_t _ queue } + (XKBGRunManager *) sharedManager {static dispatch_once_t onceRunSingle; dispatch_once (& onceRunSingle, ^ {if (! _ sharedManger) {_ sharedManger = [[XKBGRunManager alloc] init];}}); return _ sharedManger;} / / override the init method to initialize the music file-(instancetype) init {if (self = [super init]) {[self setupAudioSession]; _ queue = dispatch_queue_create ("com.audio.inBackground", NULL) / / mute file NSString * filePath = [[NSBundle mainBundle] pathForResource:@ "*" ofType:@ "mp3"]; NSURL * fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; self.playerBack = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; [self.playerBack prepareToPlay]; / / 0.01mm 1.0, default is 1.0 self.playerBack.volume = 0.01; / / Loop self.playerBack.numberOfLoops =-1;} return self }-(void) setupAudioSession {/ / New AudioSession session AVAudioSession * audioSession = [AVAudioSession sharedInstance]; / / set background playback NSError * error = nil; [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error]; if (error) {NSLog (@ "Error setCategory AVAudioSession:% @", error);} NSLog (@ "% d", audioSession.isOtherAudioPlaying); NSError * activeSetError = nil / / start AudioSession. If a foreground app is playing audio, it may fail [audioSession setActive:YES error:&activeSetError]; if (activeSetError) {NSLog (@ "Error activating AVAudioSession:% @", activeSetError);}} / * * start background running * /-(void) startBGRun {[self.playerBack play]; [self applyforBackgroundTask] / ensure that both timers dispatch_async (_ queue, ^ {self.timerLog = [[NSTimer alloc] initWithFireDate: [NSDate date] interval:1 target:self selector:@selector (log) userInfo:nil repeats:YES]; self.timerAD = [[NSTimer alloc] initWithFireDate: [NSDate date] interval:_circulaDuration target:self selector:@selector (startAudioPlay) userInfo:nil repeats:YES]; _ runloopRef = CFRunLoopGetCurrent (); [[NSRunLoop currentRunLoop] addTimer:self.timerAD forMode:NSDefaultRunLoopMode] [[NSRunLoop currentRunLoop] addTimer:self.timerLog forMode:NSDefaultRunLoopMode]; CFRunLoopRun ();});} / * * apply for backend * /-(void) applyforBackgroundTask {_ task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: ^ {dispatch_async (dispatch_get_main_queue (), ^ {[UIApplication sharedApplication] endBackgroundTask:_task]; _ task = UIBackgroundTaskInvalid;});}];} / * print * /-(void) log {_ count = _ count + 1 NSLog (@ "_ count =% ld", _ count)} / * * detect background running time * /-(void) startAudioPlay {_ count = 0; dispatch_async (dispatch_get_main_queue (), ^ {if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {NSLog (@ "the backstage is about to be killed"); [self.playerBack play]; [self applyforBackgroundTask];} else {NSLog (@ "the background continues to be active") } / / execute the player stop again, and the music file will not be played in the background all the time [self.playerBack stop];} / * * stop running in the background * /-(void) stopBGRun {if (self.timerAD) {CFRunLoopStop (_ runloopRef); [self.timerLog invalidate]; self.timerLog = nil; / / turn off the timer [self.timerAD invalidate]; self.timerAD = nil; [self.playerBack stop] } if (_ task) {[[UIApplication sharedApplication] endBackgroundTask:_task]; _ task = UIBackgroundTaskInvalid;}} @ end

Finally, in the corresponding method of AppDelegate.m, you can turn on and stop background running.

Thank you for reading this article carefully. I hope the article "how to run iOS for a long time in the background" shared by the editor will be helpful to everyone. At the same time, I also hope you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report