This question already has an answer here:
iOS Multi-Tasking Track GPS Location
(1 answer)
Closed 9 years ago.
I read some questions about app run in background and I know that there could b some possibilities to do so, like run an app monitoring the GPS data. I want to confirm is it possible to make a program like that non-stop at background and whenever GPS changes it start some other modules run for a while. After that this program still running in background ?
I hear some thing about : Adobe Air on mobile and run apps more than 10 mins. So can anyone confirm is it possible to do above requirement in normal iOS ? Thank you !
Use this code to run in background in app delegate class
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
To get gps data call gps location manager inside the above method
eg:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
locationmanager = [[CLLocationManager alloc]init];
[locationmanager setDelegate:self];
locationmanager.distanceFilter = kCLDistanceFilterNone;
[locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[locationmanager startUpdatingLocation];
UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
latitude = [[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.latitude];
longitude = [[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.longitude];
}
Related
Hello everyone I am trying to get a location update when my app is in background. But the code below does not seems to work. The IF statement is never true. I have also set the necessary keys in the info.plist files. I am running the code in iphone 3GS and ipad 3.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customizatio-n after application launch.
id locationValue = [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey];
if (locationValue)
{
// create a new manager and start checking for sig changes
locManager = [[CLLocationManager alloc] init];
locManager.delegate = self;
[locManager startMonitoringSignificantLocationChanges];
return YES;
}
I am sending a local notification once a process is finished and it acts just fine.
This is my code for didReceiveLocalNotification:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
CounterViewController *counterVC = [CounterViewController sharedInstance];
[counterVC notificationArrived];
}
But when the iPhone is locked those lines aren't called… What can I do to make them run in the background?
There are two method to receive local notification one is already you have implemented which is invoked while app is running & 2nd is in didFinishLaunchingWithOptions which is invoked while your app is running background you have add some code for receive local notification .....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(#"Recieved Notification %#",localNotif);
}
return YES;
}
I am making an application in which i want features like as when i run my app on device then it will closed immediately without showing any screen.But Application works in background. When user click on icon of application then it will not show any screen but work in background. After 2 minutes gap it will show a alert message. How do that?
I have used code for this given below:-
-(void)applicationDidFinishLaunching:(UIApplication *)application{
[application cancelAllLocalNotifications];
[self applicationWillTerminate:application];}-(void)applicationWillTerminate:(UIApplication *)application{
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/
UILocalNotification* ln = [[UILocalNotification alloc] init];
ln.fireDate =[NSDate dateWithTimeIntervalSinceNow:30];
ln.alertBody = [NSString stringWithFormat:#"Now app is working in Background."];
ln.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:ln];
ln.hasAction=NO;
[ln release];
exit(0);}
But this is not working as i want. So what is bug in this code? How do that?
Thanks in advance...
You can't put your app away by manually calling [self applicationWillTerminate:application];. It's a delegate method that gets called when your application is about to be terminated, not a method to terminate the app.
You could try to schedule a local notification in didFinishLaunchingWithOptions: and call exit(0); afterwards. Some kind of splah screen (or black screen) will probably be shown for a moment.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
[application cancelAllLocalNotifications];
UILocalNotification* ln = [[UILocalNotification alloc] init];
ln.fireDate =[NSDate dateWithTimeIntervalSinceNow:30];
ln.alertBody = [NSString stringWithFormat:#"Now app is working in Background."];
ln.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:ln];
ln.hasAction=NO;
[ln release];
exit(0); //this line kills the app (and gets your app rejected)
return NO; //this line is just to make compiler happy
}
Please note that this will most definetly not be approved for App Store.
In my iPhone Timer Application,
In which a timer should run in background.
So,
I have set the notification in appdelegate it works perfectly...
With that I am calling the methods from view controller which makes timer alive.
Take a look some code...
App delegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
NSLog(#"Time Remaining %d",(self.viewController.totalSeconds-self.viewController.totalCount));
[self.viewController selectandnotify:(self.viewController.totalSeconds-self.viewController.totalCount)];
[self.viewController stopTimer];
[self.viewController startTimerAction];
}
Here I am calling the method startTimerAction method which is in my view controller...take a look at this...
-(void)startTimerAction
{
timer_main = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:#selector(ShowActicity) userInfo:nil repeats:YES];
}
Which is NSTimer
Here every time
-ShowActivity method will call after each second...Which is below in my view controller...
-(void)ShowActicity
{
NSLog(#"Total Counts %d",totalCount);
if (totalCount == totalSeconds) {
if ([timer_main isValid]) {
[timer_main invalidate];
isTimeOver = YES;
[self generateLog];
}
} else {
totalCount++;
seconds =seconds + 1;
if(seconds > 59)
{
minutes = minutes + 1;
seconds= 0;
}
}
How to call each time This method from view controller.....
How can I call each time showActivity method from appdelegate...
Should I use delegate for that
Should I create showActivity and timer in my Appdelegate..
Actually I want this application to run when view switches in app.....
I think If I make delegate is a good option?
Any other way....please have some suggestions
Generally use this code for background running .In the Background timer doesn't work
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
[self startTimerAction];
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3
Well the title is self explained. I want to create an App that can manage programmed local notifications when App is in background mode. Notifications works smoothly but I want to fire a custom method when the alert is fired.
Is it possible?
Thank you.
Yes it can be done. You can do somethng like this:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[NSTimer scheduledTimerWithTimeInterval:17.0 target:self selector:#selector(makeNotificationRequest:) userInfo:nil repeats:YES];
}
-(void)makeNotificationRequest:(NSTimer *)timer
{
CLLocation *location = [[AppHelper appDelegate] mLatestLocation];
NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
#ifdef _DEBUG
[paramDic setValue:[NSString stringWithFormat:#"77.586"] forKey:#"Lat"];
[paramDic setValue:[NSString stringWithFormat:#"12.994"] forKey:#"long"];
#else
[paramDic setValue:[NSString stringWithFormat:#"%f",location.coordinate.latitude] forKey:#"Lat"];
[paramDic setValue:[NSString stringWithFormat:#"%f",location.coordinate.longitude] forKey:#"long"];
#endif
WNetwork *mNetwork = [[WNetwork alloc] init];
[mNetwork makeRequsetWithURL:URL_Showbeeps type:JBJsonParser paramDictionary:paramDic delegate:self];
[mNetwork autorelease];
NSLog(#"URL HIT%#",paramDic);
[paramDic autorelease];
}
And to customize your action on alert you can use this:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
;
}
}
If the app were in the foreground then you would want the - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification method of UIApplicationDelegate, however the documentation suggests that this will not be called when the app is in the background.
You can get a list of local notifications by calling scheduledLocalNotifications on your UIApplication instance - you can then poll these for their times and schedule a function to call at that time in your background mode. This won't necessarily 100% match up with when the Local Notification fires though, but I think it's as close as the App Store guidelines will let you get.
You can also present your own Local Notifications when you are in background mode by calling the presentLocalNotificationNow: method:
https://developer.apple.com/library/IOS/#documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/presentLocalNotificationNow:
so you could work around this by just presenting your own notifications and not scheduling them for the OS to deliver.
If you are trying to access Local Notifications from other applications then I don't think this is allowed.
No ..no custom methods are defined while app is running in background..Once an notification is fired we can;t change the alert message also. But nice when we show the alert message then by clicking the yes button to the alert take you to the one method called app is Running in Background which is in AppDelegate.m file