【问题标题】:Sending data whenever network becomes available网络可用时发送数据
【发布时间】:2016-07-26 09:31:46
【问题描述】:

我有一个应用程序,我必须将一组数据发送到服务器。我可以使用 NSURLSession 或其他 API 来做到这一点。问题是我需要在网络可用时触发发送数据的代码。即使应用程序处于后台/暂停状态,此操作的触发也应该起作用。我分为使用 performFetchWithCompletionHandler 或 handleEventsForBackgroundURLSession。目前我使用的是前者。

func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        //do some check for loggedInStatus here

        if loggedInStatus {

            let navigationController = self.window?.rootViewController as! UINavigationController

            let myViewController = navigationController.viewControllers[0] as! MyViewController

            //checking network connection
            if NetworkReachability.connectedToNetwork() {

                myViewController.syncStuff({ (result: UIBackgroundFetchResult) in

                    completionHandler(result)
                })
            }

        }
    }

didFinishLaunchingWithOptions

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

//if user is logged in set a minimum time interval at which the app should be woken up to sync stuff
        if loggedInStatus {

            application.setMinimumBackgroundFetchInterval(5)
        }
        else {

            application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalNever)
        }
}

这种方法的问题是,只有当应用程序处于后台时,该方法才会在某个时间间隔内触发,但如果应用程序在前台使用这种方法,我无法发送内容。解决问题的正确方法是什么?

【问题讨论】:

    标签: ios swift nsurlsession nsoperation


    【解决方案1】:

    针对您的问题:当您的应用处于前台时触发上传。

    我怀疑您仅在网络可用时才将数据发送到服务器的解决方案是否良好。如果在您的应用程序处于前台期间网络始终可用,则您没有机会发送数据。所以我认为你应该改变你的上传策略,比如在你的应用激活时设置一个定时器和它的触发时间间隔,当你的应用进入后台时使定时器失效。

    我怀疑自己没有正确理解您的问题,如果您只想在网络从 WWAN 更改为 WiFi 时向服务器发送数据,您可以使用 AFNetworking 的AFNetworkReachabilityManager,只需将 .h 和 .m 文件复制到您的项目没问题。

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2012-02-03
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      相关资源
      最近更新 更多