如何在iOS应用程序处于前台时在后台运行操作

use*_*286 11 synchronization ios swift background-fetch

我在Documents Directory中填充了字符串数据的JSON文件.在应用程序的用户界面中有一个UIButton.按下按钮,新的字符串将附加到JSON文件中.

现在我正在寻找任何帮助我使用swift将这些字符串(从JSON文件)发送到服务器的iOS服务.这项服务应完全独立于我的代码.关键是当我按下UIButton时,第一步是将字符串保存到JSON文件,然后服务应该使用此字符串并在Internet可用时将其发送到服务器.

成功发送字符串后,应将其从JSON文件中删除.如果有任何字符串保存到JSON文件中,则此服务应每30秒跟踪一次,然后将其发送到服务器.

我用Google搜索并找到后台获取,但它会performFetchWithCompletionHandler自动触发功能,我无法知道iOS何时触发它.我想每30秒就触发一次这种服务.

JAL*_*JAL 11

查看Apple的iOS App程序指南的后台执行部分.

UIApplication提供了一个用于启动和结束后台任务的界面UIBackgroundTaskIdentifier.

在您的顶层AppDelegate,创建一个类级别的任务标识符:

var backgroundTask = UIBackgroundTaskInvalid
Run Code Online (Sandbox Code Playgroud)

现在,使用您希望完成的操作创建任务,并实现任务在过期之前未完成的错误情况:

backgroundTask = application.beginBackgroundTaskWithName("MyBackgroundTask") {
    // This expirationHandler is called when your task expired
    // Cleanup the task here, remove objects from memory, etc

    application.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
}

// Implement the operation of your task as background task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Begin your upload and clean up JSON
    // NSURLSession, AlamoFire, etc

    // On completion, end your task
    application.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
}
Run Code Online (Sandbox Code Playgroud)