【问题标题】:Send data created while the user offline发送用户离线时创建的数据
【发布时间】:2020-04-04 13:04:19
【问题描述】:

我想允许用户在离线时创建一些项目。然后当用户重新连接到互联网时将创建的项目发送到后端。
我很困惑,实现这一目标的正确方法是什么?

  • 我是否应该使用 URLSession 的waitsforconnectivity,即使用户关闭应用程序也会发送请求
  • 或者我应该安排一个后台任务?如果是这样,那么当用户连接到互联网时如何触发此任务?

注意:我使用Alamofire 进行网络

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    我认为你过于复杂了。

    如果您将 Alamofire 用于网络,那么我不建议您使用第一种方法,因为这会混合使用 URLSession 和 Alamofire 来进行网络,这不是一个好主意。

    就您的第二种方法而言。为什么它需要成为后台任务?为什么你不能检查用户是否首先连接到互联网,如果他们是你可以正常进行的。如果没有,那么只需创建项目并以某种方式缓存它们。然后当你重新连接到互联网时,你可以像发送普通项目一样先发送缓存的项目。

    Alamofire 有一个内置的NetworkReachabilityManager,它可以帮助您确定您的网络状态。 this answer 中有一个很好的例子来使用它。

    【讨论】:

    • 感谢重播,我正在尝试安全地将创建的数据发送到服务器。我不想等待用户打开应用来发送这些请求。
    【解决方案2】:

    您可以使用 Alomafire 本身执行此操作: 网络管理器

    class NetworkManager {
    
    //shared instance
    static let shared = NetworkManager()
    
    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
    
    func startNetworkReachabilityObserver() {
    
        reachabilityManager?.listener = { status in
            switch status {
    
                case .notReachable:
                    print("The network is not reachable")
    
                case .unknown :
                    print("It is unknown whether the network is reachable")
    
                case .reachable(.ethernetOrWiFi):
                    print("The network is reachable over the WiFi connection")
    
                case .reachable(.wwan):
                    print("The network is reachable over the WWAN connection")
    
                }
            }
    
            // start listening
            reachabilityManager?.startListening()
       }
    }
    

    可达性观察者

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            // add network reachability observer on app start
            NetworkManager.shared.startNetworkReachabilityObserver()
    
            return true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2016-04-14
      • 1970-01-01
      • 2016-12-08
      • 2015-07-27
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多