我想在我的 iOS 应用程序中实现图像同步。为此,我所做的是
- 拍照
- 将该照片上传到 firebase
- 获取 firebase 存储的 url 并将其发送到 api 服务器,以便服务器将该信息存储到数据库
只要应用程序正在运行,它就可以正常工作,但是当我退出应用程序并按下主页按钮时,一切都会暂停。
那么,如果应用程序转到主页,如何运行不会暂停的代码?
最佳答案
根据本文档,
For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:
- >
Apps that play audible content to the user while in the background, such as a music player app
- >
Apps that record audio content while in the background Apps that keep users informed of their location at all times, such as a navigation app
- >
Apps that support Voice over Internet Protocol (VoIP) Apps that need to download and process new content regularly
- >
Apps that receive regular updates from external accessories
- >
Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services
Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.
以下是实现方法(摘自 this answer by 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) }
关于ios - 如何编写用户按下主页按钮时不会暂停的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660819/