startMonitoringSignificantLocationChanges if can terminated my app - iphone

i am want to use startMonitoringSignificantLocationChanges in my app,but i have some question,i hope get some help:
for a common app if app enter background,after 10mins ,system can kill the app.if i used startMonitoringSignificantLocationChanges ,when i enter background two hours,my app not terminated,because i click the icon,app will enter the last quit page 。if app is killed,when you click the icon you will first see the default page. so my question is use startMonitoringSignificantLocationChanges my app not killed by system after enter background 10 mins?
if i close mobile,and restart the mobile,when significant location change,my app if can be activate ,i look apple develop document it answer yes.so i test:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if([CLLocationManager significantLocationChangeMonitoringAvailable]){
[self log:#"sigAvailable=YES"];
}
// 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
[self log:#"didFinishLaunchingWithOptions location key"];
m_locManager = [[CLLocationManager alloc] init];
[self log:#"didFinishLaunchingWithOptions created manager"];
m_locManager.delegate = self;
[self log:#"didFinishLaunchingWithOptions set delegate"];
[m_locManager startMonitoringSignificantLocationChanges];
[self log:#"didFinishLaunchingWithOptions monitoring sig changes"];
// do send local notification
return YES;
}
[self log:#"didFinishLaunchingWithOptions"];
return YES;
}
my question: when restart mobile and local notification,above code is run and log "didFinishLaunchingWithOptions location key" and so on,if i send local notification at the above code, if user will receive?

in ios 6 there is new feature for maps, which stops location updates
It helps to wake app to recieve location updates.link
locationManager.pausesLocationUpdatesAutomatically
Also see all others.
Your app can start on device boot if its VOIP.
see this apple doc
for local notification add to
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// creating local notification
Class cls = NSClassFromString(#"UILocalNotification");
if (cls)
{
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
NSLog(#"notification text:%#",reminderText);
// [viewController._msgTextView setText:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
and you can handle them in
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
NSLog(#"application:didReceiveLocalNotification:");
}
you can schedule your local notification in
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = notifyDate;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = AlertMsg;
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
notif.alertAction = #"Show me";
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
}

Related

iOS Alarm Clock

I have created a simple alarm notification App through which I can get real time, set alarm on or off, and play a single tone audio. But I need to play a sound which should start with a class VOID.
Below is the code:
To get and start alarm notification:
- (void)viewDidLoad {
[super viewDidLoad];
dateTimerPicker.date = [NSDate date];
}
- (void)presentMessage:(NSString *)message {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Hello!"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
- (void)scheduleLocalNotificationWithDate:(NSDate *)fireDate {
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = fireDate;
notification.alertBody = #"Time to wake up!!";
notification.soundName = #"PhoneOld.mp3";
[self playPause];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
- (IBAction)alarmSetOn:(id)sender{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
NSString *dateTimeString = [dateFormatter stringFromDate:dateTimerPicker.date];
NSLog(#"Alarm Set: %#", dateTimeString);
[self scheduleLocalNotificationWithDate:dateTimerPicker.date];
[self presentMessage:#"Alarm ON!"];
}
- (IBAction)alarmSetOff:(id)sender {
NSLog(#"Alarm Off");
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[self presentMessage:#"Alarm OFF!"];
}
This is my VOID:
- (void)playPause {
RADAppDelegate *appDelegate = (RADAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.radiosound == 0){
[appDelegate.radiosound play];
} else {
[appDelegate.radiosound pause];
}
}
How can I set the alarm to start playing the radiosound if is rated 0, like a:
notification.soundName = [self playPause];
But I know this is a NSString.
You don't need to assign a sound name to scheduled notification, just invoke the playPause method and get the name of sound file from notification, as shown below and just assign it to NSString and set property to it in appDelegate and access it to play that file.
AppDelegate.h
#property (nonatomic,strong) NSString *nsStr_soundFile;
AppDelegate.m
#synthesize nsStr_soundFile;
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
//Give call to play sound method.
self.nsStr_soundFile=notification.soundName;
VOID *obj=[VOID alloc]init];
[obj playPause];
}
You can make a trick with opting out of iOS multitasking by setting in your app .plist file this key UIApplicationExitsOnSuspend to YES as written here
When an app opts out, it cycles between the not-running, inactive, and
active states and never enters the background or suspended states.
An app that runs in the pre-multitasking compatibility mode keeps
running when the user locks the device while the app is in the
foreground. All the app has to do is wait for the alarm time and
execute its custom code.

scheduleLocalNotification doesn't work for jailbreak apps?

I have an app that calls scheduleLocalNotification, but it doesn't work when I install it to /Applications instead of /var/mobile/Applications:
- (void) doNotify
{
// this doesn't work when app is in /Applications but does in /var/mobile/Applications
UILocalNotification * theNotification = [[UILocalNotification alloc] init];
theNotification.alertBody = #"Finished processing.";
theNotification.alertAction = #"Ok";
theNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
[[UIApplication sharedApplication] scheduleLocalNotification:theNotification];
NSLog(#"notification scheduled: %#", theNotification);
}
I tried presentLocalNotification instead in case it was a timing issue.
I implemented didReceiveLocalNotification in app delegate to see if that was being called instead, but it wasn't, it was only called when app is in foreground like it should.
If I put the app back in /var/mobile/Applications, it works as it should.
I'm using Xcode 4.2.1 and running iOS 5.1.1 on an iPhone 4S and iPod Touch 4g
EDIT: App can run in the background because it is a music app
I met the same problem just now. And I already solve this problem through the official document.
In fact, you should regist the notification to get access to use notification:
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
[[UIApplication shareApplication] registerUserNotificationSettings: settings];
Register for Notifications
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings
settingsForTypes:UIUserNotificationTypeAlert| UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];
}
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}
Schedule Notification
- (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(#"startLocalNotification");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
notification.alertBody = #"notification Message ";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
//notification.applicationIconBadgeNumber = 10;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

Showing Local Notifications using Location Manager, While app is in the background

I am new to iPhone Programming .I have developed one application for checking user entered into a particular region.But i need to check in Background.In background i am checking but the problem is repeating the UILocalNotification alerts .
So how to prevent the repeated UILocalNotifications
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"running in background ...");
[self checkRegionEntered];
CurrentlattitudeValue1 =newLocation.coordinate.latitude;
CurrentlongitudeValue1=newLocation.coordinate.longitude;
}
-(void)checkRegionEntered
{
if ([testRegion containsCoordinate:currentCoordinates])
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
UILocalNotification *notif = [[cls alloc] init];
NSDate *now = [NSDate date];
[notif setFireDate:now];
if([Obj.NotesGeo length])
[notif setAlertBody:Obj.NotesGeo];
else
{
[notif setAlertBody:[NSString stringWithFormat:#", you have arrived at %#",Obj.NameGeo]];
}
[notif setAlertAction:#"Launch"];
notif.soundName=[NSString stringWithFormat:#"%#.wav",Obj.Ringtone1];//[NSString stringWithFormat:#"%g",Obj.LatitudeGeo]
NSDictionary *userDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"%f",Obj.LatitudeGeo] forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
}
}
}
This may help. This logic is designed to ensure that your notification will only fire once, and that the same alert is displayed regardless of whether the app is in the foreground or background when it fires.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add the view controller's view to the window and display.
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
//detect if app was launched by notification
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
//trigger our custom notification handler
[self handleLocalNotification:notification];
}
return YES;
}
- (void)handleLocalNotification:(UILocalNotification *)notification
{
//this is our custom method to handle the in-app notification behaviour
[[[[UIAlertView alloc] initWithTitle:#"You have a notification"
message:#"Yay!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease] show];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
//this standard application delegate method is called under the following circumstances
//1. the app is running in the foreground when the notification fires
//2. the app was running in the background when the notification fired, and the user pressed the action button
//confusingly, if the app was not running when the notification fired, this method won't be called at startup
//automatically and you need to check for the notification key in the launch options instead
if ([UIApplication sharedApplication].applicationState != UIApplicationStateBackground)
{
//this code emulates the same behaviour as when a local notification is received
//when the app is not running (except for playing the sound)
//store notification temporarily
[lastNotification release];
lastNotification = [notification retain];
//get button labels
NSString *actionButton = nil;
NSString *cancelButton = #"Close";
if (notification.hasAction)
{
actionButton = (notification.alertAction)? notification.alertAction: #"View"; //defaults to "View" if nil
cancelButton = #"OK";
}
//show alert
[[[[UIAlertView alloc] initWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"] //name of application
message:notification.alertBody
delegate:self
cancelButtonTitle:cancelButton
otherButtonTitles:actionButton, nil] autorelease] show];
}
else
{
//trigger our custom notification handler
[self handleLocalNotification:notification];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
//trigger our custom notification handler
[self handleLocalNotification:lastNotification];
}
}

Setting Local Notifications on a new thread?

I need to know if it is possible to create a new thread to handle setting local notifications.
My app depends heavily on these notifications, so I want to make the app work while the phone sets the notifications.
Example:
(now)
you launch the app, the app hangs at the splash screen to set the local notifications, then it launches.
(I want)
The app launches and is usable while the Local notifications are set.
I need some sample code, too, please :)
(for the record, i am setting 60 local notifications each time the app enters foreground for my own reasons...)
Thanks!!
Yes this can be done, I do it all the time:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add the navigation controller's view to the window and display.
[NSThread detachNewThreadSelector:#selector(scheduleLocalNotifications) toTarget:self withObject:nil];
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
-(void) scheduleLocalNotifications
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < 60; i++)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
NSLog(#"Sleepdate is: %#", sleepDate);
localNotif.fireDate = sleepDate;
NSLog(#"fireDate is %#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"This is local notification %i"), i];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(#"scheduledLocalNotifications are %#", [[UIApplication sharedApplication] scheduledLocalNotifications]);
[localNotif release];
}
[pool release];
}
Taken from a project I am working on now, I can confirm that It works as expected.
EDIT:
Example was leaking in scheduleLocalNotifications because handling the NSAutoreleasePool was missing – now it's added to the example.
One way to do threads is with is with performSelectorInBackground.
For example:
[myObj performSelectorInBackground:#selector(doSomething) withObject:nil];
You should note, however, that Apple is pretty strongly recommending that you use higher-level concepts like NSOperations and Dispatch Queues instead of explicitly spawning threads. See the Concurrency Programming Guide

local notification "didReceiveLocalNotification" calls twice

I am handling local notifications using:
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
And to schedule a local notification:
- (void)scheduleNotificationWithInterval:(int)minutesBefore {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
NSDate *fireDate = [NSDate date];
localNotif.fireDate = [fireDate dateByAddingTimeInterval:minutesBefore*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatInterval = kCFCalendarUnitMinute;
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"LocalEvent notification in %i minutes.", nil),minutesBefore];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:#"This is dict, you can pass info for your notification",#"info",nil];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
NSLog(#"Event scheduled");
}
When I receive a notification, didReceiveLocalNotification: is called twice.
Am I doing something wrong?
Please help.
Thanks.
I think there is a known bug in the simulator, that fires the delegate notification method twice. It should not happen on the device, tethered to XCode or not.
i was also facing the same problem and the solution which i find is that write this code in didReceiveLocalNotification
if (state == UIApplicationStateActive) {
NSLog(#"UIApplicationStateActive");
}
else if(state == UIApplicationStateInactive){
NSLog(#"UIApplicationStateInActive");
}
here in these condition i just write the code which i want my application to do on notification , in Active mode and in inactive mode
I suspect that the notification is being retriggered as long as its in the same second still. I fixed it by setting the fireDate to nil in the handler:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:notification.alertAction message:notification.alertBody delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
notification.fireDate = nil;
}
I had the same issued. It was caused by calling 'registerUserNotificationSettings' twice in the AppDelegate's 'didFinishLaunchingWithOptions.' However, simply removing the duplicate call did not fix the problem yet. I had to delete the app and then rebuild. Only then did the double local notification issue get fixed.