ios - 如何编写用户按下主页按钮时不会暂停的代码

标签 ios swift

我想在我的 iOS 应用程序中实现图像同步。为此,我所做的是

  1. 拍照
  2. 将该照片上传到 firebase
  3. 获取 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.

链接:https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

以下是实现方法(摘自 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/

相关文章:

ios - SpriteKit - 从右到左将节点缩放到 X

swift - 如何立即触发 Timer.publish()?

ios - 更改 UILabel 文本仅适用于 viewDidLoad()

ios - 为什么纹理数据无法显示?

ios - Swift:iOS - 通过第三类将数据从 ViewController 传递到 xib 文件

swift - 字符串比较期间 SwiftyJSON 崩溃 : swift_unknownRetain

ios - UITableViewCell 中 UIImageView 上的 UISwipeGesture

ios - 当我点击 MapKit 中的图钉时如何执行操作? ios9, swift 2

objective-c - 使用 like 选择查询以避免使用 fmdb 时的 SQL 注入(inject)

iphone - initWithTitle 导致执行不完整