2017-08-03 46 views
0

我想時間。但一些間隔時,應用程序在後臺或無效狀態這不應該occour期間執行一些動作。 我已經實現這個如下只有當應用程序處於活動狀態時,如何在performFetchWithCompletionHandler中執行代碼?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 


UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) 
    return true 
} 

而在performFetchWithCompletionHandler

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

    print("Background fetch called") 



     // foreground 

    if (application.applicationState == .active) 
    { 

     //lines of code to perform 



} 
} 

但是,當我試圖模擬背景在模擬器取,它顯示以下消息

警告:接收應用程序代理調用-application:performFetchWithCompletionHandler:但完成處理程序從未被調用。

我試着刪除應用程序狀態條件,它是工作fine.But我想執行這些線路只有當應用程序被激活,而不是在後臺或不活動state.How我能做到這一點?

回答

1

你忘了完成處理程序添加到函數。應在數據獲取完成時調用它。

插入這對你的代碼,如果你有新的數據顯示:

completionHandler(.newData) 

...這個,如果你沒有數據:

completionHandler(.noData) 

...這如果下載失敗:

completionHandler(.failed) 
相關問題