![](/img/trans.png)
[英]How can I make my Radio Streaming Application keep singing when the user press the home button?
[英]How to write code that will not pause when user press home button
我想在我的ios应用中实现图像同步。 为此,我所做的是
只要应用程序正在运行,它就可以正常工作,但是当我退出应用程序并按“主页”按钮时,所有内容都会暂停。
那么,如何运行在应用程序进入首页时不会暂停的代码?
根据本文档,
对于需要更多执行时间才能实现的任务,您必须请求特定的权限才能在后台运行它们而不暂停它们。 在iOS中,只允许特定的应用类型在后台运行:
在后台播放用户可听内容的应用程序,例如音乐播放器应用程序
在后台记录音频内容的应用程序,使用户始终了解其位置的应用程序,例如导航应用程序
支持互联网协议语音(VoIP)的应用程序需要定期下载和处理新内容的应用程序
从外部配件接收定期更新的应用
实现这些服务的应用必须声明它们支持的服务,并使用系统框架来实现这些服务的相关方面
声明服务可以使系统知道您使用的服务,但是在某些情况下,实际上是系统框架阻止了应用程序被挂起。
链接: https : //developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
这是实现方法(摘自Ashley Mills的 回答 ):
func doUpdate () { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let taskID = beginBackgroundUpdateTask() var response: NSURLResponse?, error: NSError?, request: NSURLRequest? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) // Do something with the result endBackgroundUpdateTask(taskID) }) } func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({}) } func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(taskID) }
[Swift3]这对我有用
func doUpdate () {
DispatchQueue.global(qos: .background).async {
let taskID = self.beginBackgroundUpdateTask()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: {
print("printing after 10 min")
})
DispatchQueue.main.async {
self.endBackgroundUpdateTask(taskID: taskID)
}
}
}
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
return UIApplication.shared.beginBackgroundTask(expirationHandler: {})
}
func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) {
UIApplication.shared.endBackgroundTask(taskID)
}
由于我看到有一个expirationHandler
,因此不确定完成此操作的最长时间是多少
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.