iOS后台正常运行


前言

实现app进入后台仍然可以正常运行

一、配置工程

一、在工程TARGETS中的“Signing & Capabilities”,点击左上角“+Capability”按钮添加“Background Modes”,勾选中选项"Audio, AirPlay, and Picture in Picture"。
二、将附带的空白mp3资源文件拷贝到工程。

二、代码

AppDelegate.swift

//

import UIKit
import AVFoundation

extension AppDelegate: UIApplicationDelegate {
    
    ///进入后台
    func applicationDidEnterBackground(_ application: UIApplication) {
    	guard needToBackground else {
    		return
    	}
        taskId = UIApplication.shared.beginBackgroundTask() {[weak self] in
            guard let WEAKSELF = self, let k = WEAKSELF.taskId else {
                return
            }
            application.endBackgroundTask(k)
            WEAKSELF.taskId = UIBackgroundTaskInvalid
        }
        
        customBeginRunInBackground()
    }
    
    ///进入前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        //
        guard needToBackground else {
    		return
    	}
        audioActive(active: true)
        customEndRunInBackground()
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // 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.
    }


    func applicationDidBecomeActive(_ application: UIApplication) {
        // 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.
    }

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


@UIApplicationMain
class AppDelegate: UIResponder {

    var window: UIWindow?
    

    private var taskId: UIBackgroundTaskIdentifier?
    private var audioPlayer: AVAudioPlayer?
	
	var needToBackground = true


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        application.isIdleTimerDisabled = true
        UIApplication.shared.beginReceivingRemoteControlEvents()
        return true
    }
   
    private func customBeginRunInBackground() {
        let session = AVAudioSession.sharedInstance()
        
        do {
            try session.setActive(true)
            try session.setCategory(AVAudioSessionCategoryPlayback)
            
            
            guard let url = Bundle.main.url(forResource: "mysong", withExtension: "mp3") else {
                return
            }
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.prepareToPlay()
            //无限循环播放
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.play()
            
        }
        catch {
            
        }
        
    }
    
    private func customEndRunInBackground() {
        UIApplication.shared.endReceivingRemoteControlEvents()
        
        audioPlayer?.stop()
        audioPlayer = nil
    }
    
    private func audioActive(active: Bool) {
        do {
            try AVAudioSession.sharedInstance().setActive(active)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord)
            
        } catch {
            GLog(message: "audio异常: \(error)")
        }
        
    }
}

总结

可以在后台播放一个空白的mp3资源文件进行保活。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值