如何在App Delegate的“ performFetchWithCompletionHandler”函数中从Alamofire获取数据?

时间:2018-12-07 20:06:24

标签: ios swift background alamofire

好的,所以我一直在努力寻找答案,但是当我通过Xcode模拟后台刷新时,我仍然无法让Alamofire发挥其魔力。

这就是我在应用程序委托中所说的功能

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

    let vc = ViewController()
    vc.fetchData()
    vc.sendNoti(currentFlightRules: currentFlightRules)
    completionHandler(.newData)
        print("Background Fetch Complete! UP")
}

fetchData()是通过Alamofire发出API请求的请求,它不会运行,而sendNoti()可以运行。我知道该实现正在运行,就像我模拟后台执行print语句执行时一样。

真的很感谢您的帮助,因为我不熟悉如何在后台执行任务,特别是在后台执行网络任务。预先感谢。

1 个答案:

答案 0 :(得分:0)

您的问题是fetchData将异步完成。这意味着sendNotificationcompletionHandler将在网络操作完成之前被调用。

您需要fetchData函数在有数据时接受并调用完成处理程序。然后,您调用通知方法,并从该闭包中获取后台completionHandler

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

    let vc = ViewController()
    vc.fetchData { (error, data) in 
        guard error == nil else {
            print("There was an error \(error!.localizedDescription)")
            completionHandler(.failed)
            return
        }

        if let newData = data {
            vc.sendNoti(currentFlightRules: newData)
            completionHandler(.newData)
        } else {
            completionHandler(.noData)
        }
    }
}

我还建议您进行重构,以使获取和通知操作不包含在视图控制器中。他们应该分成自己的班级。

相关问题