I am using AFNetworking 2.0 and Mantle in order to connect to an API and return a user account.
My plan is to call the function that gets the user data in the application:didFinishLaunchingWithOptions: method. I will then encode the data and save the user into NSUserDefaults
Is this the best way to approach this task? What alternatives are there? (I'd like to stay away from creating singletons)
UPDATE
Some code to maybe help show what I am thinking in my head:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedUserData = [defaults objectForKey:#"currentUser"];
if (encodedUserData) {
self.currentUser = [NSKeyedUnarchiver unarchiveObjectWithData:encodedUserData];
} else {
NSLog(#"No current user");
// Show login ViewController
}
If you are going to get the user account every time user launches the app, then you don't need to store it in NSUserDefaults. Just use a singleton or static object to store it as your model object type.
static Account *_userAccount = nil;
+ (Account*)userAccount {
return _userAccount;
}
+ (void)setUserAccount:(Account*)account {
_userAccount = account;
}
You can use NSUserDefaults for this purpose and can access it through out application.
// to save data in userdefaults
[[NSUserDefaults standardUserDefaults] setObject:#"your object" forKey:#"your key"];
[[NSUserDefaults standardUserDefaults] synchronize];
// for getting saved data from User defaults
NSData *encodedUserData = [[NSUserDefaults standardUserDefaults] objectForKey:#"your key"];
if (encodedUserData) {
self.currentUser = [NSKeyedUnarchiver unarchiveObjectWithData:encodedUserData];
} else {
NSLog(#"No current user");
// Show login ViewController
}
Related
I wanted to know how can I save a user's input when the user enters something from his mobile phone in the UITextField?
If I just use the text field and run the app I can enter data in the text field but when I close the application the data is gone. So how can I store that data permanently and show it again after the application is closed and reopened. Is there any way to save it?
At first, you should save the text when user did editing before user close the application(e.g. saved by NSUserDefaults):
self.yourTextView.delegate = self;
- (void)textViewDidChange:(UITextView *)textView
{
if (textView.markedTextRange == nil)
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textView.text forKey:#"userText"];
[defaults synchronize];
}
}
Then, load the text that user saved before when user open your application again:
- (void)viewDidLoad
{
[super viewDidLoad];
self.yourTextView.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"userText"];
}
We can save data into 3 data base
If you want to store single data into db, you can use
NSUserDefault
For store
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textView.text forKey:#"textviewdata"];
[defaults synchronize];
For Retrieve
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *strTextViewText = [NSString stringWithFormat:#"%#",[defaults objectForKey:#"textviewdata"]];
Then Store a larger amount of data,we can use
SQLite
CoreData
Here are some ways to save data inside application.
create local database using sqlite or coredata both provides facilty to save data locally and before use please find the different situations to use these databases.
using NSUserDefaluts but not recomemded because NSUserDefaults aren’t meant to store sensitive information for more information see imp link see example also if you still.
To store data using NSUserDefaluts:
[[NSUserDefaults standardUserDefaults]setObject:self.textfield.text forKey:#"yourKey"];
To get data anywhere inside app:
object = [[NSUserDefaults standardUserDefaults] valueForKey:#"yourKey"];
Try with this:
-(void)viewDidDisappear:(BOOL)animated
{
[[NSUserDefaults standardUserDefaults]setObject:self.urtextfield.text forKey:#"savedtext"];
}
-(void)viewWillAppear:(BOOL)animated
{
self.urtextfield.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"savedtext"];
}
I am new to iOS i donot know how to save username and password in an app So that there is no need to fill login details in the app till then user do not logout the app. I save my username and password in NSUSerdefaults. I search on google. I found this could be done with KeyChainWrapper class . i tried that way but that will not give me useful result. AnyOne can me help out for this problem.He/She could be greatly appreciate for that.
Use the iOS keychain. Do Not use user defaults to store potentially important information such as logins and passwords.
Here's some documentation from Apple about its OS Keychain.
There's also this very handy, open sourced, wrapper around iOS Keychain called UICKeychainStore.
- (void)viewWillAppear:(BOOL)animated
{
if([[defaults objectForKey:#"remember"]isEqualToString:#"1"])
{
////for getting those values:
_txt_email.text = [defaults objectForKey:#"username"];
_txt_password.text = [defaults objectForKey:#"password"];
// Login code
}
[super viewWillAppear:animated];
}
- (IBAction)Login:(id)sender
{
//To store valuses:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([[defaults objectForKey:#"remember"]isEqualToString:#"1"])
{
[defaults setObject:_txt_email.text forKey:#"username"];
[defaults setObject:_txt_password.text forKey:#"password"];
[defaults synchronize];
}
//Login here
}
easiest way is this, download this repo, and import it into your project:
https://github.com/soffes/sskeychain
Then do this:
[[NSUserDefaults standardUserDefaults] setObject:USERS_USERNAME forKey:#"com.yourapp.whateveryouwant"];
[[NSUserDefaults standardUserDefaults] synchronize];
[SSKeychain setPassword:USERS_PASSWORD forService:[[NSBundle mainBundle] bundleIdentifier] account:USERS_USERNAME];
Using the SSKeyChain repo, you can sync your User's user name to the password and store it securely
You can retrieve it and check it by doing this:
if ([[NSUserDefaults standardUserDefaults] valueForKey:#"com.yourapp.whateveryouwant"]) {
if ([SSKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier]
account:[[NSUserDefaults standardUserDefaults] valueForKey:#"com.yourapp.whateveryouwant"]]) {
//do work
}
}
try this:
call below method after successful log in and when user uses app next time push directly to the next view.
+(void)setFirstLogIn:(BOOL)flag
{
[[NSUserDefaults standardUserDefaults] setBool:flag forKey:#"FirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
There are many ways to do that. If you are having more data to store after login, I would prefer to use CoreData or Sqlite. You can store create entity or table, and store you required data into that. Nexttime whenever you start app, Check it the values are stored or not.
Here the links which help you to start with basics for coredata and sqllite
CoreData Referral
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
Sqlite Referral
http://www.theappguruz.com/blog/use-sqlite-database-swift
To store values:
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:#"username"];
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:#"password"];
[[NSUserDefaults standardUserDefaults] synchronize];
for getting those values:
[[NSUserDefaults standardUserDefaults] valueForKey: #"username"];
[[NSUserDefaults standardUserDefaults] valueForKey: #"password"];
NSUserDefaults will remove when your app will be removed from device. Otherwise it will store the values.
Use the class NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:#"username" forKey:#"usersave"];
[[NSUserDefaults standardUserDefaults] setObject:#"usernamexxx" forKey:#"passsave"];
[[NSUserDefaults standardUserDefaults] synchronize];
Get them using:
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"passsave"];
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"usersave"];
I am new to iOS development and have the following problem.
EXPLANATION:
I have an app which consists of several mini games. Each mini game is available through in app purchase. However the mini game availability is saved in a BOOL variable like this:
_miniGamesArray = [[NSMutableArray alloc] init];
NSMutableDictionary *mutDictMg0 = [NSMutableDictionary dictionaryWithCapacity:3];
[mutDictMg0 setValue:[self.gameAvailabilityMutableArray objectAtIndex:0] forKey:#"GameAvailable"];
[_miniGamesArray addObject:mutDictMg0];
PROBLEM:
Each time I start the app the game availability is checked from the self.gameAvailabilityMutableArray which is set to:
- (NSMutableArray *)gameAvailabilityMutableArray
{
if (!_gameAvailabilityMutableArray)
{
//[_gameAvailabilityMutableArray addObjectsFromArray:#[#1,#0,#0,#0 ,#0,#0,#0,#0]];
_gameAvailabilityMutableArray = [[NSMutableArray alloc] initWithArray:#[#1,#1,#1,#1 ,#1,#1,#1,#1]];
}
return _gameAvailabilityMutableArray;
}
When the customer buys a mini game I want the array to be set to (example):
#[#1,#1,#0,#0 ,#0,#0,#0,#0]]
TRIED SOLUTIONS:
I tried to implement the array by calling the iTunes server and writing the data. However, the time to recieve the request is greater then the app loading time. The second problem arrises if there is no internet connection, then the app crashes.
I also tried using .plist files. I don't know why but writing to the plist file doesn't change it's contest all the time! Some times it works , sometimes it doesn't... Sometimes the app loads the values correctly sometimes it mixes them with the last values.
QUESTION:
Is there a way to store permanent app data which is being checked when the app loads beside plists?
Thank you for your time.
save your data in NSUserDefaults.then use below conditions for app start first time or handle another conditions.
BOOL iSFirstTime = [[NSUserDefaults standardUserDefaults] boolForKey:#"AppStartFirstTime"];
if (!iSFirstTime) {
NSLog(#"Application start first time");
[[NSUserDefaults standardUserDefaults] setValue:#"ImgDownloaded" forKey:#"ProductIDDef"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"AppStartFirstTime"];
}else{
// NSLog(#"we are here");
if ([[[NSUserDefaults standardUserDefaults] valueForKey:#"ProductIDDef"] isEqualToString:#"ImgDownloaded"]) {
NSLog(#"All transaction and Image Downloading has been perform successfully");
}else{
//If any network problem or any thing else then handle here.
}
}
}
You can save the data in NSUserDefaults using the following code:
[[NSUserDefaults standardUserDefaults] setObject:_gameAvailabilityMutableArray forKey:#"gameArray"];
[[NSUserDefaults standardUserDefaults] synchronise];
and you can retrieve the array using
_gameAvailabilityMutableArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"gameArray"];
Is it possible to save and load data on Today Extension using NSUserDefaults?
After closing the Notification Center, the widget behaves like an app which is terminated, so any data results lost. How could I solve this issue?
This is my code:
NSUserDefaults *defaults;
- (void)viewDidLoad {
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
NSArray *loadStrings = [defaults stringArrayForKey:#"savedStrings"];
if ([loadStrings objectAtIndex:0] != nil) {
[display setText:[NSString stringWithFormat:#"%#", [loadStrings objectAtIndex:0]]];
}
if ([loadStrings objectAtIndex:1] != nil) {
calculatorMemory = [NSString stringWithFormat:#"%#", [loadStrings objectAtIndex:1]].doubleValue;
}
}
- (IBAction)saveData:(id)sender {
NSString *displayString;
NSString *memoryString;
NSArray *saveStrings = [[NSArray alloc] initWithObjects: displayString, memoryString, nil];
defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:saveStrings forKey:#"savedStrings"];
[defaults synchronize];
}
You need to use app group identifier instead of com.*
For instance:
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:#"group.company.appgroup"];
Don't forget to synchronise when you store data
[shared synchronize];
You need to add the App Group stuff detailed under here and then if it actually worked (pretty iffy under beta) it should allow you to share NSUserDefault data like normal between the host and widget.
Edit: Normal NSUserDefaults does not work. Apple has implemented a new method. To use, simply redefine your NSUserDefaults instance like this:
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:#"com.you.app.container"];
For anyone wondering how in the world do you save and get values then look at this code.
In your regular app add this to save whatever you like in your *.m file.
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:#"group.yourcompanyname.TodayExtensionSharingDefaults"];
//save dic
[shared setObject:dictionary2 forKey:#"dicForTodayWidget"];
//save array
[shared setObject:tempArray2 forKey:#"arrayForTodayWidget"];
//save some value
[shared setObject:#"1234" forKey:#"myValForTodayWidget"];
[shared synchronize];
In your today widget under TodayViewController.m in viewDidLoad add this.
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:#"group.yourcompanyname.TodayExtensionSharingDefaults"];
//get dic
NSMutableDictionary *dictionary = [shared objectForKey:#"dicForTodayWidget"];
You first need the App Groups set up for both targets (application and the extension).
Then, use the
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:#"group.company.myapp"];
to obtain the defaults object which you can read from/write to as usual.
If you want to be notified of changes to the defaults, use the NSUserDefaultsDidChangeNotification in your widget (or app).
For a step-by-step tutorial explaining all this, take a look at this blog post.
#edukulele
Today Extension and Main app run on two processes. Today Extension can't receive NSUserDefaultsDidChangeNotifications. I tried use MMWormhole. It is very good.
This question already has answers here:
declaring global variables in iPhone project
(6 answers)
Closed 9 years ago.
I am making a login system in objective c (for an iPhone app) and I would like to record if the user is logged in or not. I figured the best way to do this would be to use a global variable BOOL isLoggedIn after I have validated their credentials. Can someone please help me or give me some advice because I am completely lost on how to do this.
Thanks in advance
-(void)saveToUserDefaults:(BOOL)isLoggedIn
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setBool:isLoggedIn forKey:#"isLoggedIn"];
[standardUserDefaults synchronize];
}
}
Use NSUserDefaults, It will retain the value until your app is deleted from the phone.
use this two function
-(void)addToNSUserDefaults:(id)pobjValue forKey:(NSString *)pstrKey{
NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults];
[objUserDefaults setObject:pobjValue forKey:pstrKey];
[objUserDefaults synchronize];
}
-(id)fetchFromNSUserDefaults:(NSString *)pstrKey{
NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults];
return [objUserDefaults objectForKey:pstrKey];
}
When you store it
[self addToNSUserDefaults:#"YES" forKey:#"isLoggedIn"];
When retrive it
if ([self fetchFromNSUserDefaults:#"isLoggedIn"]==nil || [[self fetchFromNSUserDefaults:#"isLoggedIn"] isEqualToString:#""]) {
//Go to Login
}
else
//all ready Login
You can either use NSUserDefaults to store the app's login state as stated by the others. The value will stay as is until the app is deleted. i.e. even when you kill the app or restart the device, if the last value was 'logged in'.
If you want to 'reset' the user's state when the app is killed or device is restarted, then another approache is to make your User's object as a singleton. When app is killed or device is restarted, unlike the NSUserDefault, the user's state will be reset (as the object no longer exists) and user will need to login again. Using this method: http://lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html to create singleton of your user's object
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
Add the above to your User's class and then you can then add the appropriate properties related to the user's state, e.g BOOL isLoggedOn, and then you can access this along the line:
BOOL isLoggedIn = [[User sharedInstance] isLoggedIn];