【发布时间】: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