我有一个应用程序,我必须将一组数据发送到服务器。我可以使用 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)
}
}
这种方法的问题是,只有当应用程序在后台运行时,此方法才会在某个时间间隔内被触发,但如果应用程序在前台使用这种方法,我就无法发送内容。解决问题的正确方法是什么?
最佳答案
针对您的问题:当您的应用处于前台时触发上传。
我怀疑你的解决方案仅在网络可用时才向服务器发送数据是否良好。如果您的应用程序处于前台期间网络始终可用,您将没有机会发送数据。所以我认为你应该改变你的上传策略,比如在你的应用程序激活时设置一个计时器及其触发时间间隔,当你的应用程序进入后台时使计时器无效。
我怀疑自己没有正确理解你的问题,如果你只想在网络从WWAN变为WiFi时向服务器发送数据,你可以使用AFNetworking的AFNetworkReachabilityManager ,只需将.h和.m文件复制到您的项目中即可。
关于ios - 只要网络可用就发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586130/