Use a mysql returned variable in IOS app for otherJSON calls - iphone

I have a app and I connect with Json to a mysql DB using PHP and return a value ( UserID ). I now would like to use that value returned for other JSON calls in my WHERE statements.
Do i store the value in a plist file?
How do i make that a global value for that specific user?
Thanks

All you need to do is to save this value in your NSUserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// write value
[defaults setInteger:value forKey:#"value"];
[defaults synchronize];
// read
// if value is not an int but an NSNumber, change it to [defaults objectForKey:#"value"]
value = [defaults intForKey:#"value"];

Historically on iOS, the device UDID has been used as a user's ID in databases. That's recently been banned by Apple, so unless you're forcing users to register with a username and password, you should use the vendor ID as their user ID in the database. The vendor ID is determined using:
NSString* vendorID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
You should pass this value to the server and insert it into your user table as the user's ID.

You can use NSUserDefault to store any variable that is common throughout the application. You can add the object in it and you can remove that when application terminates or that particular User logs out from the application.
e.g.
[[NSUserDefaults standardUserDefaults]setObject:#"10" forKey:#"UserID"];
[[NSUserDefaults standardUserDefaults]synchronize];
And to remove
[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"UserID"];

Related

Please explain NSUserDefault purpose

NSUserDefaults *nsu=[NSUserDefaults standardUserDefaults];
[nsu setObject:[postdata objectForKey:#"url"] forKey:#"url"];
Can anyone explain purpose of NSUserDefault?
I think it is worth mentioning that NSUserDefaults can and should be used to store small amounts of data dealing with user settings and app configuration not set in the Settings.bundle. It is not recommended storing anything with sensitive user information (username, password, etc) as these values are saved in a plain text .plist file in the documents directory.
User defaults can be very flexible and the sky is the limit as to its use, but care should be taken to protect the user's private data. For login information, use the built in keychain. For everything else, there are plenty of options. (e.g. CoreDate, Sqlite)
I hope this is help u.....
NSUserDefaults is a quick and easy way to store small amounts of data for you app. In this example, I’m going to show you how to use NSUserDefaults to store and retrieve data.
Storing Data
// create a standardUserDefaults variable
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[standardUserDefaults setObject:#"mystring" forKey:#"string"];
// saving an NSInteger
[standardUserDefaults setInteger:42 forKey:#"integer"];
// saving a Double
[standardUserDefaults setDouble:3.1415 forKey:#"double"];
// saving a Float
[standardUserDefaults setFloat:3.1415 forKey:#"float"];
// synchronize the settings
[standardUserDefaults synchronize];
Retrieving Data
// create a standardUserDefaults variable
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString object
NSString *myString = [standardUserDefaults stringForKey:#"keyToLookupString"];
// getting an NSInteger object
NSInteger myInt = [standardUserDefaults integerForKey:#"integerKey"];
// getting an Float object
float myFloat = [standardUserDefaults floatForKey:#"floatKey"];
Try this Example also
http://mobile.tutsplus.com/tutorials/iphone/nsuserdefaults_iphone-sdk/
If you want to store data like user_id, name, etc., for your application, which can be accessible anywhere throughout your application, then NSUserDefaults can be used. It is like storing data in user preferences.
For more details, see
NSUserDefaults
NSUserDefault is generally used for storing data for an app in a global manner within the app. When you store a value in NSUserDefault it will be available until the app is removed from the device. In your above example, you store url in key url. You can access the value from anywhere using:
NSUserDefaults *nsu=[NSUserDefaults standardUserDefaults];
NSString *url = [nsu ObjectforKey:#"url"];
NSUserDefault is used to save small amount of data in your App. If your application needs to store certain data which is small in size, so to better avoid concepts like SQLite we use NSUserDefault. I suggest you to go through the following link for better understanding.
Click here for Tutorial

Storing values from NSUserDefaults in Settings bundle

I am trying to find out how to save/store my values from NSDefaults so that when I exit the application they are stored in the Settings.bundle. This is what I am doing...
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:#"M1", #"IDMissiles",
#"G2", #"IDGuns",
#"B3", #"IDBombs",
#"KM", #"IDDistance", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:settings];
If I do the following, the values print out correctly from NSUserDefaults ...
NSLog(#"IDMissiles: %#", [userDefaults stringForKey:#"IDMissiles"]);
NSLog(#"IDGuns : %#", [userDefaults stringForKey:#"IDGuns"]);
NSLog(#"IDBombs : %#", [userDefaults stringForKey:#"IDBombs"]);
NSLog(#"IDDistance: %#", [userDefaults stringForKey:#"IDDistance"]);
However ... Each time I run the application the values in NSUserDefaults start off as (null), I was thinking that doing [[NSUserDefaults standardUserDefaults] synchronize]; would store the values for the next time I run the application, but no such luck.
Instead of using
[[NSUserDefaults standardUserDefaults] registerDefaults:settings];
try this:
[[NSUserDefaults standardUserDefaults] setObject:settings forKey:#"settings"];
Then, get from defaults like this:
NSLog(#"IDMissiles:%#[[[NSUserDefaultsstandardUserDefaults]objectForKey:#"settings"]objectForKey:#"IDMissiles"]);
One thing I discovered when working with the settings.bundle is that none of the values get initialized until you actually open the settings pane. You can have default values saved there, but they will return nil until you open the settings.
I'm not sure if this happens when you try and save values there but never open the settings pane.
If you are not using a settings pane, then you wouldn't want to use the registerDefaults option.
Try this instead.
[[NSUserDefaults standardDefaults] setObject:#"M1" forKey:#"IDMissiles"];
// set remaining values
[[NSUserDefaults standardDefaults] synchronize]; // this really only needs to be called if you plan on accessing values right away, otherwise they are saved automatically after the next run loop
From the documentation:
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.
In other words, you aren't storing anything by registering defaults like this. To have default values both in your app and in the settings bundle, you have to maintain the settings bundle separately as discussed here.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[NSUserDefaults removeObjectForKey:#"userDefaults"];
[userDefaults setObject:[settings objectForKey:#"mainData"] forKey:#"userDefaultsValue"];
[userDefaults synchronize];

How to read from app preferences?

I read Apple Programming Guide on this subject but couldn't figure it out.
I created a Settings bundle using the following tutorial, and I tried accessing my preferences (edited manually) like this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[self setShouldPlaySounds:[defaults boolForKey:#"play_sounds_preference"]];
for "Key" I used the key value entered in the xml editor (double click on Root.plist).
I know you can build preferences with "Identifier" key and "DefaultValue" but I don't want the settings to be accesible in the setting app, I just want two dictuinaries with some strings for my custom settings.
What am I doing wrong? Why can't I get the value of the preferences?
Is it simpler to create my own config file? Implementing a serializer.
Are you setting the value anywhere? And what behavior are you seeing with respect to the value of shouldPlaySounds?
What happens if you execute this first?
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"play_sounds_preference"];
BOOL result = [defaults synchronize]; // force immediate saving of defaults.
NSLog(#"[defaults synchronize] returned %d", result);

Unexpected results from NSUserDefaults boolForKey

After uninstalling an application completely from the device and then loading it in the debugger, I am attempting in a setup method to load a flag using boolForKey. The first time the app runs I have the expectation that the bool will not exist, since I have just reinstalled the app. I expect from the documentation that boolForKey will therefore return NO.
I am seeing the opposite though. boolForKey is returning YES, which fubars my initial user settings. Any idea why this might be happening or a good way around it?
BOOL stopAutoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:#"StopAutoLogin"];
_userWantsAutoLogin = !stopAutoLogin;
So stopAutoLogin comes out as "YES", which is completely unexpected.
Stranger and stranger: When I call objectForKey:#"StopAutoLogin" I get a nil object, as expected. It's just the boolForKey that returns a bad value. So I changed the code to this:
// this is nil
NSObject *wrapper = [[NSUserDefaults standardUserDefaults] objectForKey:#"StopAutoLogin"];
// this is YES
BOOL stopAutoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:#"StopAutoLogin"];
please try [UserDefaults synchronize];
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
please see: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
Do you register the default values for your keys?
NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithCapacity:1];
[appDefaults setObject:#"NO" forKey:kReloadOnStartKey];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:appDefaults];
If there is no registration domain,
one is created using the specified
dictionary, and NSRegistrationDomain
is added to the end of the search
list.
The contents of the registration
domain are not written to disk; you
need to call this method each time
your application starts. You can place
a plist file in the application's
Resources directory and call
registerDefaults: with the contents
that you read in from that file.
See this link for more information.

can we make the user know the date on which the data updated from internet with iphone sdk?

i m making an iphone app that displays data from a website on a table view .basically i m atoring the website's data in an array and then display it on a table. now i want whenever the website update their data the user get the date when the data was updated .can anybody tell some different ways to do it?
So, are you storing (caching) the website's data on the phone and only updating once in a while, or are to loading the website and populating the table every time the app starts?
If you are not storing it (with Core Data, User Defaults, NSKeyedArchiver, etc.) it will be difficult for how can you tell that the data has changed?
In that case (not storing) you could after having pulled the data from the website generate the hash value of the data and store it using NSUserDefaults along with a NSDate.
The next time you pull the information from the website you will generate the hash again and compare it to the previous value. If they match, then the content was not updated, else it was and you store the new hash value and the current date.
If you have control over the website you can do a couple of things.
Return a HTTP header with information about when the website was last updated and compare it with a date stored locally. This will allow you to use the HEAD HTTP semantic to check if a full GET request is needed allowing you to minimize network access.
Implement push notifications (does seem over-kill for your situation) telling the user that the content was updated.
Best of luck.
UPDATE
So your best bet would be calling [myArray hash] and store it in NSUserDefaults, e.g.
NSUInteger hashValue = [myArray hash];
NSDate *now = [NSDate now];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:hashValue forKey:#"hash"];
[prefs setObject:now forKey:#"date"]; // Maybe you have to convert the date to a string.
[prefs synchronize];
And later load it when the app starts (or becomes active):
// Load the website again and generate the hash.
NSUInteger newHashValue = [myArray hash];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSUInteger *oldHashValue = [prefs stringForKey:#"hash"];
NSDate *contentDate;
if (newHashValue == oldHashValue)
{
contentDate = [prefs dateForKey:#"date"];
}
else
{
contentDate = [NSDate now];
// Store the new date.
// and the new hash.
}