我们项目要求我们是每隔一个小时上传一次地理位置,试了好几种方法都不成功,只能选择后台循环播放音乐达到后台持续运行.(我是企业账号开发的,不清楚App Store上传上去会不会有问题)
1.首先用到音频,需要 import MediaPlayer
2. 音频播放代码
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
let path = NSBundle.mainBundle().pathForResource("voice", ofType: "wav") //音频文件
let pathURL=NSURL(fileURLWithPath: path!)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: pathURL)
audioPlayer?.prepareToPlay()
audioPlayer?.numberOfLoops = -1 //循环
audioPlayer?.volume = 0.0//无声
audioPlayer?.play()
//UIApplication.sharedApplication().beginReceivingRemoteControlEvents() 锁屏的时候显示用,这里不用显示
} catch {
audioPlayer = nil
}
//来电话等中断音频播放时的处理
NSNotificationCenter.defaultCenter().addObserver(self, selector:
#selector(ViewController.breakAudioSessionEvent(_:)),name: AVAudioSessionInterruptionNotification, object: nil)
3.音频中断处理方法
func breakAudioSessionEvent(sender:NSNotification){
//音乐被中断,重新播放
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
NSBundle.mainBundle().pathForResource("voice", ofType: "wav")!))
audioPlayer?.prepareToPlay()
audioPlayer?.numberOfLoops = -1 //循环
audioPlayer?.volume = 0.0//无声
audioPlayer?.play()
} catch {
audioPlayer = nil
print(error)
}
}
4.这样测试下来,几个小时还继续后台运行,位置也一直上传着