iOS让你的app一直在后台活着(运行)

准备工作:

1.导入AVFoundation.framework

2.导入一个无声音乐文件 (.mp3)

3.在info.plist里面请求后台播放音乐的权限

4.上代码

[objc] view plain copy
  1. #import "AppDelegate.h"  
  2. #import <AVFoundation/AVFoundation.h>  
  3.   
  4.   
  5. @interface AppDelegate ()  
  6. @property (strong, nonatomic) NSString *startTime;  
  7.   
  8. @end  
  9.   
  10. @implementation AppDelegate  
  11.   
  12.   
  13. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  14.     // Override point for customization after application launch.  
  15.       
  16.     AVAudioSession *session = [AVAudioSession sharedInstance];  
  17.     [session setActive:YES error:nil];  
  18.     [session setCategory:AVAudioSessionCategoryPlayback error:nil];  
  19.     //让 app 支持接受远程控制事件  
  20.     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  
  21.       
  22.     //播放背景音乐  
  23.     NSString *musicPath=[[NSBundle mainBundle] pathForResource:@"wusheng" ofType:@"mp3"];  
  24.     NSURL *url=[[NSURL alloc]initFileURLWithPath:musicPath];  
  25.       
  26.     //创建播放器  
  27.     AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];  
  28.       
  29.     [audioPlayer prepareToPlay];  
  30.       
  31.     //无限循环播放  
  32.     audioPlayer.numberOfLoops=-1;  
  33.     [audioPlayer play];  
  34.       
  35.     [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(printCurrentTime:) userInfo:nil repeats:YES];  
  36.       
  37.     return YES;  
  38. }  
  39.   
  40.   
  41.   
  42. -(void)printCurrentTime:(id)sender{  
  43.     NSLog(@"当前的时间是---%@---",[self getCurrentTime]);  
  44. }  
  45. -(NSString *)getCurrentTime{  
  46.     NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];  
  47.     [dateFormatter setDateFormat:@"yyyy-MM-DD HH:mm:ss"];  
  48.     NSString *dateTime=[dateFormatter stringFromDate:[NSDate date]];  
  49.     self.startTime=dateTime;  
  50.     return self.startTime;  
  51. }  
  52.   
  53.   
  54.   
  55.   
  56. - (void)applicationWillResignActive:(UIApplication *)application {  
  57.     // 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.  
  58.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  59. }  
  60.   
  61. - (void)applicationDidEnterBackground:(UIApplication *)application {  
  62.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
  63.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  64. }  
  65.   
  66. - (void)applicationWillEnterForeground:(UIApplication *)application {  
  67.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  68. }  
  69.   
  70. - (void)applicationDidBecomeActive:(UIApplication *)application {  
  71.     // 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.  
  72. }  
  73.   
  74. - (void)applicationWillTerminate:(UIApplication *)application {  
  75.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  76. }  
  77.   
  78. @end  

只要不占用太多内存,活着用户手动的kill程序,看打印的log知道这个app可以长时间的在后台运行

原文地址:https://www.cnblogs.com/xiao-love-meng/p/5821153.html