Long running background tasks in ios

时间:2017-08-04 12:15:28

标签: android ios iphone service

In my android app, I'm using a background service which every 2 minutes check in local database, if finds some unsynced data it tries to sync it to server. Now I want to implement the same in ios, so I want to know is there something in ios equivalent to android's service.

1 个答案:

答案 0 :(得分:1)

No, there is no iOS equivalent of Service. However, what you are trying to do can be achieved with Background Modes. To be specific, fetch background mode.

To enable Background Modes go to Project settings -> Capabilities -> Background Modes and enable Background fetch.

Then, is your UIApplicationDelegate implement function

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

// Objective-C
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

As per Background Modes documentation

When a good opportunity arises, the system wakes or launches your app into the background and calls the app delegate’s application:performFetchWithCompletionHandler: method. Use that method to check for new content and initiate a download operation if content is available. As soon as you finish downloading the new content, you must execute the provided completion handler block, passing a result that indicates whether content was available. Executing this block tells the system that it can move your app back to the suspended state and evaluate its power usage. Apps that download small amounts of content quickly, and accurately reflect when they had content available to download, are more likely to receive execution time in the future than apps that take a long time to download their content or that claim content was available but then do not download anything.

Using background modes, your app will be woken up or launched to perform tasks, even if it was killed or device was rebooted - with the exception of user force-quitting the app.

相关问题