In my iOS application i want to make an api call for every 4 hours.
As of my research i found that it can be achieved by background task or Local notification or Push Notification.
As of my knowledge, By Notifications (Either Local or Push both) user have to interact with application.
I want to make an api call without user interaction, even app is in background or foreground or active.
I didn't get exact sample code for background fetch which works with intervals.
Some one please guide me in this issue.
Thank you in Advance.
You can set the interval here or specified a minimum fetch interval (The smallest fetch interval supported by the system) like this example:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
return YES;
}
For 4 hours:
NSTimeInterval fourHours = 14400;
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:fourHours];
Related
I am developing an app which only works in 8.30am to 5.30pm. I want to store the data only in between 8.30am to 5.30 pm. I used local notification for doing so. But it only works when user tap the notification.In 8.30am and 5.30pm, i need to execute some code even if the app is killed. Is there any other mechanism to do so...?
Here is my code:
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification!=nil)
{
[self application:application didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
code to be executed;
}
There is no way to execute a method in your app if the app is killed. You can bring the app up in the background using silent notifications. But silent notifications are better suited for News apps or apps which need to download content in the background so it is readily available for users when the app comes to the foreground.
Apart from this, the only way to execute the method is when it is either in the foreground or at least active in the background (using one of the available background modes). If your app is using a background mode only to stay in the background, Apple will reject the app, so be careful.
In birthday app which is the best place to check birthdates and set its UILocalNotification in iOS.
Iss didfinishlaunching the best place? or any other.
That is a good place to schedule the notification if you need to check it only once.
If data changes often I suggest you put it in applicationDidBecomeActive: since iOS might not remove the app from memory each time.
You also need to make sure that you schedule only one notification, and not each time the application is started.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(#"Notification fired"!);
}
if your in foregroud it will call this method. then you can use this method also.
I'm developing a Calendar/Alarm app for iOS which is synchronising with a web server. When an activity is added on the server, a push notification is sent out so that the iOS client can fetch the new data and, if needed, update and schedule the time for next alarm (local notification).
But this only works when the app is open on client side. I would like the client to receive the push notifications and if needed, re-schedule the time for next alarm in background.
Is this impossible on iOS?
You can use Background Fetch for this, where the OS will "wake up" your app periodically to perform data fetching in the background.
First, enable the background fetch capability for your app. In XCode 6, view your project, then go to the Capabilities tab, turn on Background Modes, and check Background Fetch.
Then you'll have to implement some codes in the App Delegate:
In application:didFinishLaunchingWithOptions:, add:
[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
The above sets how often you wish the system to "wake up" your app for background processes ideally. Note that the final frequency is determined by an algorithm in the iOS, so it may not always be this often.
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
//fetch code here
completionHandler(UIBackgroundFetchResultNewData);
}
The above is the actual overridden function that is called during this period of background process. Remember to call the completionHandler - failing to do so might reduce the chance of your app being run in the background next time (or so says the docs). The enums you may pass to the completionHandler are UIBackgroundFetchResultNewData, UIBackgroundFetchResultNoData, UIBackgroundFetchResultFailed. Use one of these depending on the result of your fetch.
// use this methods in Appdeleagte
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[self showAlarm:notification.alertBody];
application.applicationIconBadgeNumber = 1;
application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}
// call this in appdelagete
-(void)makeNotificationRequest:(UILocalNotification *)notification1
{
[self showAlarm:notification1.alertBody];
}
// call this mathods in appdelagte
- (void)showAlarm:(NSString *)text {
**strong text**
// set notification and call this notification methods your another view .....
[[NSNotificationCenter defaultCenter] postNotificationName:#"uniqueNotificationName" object:self]; //leak
}
Title says it all.
I've looked at this question and also here on the pubnub forums (same question, just different suggestion).
The core of the issue is that as soon as the application suspends, pubnub connectivity is queued and not sent until the app goes back to foreground. It seems to be a reasonable thing to do to send a notification saying that you're going in the background on your channel but it doesn't work.
From my readings I understand that pubnub uses websockets and that it is not allowed in background mode. Even tried to enable VOIP as a background mode with no luck but Location updates bg mode works. However, using this will have my app rejected as I don't use location services.
When running this code
- (void)applicationDidEnterBackground:(UIApplication *)application {
[PubNub sendMessage:#"Hello from PubNub iOS!" toChannel:self.myChannel;
}
I get this log entry from pubnub (so at least I know the command is ran):
Looks like the client suspended"; Fix suggestion="Make sure that your application is configured to run persistently in background
I have been killing myself over this for a day. One of these days where you start doing something that you think is pretty simple, a 15min thing and it turns into a day of frustration ... You know what I mean :)
I was actually able to send the messages I needed when the app was about to enter Background. And without enabling any of the background modes.
I took advantage of the background finite task as explained is this tutorial.
- (void)applicationWillResignActive:(UIApplication *)application {
[PubNub updateClientState:#"MyID" state:#{#"appState":#"Background",#"userNickname":#"MyNickname"} forObject:[PNChannel channelWithName:#"MyChannel"]];
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(#"Background handler called. Not running background tasks anymore.");
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}];
}
And implementing the stop background when coming back online
- (void)applicationDidBecomeActive:(UIApplication *)application {
if (self.backgroundTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
NSLog(#"Task invalidated");
}
}
I'm using a Beacon device for testing. The scenario is as follows.
I'm throwing a local notifications when receiver enters the location which is based on latitude & longitude range which i have set manually. This works fine and i'm clearing this notification on didFinishLaunchingWithOptions. When I enter to the next closest region i'm getting the notification and on clicking it I can able to present a view. But when i come out of the app the local notifications are not getting cleared. What may be the problem?
I'm using two different methods for two different regions.
1st one is
-(void) didEnterLocation:(SLMLocation*)location
{
// throwing a local notification
}
the above method's notification is getting cleared in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
the second method is as follows: this is for 2nd region
- (void) didEnterNewClosestRegion :(SLMBLERegion*) region
{
// throwing local notifications here & notifications are visible
}
Now in the second method only I can't able to clear the local notification. Your help is highly appreciated.
try this may be help full ..
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
Thanks
This is because didFinishLaunchingWithOptions method is only called one in app life time, there is a possibility that it is already running in background so the notifications will not be cleared. I would suggest you to move cancelling code to applicationDidBecomeActive.
cancelAllLocalNotifications, cancels the delivery of all scheduled local notifications, it doesn't clear already presented notifications from lock-screen or notification-center.
https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/cancelAllLocalNotifications