Store data after adding items to array - iphone

I have an array that you can add items to. Though when I exit the app the records are not saved. How would I do this.
Here is my appdelgate file becausde that is where my NSMutableArray is held
AppDelegate.m:
#import "LSAppDelegate.h"
#import "LSViewController.h"
#import "Patient.h"
#import "PRViewController.h"
#implementation LSAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
Patient *patient = [[Patient alloc]init];
patient.patientName = #"Patient Name";
patient.patientSurname = #"Patient Surname";
patient.patientDoB = #"Patient Date of Birth";
patient.patientHomeNumber = #"Patient Home No";
patient.patientMobileNumber = #"Patient Mobile No";
patient.patientEmail = #"Patient Email Address";
patient.patientAddress = #"Patient Address";
patient.patientPicture = [UIImage imageNamed:#"patientPicture.jpg"];
// Treatments
patient.treatmentName = #"Treatment Name";
patient.treatmentDate = #"Treatment Date";
patient.treatmentType = #"Treatment Type";
self.patients = [[NSMutableArray alloc]
initWithObjects:patient, nil];
// Override point for customization after application launch.
self.viewController = [[LSViewController alloc] initWithNibName:#"LSViewController" bundle:nil];
self.navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
[[UINavigationBar appearance] setTintColor:[UIColor brownColor]];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (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.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
#end
so far all i've got is:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
please say if you want more code snippets or files.

To preserve the data, you write it to a file on disk and then load that file when the application is started again.

This is how I have done it in my apps.
Create your array and save it to NSdictonary object
Then store your NSDictonary to your apps documents directory.
When your app launches then find your NSDictonary file object and read the array out of it.
The advantage of using NSDictonary is that you can store multiple arrays (in case you are storing multiple patient info).
Here are some sample answers to get you started.
How to store an NSArray in an NSDictionary?
is it possible to save NSMutableArray or NSDictionary data as file in iOS?
How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

Related

Trying to get location updates in background not working

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;
}

Restart application after low memory warning

I'm using my appDelegate's applicationDidReceiveMemoryWarning method to dump some high resource objects. When the app starts back up, rather than trying to reload just those objects and return the user to his last page, I would like just to restart the app from the top (from the main page, the app only goes one level deep, so this is totally acceptable to us).
Here's my paltry attempt, but it was an abject failure. It got close, but I ended up introducing some problems that resulted in an actual memory dump and app crash.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[SplashScreenViewController alloc] initWithNibName:#"SplashScreenViewController" bundle:nil];
UINavigationController *navcon = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navcon;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
//For testing purposes only
self.lowMemoryWarning = TRUE;
NSLog(#"app did enter background");
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSLog(#"app will enter foreground");
if (self.lowMemoryWarning) {
NSLog(#"recovering from low memory warning");
self.window.rootViewController = nil;
UINavigationController *navcon = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navcon;
[self.window makeKeyAndVisible];
}
}
What's the best approach for doing something like this? Is there maybe a simple trick that I don't know about?
Thank you!
Do you mean you want the app to restart each time it started (or enter foreground) ? If yes, maybe you can just set the app to not support multi tasking
http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW5
Search for "Opting out of Background Execution"
================================================================================
Ah sorry, I didn't know the nature of your application, if some process need to be run on the background then this method is no go.
I read your comment above about the UIActivityIndicator + loading the certain objects back on the current view after app enter foreground. Maybe this thread can help you, Finding the current view when application enter foreground. IOS

iOS 6 - State Preservation and Restoration

I have implemented iOS 6 API for state saving, it works - after I quit the app and launch back in for some milliseconds the restored view controller fly in, but then it's replaced by the main view controller I display at launch.
I'm setting every time the app launch the root view of the main window, so this must be the issue.
Here is my code:
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self commonInitializationLaunching:launchOptions];
return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self commonInitializationLaunching:launchOptions];
return YES;
}
- (void)commonInitializationLaunching:(NSDictionary *)launchOptions
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
static NSString *const kKeychainItemName = #"OAuthGoogleReader";
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:kClientSecret];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
BOOL isSignedIn = [auth canAuthorize];
if (isSignedIn) {
NSLog(#"Signed");
}else{
NSString *scope = #"https://www.google.com/reader/api/";
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope
clientID:kClientID
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[self.navController pushViewController:viewController animated:YES];
// self.window.rootViewController = viewController;
}
});
}
You can see that in -(void)commonInitializationLaunching:(NSDictionary *)launchOptions
I'm setting my window's root view. I don't know what to put in there. Perhaps check if there is saved state and then load this method? But how?
Thanks!
Here is what I've tried following Rob's advice:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (!self.isRestored) {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
[self commonInitializationLaunching:launchOptions];
[self.window makeKeyAndVisible];
return YES;
}
with nothing in willFinishLaunching...
I also removed by window code from my commonInitializationLaunching method.
Storyboards will do most of the heavy lifting for you, such as restoring the window. Using code, however, will not restore the window. You will need to hold on to your root view controller using the encoder. Your code will look something like this:
NSString * const AppDelegateRootVCKey = #"AppDelegateRootVCKey";
- (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder {
[coder encodeObject:self.window.rootViewController forKey:AppDelegateRootVCKey];
}
- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder {
// Grabs the preserved root view controller.
UIViewController * vc = [coder decodeObjectForKey:AppDelegateRootVCKey];
if (vc) {
UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.rootViewController = vc;
window.restorationIdentifier = NSStringFromClass([window class]);
// The green color is just to make it obvious if our view didn't load properly.
// It can be removed when you are finished debugging.
window.backgroundColor = [UIColor greenColor];
self.window = window;
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (!self.window) {
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// The blue color is just to make it obvious if our view didn't load properly.
// It can be removed when you are finished debugging.
window.backgroundColor = [UIColor blueColor];
UIViewController *root = // However you create your root.
window.rootViewController = root;
window.restorationIdentifier = NSStringFromClass([window class]);
self.window = window;
}
[self commonInitializationLaunching:launchOptions];
[self.window makeKeyAndVisible];
return YES;
}
Another gotcha to watch out for is to make sure that your UINavigationControllers and UITabBarControllers have restoration identifiers.
State restoration is generally integrated with storyboards. If you're using a storyboard, you should not be creating your own window, view controllers, etc. You should let the storyboard do this for you. What's happening is that the storyboard is doing all the state restoration, and then you're creating a new window and laying it on top of all that. If that's the case, you're probably creating two copies of your UI on every launch. You're just not noticing it.
If you are constructing your entire interface in code (not a recommended approach, but it does work), then you need to determine whether state restoration happened before creating your UI. This is fairly simple:
In your commonInitializationLaunching:, initialize only non-UI elements (things that wouldn't ever be in state-preservation). This is the place to handle things that the UI elements might rely on during state restoration. You don't have any of these in your current code.
In application:didDecodeRestorableState:, set an app delegate ivar to indicate that state was restored.
In application:didFinishLaunchingWithOptions:, after running commonInitializationLaunching:, check your ivar. If state wasn't restored, create a UI.
Do remember that the commonInitializationLaunching: pattern only exists for backward compatibility with iOS 5. If you don't need that, then just put non-UI in willFinish and UI in didFinish (if state wasn't restored).

Can UILocalNotification fire a custom method when App is in background mode?

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

iPhone didFinishLaunchingWithOptions Method

So i'm trying to use this method to load a certain theme based on what the user chose in the settings bundle. When I insert NSLog it will load the default them (Modern Theme), but it will never change to the Pink Theme.
Is this method loaded every time the app is launched, even if the app is still running in the background.
Otherwise, where else could I do this, if I want to use the settings bundle.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary *userDefaultsDefaults = [NSDictionary dictionaryWithObjectsAndKeys: #"Modern Theme", #"theme", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsDefaults];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
theme =[defaults objectForKey:#"theme"];
NSLog(#"%#", theme);
if ([theme isEqualToString:#"Modern Theme"]) {
viewController = [[viewTwo alloc] initWithNibName:#"viewTwo" bundle:nil];
}
else {
viewController = [[viewOne alloc] initWithNibName:#"viewOne" bundle:nil];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Have you tried putting your code in applicationDidBecomeActive:? That one is guaranteed to be called whether on the initial launch or resuming from the background.
Reference docs.
The method
- (void)applicationWillResignActive:(UIApplication *)application
is fired when the app is resumed from the background.
I'd nearly load the theme in the ViewController's
-(void)viewDidAppear:(BOOL)animated
method.