【问题标题】:Swift - post data in background once device is connected [closed]Swift - 连接设备后在后台发布数据[关闭]
【发布时间】:2021-03-26 06:39:37
【问题描述】:

我有一个应用程序,它要求用户将数据从表单发布到特定端点。我需要用户能够离线使用该应用程序。因此,他们的想法是他们可以像往常一样继续填写表格,然后一旦设备再次在线,数据就可以发布到相关端点。

我不确定如何在 iOS 中处理这个问题。如果可以在后台避免,我不想不断检查连接状态。有没有办法让任务排队等待连接建立?

【问题讨论】:

标签: ios swift push offline


【解决方案1】:

这是内置的,功能非常丰富。

Uploading Data to a WebsiteDownloading Files in the Background 了解详细信息。 (后台文档侧重于下载,但同样的方法适用于发送。)

使用URLSessionConfiguration.background(withIdentifier:) 创建后台会话。然后你可以用它和 URLSessionUploadTask 来发送你的数据。

如果您需要在任务完成时启动并通知您,请设置sessionSendsLaunchEvents(但听起来您可能不需要)。

使用委托进行回调。您不能为此配置使用完成处理程序。

例如,创建会话(基于文档):

private lazy var urlSession: URLSession = {
    let config = URLSessionConfiguration.background(withIdentifier: "MySession")
    return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()

如果您需要在完成后重新启动,您还需要配置您的应用委托以通过实现来处理这些启动事件:

func application(_ application: UIApplication,
                 handleEventsForBackgroundURLSession identifier: String,
                 completionHandler: @escaping () -> Void) 

(请务必在提交活动后致电completionHandler!)

有关更多详细信息,请参阅 WWDC 2020 的 Background execution demystified

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多