How to fetch data in background every hour in Swift even the app is terminated?
Asked Answered
G

6

8

I am making an app that provides functionality to fetch data every hour. It fetches data even when the app terminates. How can I implement this functionality?

After a lot searching I found background fetching using performFetchWithCompletionHandler. Will this function work even if my app terminates? What I mean is if my app is in closed or terminated state, can I call this function automatically?

Girosol answered 19/5, 2016 at 9:28 Comment(6)
Not Possible for infinite time!!Georgenegeorges
but backgrount fetch will work if my app is terminated?@GeorgenegeorgesGirosol
You can fetch data once only when application state is being changed to background but not for forever.Georgenegeorges
@DearDownvoter: Question is not entitled for downvote. Question is correct and follows the SO FAQ. So before down voting give a reason in comment.Georgenegeorges
Thanks @Georgenegeorges got it. can you please tell me that how much maximum time app stay in background?Girosol
I want the same thing in my project know, I want to call an API every 5 minutes in background and if the result which API send me back is what I want, show a notification to user and stop calling API anymore. which way did you resolve this issue?Derk
M
11

You can't do anything if your app is in terminated state. Apple is not allowing anything (except receiving notification) in terminated or closed state.

You are also restricted for background execution also. You can perform specific kind of task in background mode like : Location update,Music playing, VOIP, finite length task, Newsstand downloads, etc. You can refer apple documentation for more details about background execution.

Hope this will help :)

Manthei answered 19/5, 2016 at 9:35 Comment(1)
"except for receiving notification" <-- I think this is incorrect. You can do all of the actions which launch your app in the background.Cowbane
F
1

Once I needed this same when I was working on some project, unfortunately I didn't find any solution for it.

You can run a task when your app is in Background state(that too with limited services) but apple doesn't allow to run a task when app is Terminated

Please go through the link.

https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

and this is for background running. Sending Latitude and Longitude to Server when app is in background

Floria answered 19/5, 2016 at 11:7 Comment(0)
O
1

Your app is terminated once it will not do any kind of task related to it. Apple Doesn't support it. You can not call Functions when your app is not running. So it's not possible Due to apple rules. performFetchWithCompletionHandler is only work when your app is running if your application is terminated it will not perform any kind of task.

Olag answered 19/5, 2016 at 12:45 Comment(0)
A
0

From what i have experienced:

First of all the timer will stop when the app goes to the background to stop fast battery drainage and expand the lifetime of the battery even to save network bundles quota consumption while you are not actively using the app.

You can do background fetch tasks by adding the following in the AppDelagate "as you mentioned":

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

    //Do whatever you need
    //This will keep running for max 3 mins
}

But the same is for background fetch tasks. You have got maximum 3 min of background activity except for Locations services, Audio playing, VOIP and some other tasks.

I really don't know the use and the functionality of the app and why do you need to grab data from the server every 1hr if the app is already closed and the user is not concerned about seeing the updated data.

But if this data is important to be updated every hour and need to notify the user with the updates "for instance checking the status of a certain event on the server, like making a chat app and the user received a message". Then it is better to send a remote push notification to the user from the server upon a certain event taking place and this will make the user get the app again on the foreground and the app will start fetching the updated data "in my case here the message".

Aquatint answered 12/5, 2017 at 13:5 Comment(0)
D
0

you can find location in app terminated state, after significantly change in location like about 500 meter. here is working example

http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended

but what I am stuck at is post location through webservice.

Dato answered 26/8, 2017 at 11:24 Comment(0)
N
-3

@Jack.Right you can call the method after every 1 hour so use NSTimeinterval it would be helpful!!

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication *app = [UIApplication sharedApplication];

    //create new uiBackgroundTask
    __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    //and create new timer with async call: 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //run function methodRunAfterBackground
        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(methodRunAfterBackground) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });
}
Newton answered 19/5, 2016 at 10:4 Comment(6)
but the thing is that where should i write my code so method get call after every one hour? NSTimeinterval will work if my app is terminated?Girosol
@Girosol if you want method call after terminating the app then Use siltent notification.Newton
Wrong Answer. NSTimer doesn't work in background mode.Georgenegeorges
@dear down voter i think you don't want to get the answer just you know how to down the vote.Newton
Use the ApplicationDelegate Lifecycle methods to drive it. application:didFinishLaunchingWithOptions: applicationDidBecomeActive: applicationWillResignActive: applicationDidEnterBackground: applicationWillEnterForeground: applicationWillTerminate: applicationDidFinishLaunching:Newton
@Sanjeetverma Not like that! Have you tried your code? It would work only once. Not in loop for forever. And if user terminate the app it would not work even once.Georgenegeorges

© 2022 - 2024 — McMap. All rights reserved.