1.Whatever I do the saveButton method won't save and it still returns 0 for REJECTIONS
2.Please help me fix my saveButton to userdefaults method
3.I've tried multiple things and the values still won't change
#import "CCViewController.h"
#interface CCViewController ()
#end
#implementation CCViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [NSUserDefaults integerForKey:#"REJECTIONS"];
self.rejectLabel.text=REJECTIONS;
self.acceptedLabel.text=ACCEPTED;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.customInputTextField resignFirstResponder];
}
- (IBAction)resetButton:(UIButton *)sender {
self.rejectLabel.text=#"0";
self.acceptedLabel.text=#"0";
}
- (IBAction)rejectButton:(UIButton *)sender {
int current=stringToInt(self.rejectLabel.text);
int test=stringToInt(self.customInputTextField.text);
if (test>0) {
self.rejectLabel.text=self.customInputTextField.text;
self.customInputTextField.text=nil;
} else {
current++;
self.rejectLabel.text=intToString(current);
}
if (stringToInt(self.rejectLabel.text)==3000) {
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Achievement Message" message:#"You have reached 3000 rejections!" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[alertView show];
}
}
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:#"%d", integer];
}
- (IBAction)acceptedButton:(UIButton *)sender {
int current=stringToInt(self.acceptedLabel.text);
int test=stringToInt(self.customInputTextField.text);
if (test>0) {
self.acceptedLabel.text=self.customInputTextField.text;
self.customInputTextField.text=nil;
} else {
current++;
self.acceptedLabel.text=intToString(current);
}
NSLog(#"after is: %i", current);
}
- (IBAction)unrejectButton:(UIButton *)sender {
int current=stringToInt(self.rejectLabel.text);
current--;
if (current>=0) {
self.rejectLabel.text=intToString(current);
} else {UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Error Message" message:#"You can not have negative rejections!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];}
NSLog(#"after is: %i", current);
}
- (IBAction)saveButton:(UIButton *)sender {
NSString *rejected=self.rejectLabel.text;
int reject=intToString(self.rejectLabel.text);
NSString *accepted=self.acceptedLabel.text;
NSUserDefaults *rejectTry=[NSUserDefaults standardUserDefaults];
[rejectTry setObject:self.rejectLabel.text forKey:REJECTIONS];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setValue:#"reject" forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setValue:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setObject:#"accepted" forKey:ACCEPTED];
}
NSLog(#"test save %# & %# & %# & %#", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text);
[rejectTry synchronize];
NSLog(#"test save %# & %# & %# & %#, &a %i", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text, picker_value);
}
- (IBAction)loadButton:(id)sender {
self.rejectLabel.text=REJECTIONS;
self.acceptedLabel.text=ACCEPTED;
}
#end
Still not saving to the keys rejections and accepted
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.acceptedLabel.text forKey:ACCEPTED];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"test save %# & %# & %# & %# pointers %# %#", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text, defaults, prefs);
It looks like you have muddled up your pointers. You have two references to the same instance of userDefaults yet you expect different results when writing to each one. Here, lets walk through your code
NSString *rejected=self.rejectLabel.text;
int reject=intToString(self.rejectLabel.text);
NSString *accepted=self.acceptedLabel.text;
NSUserDefaults *rejectTry=[NSUserDefaults standardUserDefaults];
Lets stop here. standardUserDefaults is a singleton object. You are not creating a user defaults object when you call this method. You then go on to set a value
[rejectTry setObject:self.rejectLabel.text forKey:REJECTIONS];
This works fine.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
Now you have written over your previous value!
[[NSUserDefaults standardUserDefaults] setValue:#"reject" forKey:REJECTIONS];
And you do it again!
[[NSUserDefaults standardUserDefaults] setValue:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setObject:#"accepted" forKey:ACCEPTED];
Conclusion
What you should be doing is creating a local variable like this NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; Then use this for all your writes. Then you will see how you are overwriting the value with key REJECTIONS multiple times
Related
I have a working code, but now find the need to import & save two different Sqlite files via email "Open in" option, I tried using UIAlertView to create to different save file paths but it only seems to work with one way
- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName]; [dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
}
Both file have specific file names so was wonder if I could use "if equal to string" & use an if statement after I have synchronised NSUserDefaults to give two file path save options
Thanks for any help in advance
This was my UIALertView try
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"What type of data do you want to import?"
message:#"Choose data type"
delegate:self
cancelButtonTitle:#"Import RM Name Data"
otherButtonTitles:#"Import Store Visit Data", nil];
NSInteger *buttonIndex = NULL;
NSLog(#"Button Index =%ld",(long)buttonIndex);
if (buttonIndex == 0)
{
}
else if (buttonIndex == 1)
{
databaseExportName = #"export.sql";
NSArray *pathssqlite3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathssqliteDir2 = [pathssqlite3 objectAtIndex:0];
filePathsqlite3 = [pathssqliteDir2 stringByAppendingPathComponent:databaseExportName];
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSMutableData *dbimport = [[NSMutableData alloc] initWithContentsOfURL:urlx];
NSError *writeError = nil;
[dbimport writeToFile:filePathsqlite3 atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
} } [alertdata show];
Still trying to resolve, was hoping this would work, but still cannot crack it
`- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
if([[urlx absoluteString] isEqualToString:#"svrStoreData2.sql"])
{
NSLog(#"If statement called");
//
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName];
[dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
//
else {
databaseExportName = #"export.sql";
NSString *documentsPathy = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathy = [documentsPathy stringByAppendingPathComponent:databaseExportName];
[dbimport writeToFile:filePathy atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
NSLog(#"If statement Not called");
}
}
}
`
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex(NSInteger)buttonIndex {
if ([alertView tag] == 14)
{
if (buttonIndex == 1)
{
[self reviewSave];
}
}
if ([alertView tag] == 11) {
if (buttonIndex == 1)
{
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];}
}
}
Solved the problem, I had another UIAlert, so by adding Tags sorted it
I have some problems on save the position of switch,any help?
- (IBAction)SWitchActionAño:(id)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (switchAño.on) {
[standardDefaults setBool:YES forKey:#"SwitchState"];
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MMM dd,yyyy HH:mm"];
diadelasemanalabel.text=[formatter stringFromDate:[NSDate date]];
} else {
[standardDefaults setBool:NO forKey:#"SwitchState"];
Año.text=#"";
}
}
but i have the problem here! I dont know what is the property!
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
//the error here:property switchAño not found on object....
if ([standardDefaults objectForKey:#"SwitchState"])
self.switchAño.on =[standardDefaults boolForKey:#"SwitchState"];
Try this in viewDidLoad
-(void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *standardDefaults = [[NSUserDefaults standardUserDefaults];
if ([standardDefaults boolForKey:#"SwitchState"] == YES) {
self.switchAño.on = YES;
}
else {
self.switchAño.on = NO
}
hi i want to integrate Via Me social site into my iphone app,i googled but didn't find any samples.
The basic process is as follows:
Create a custom URL scheme for your app. Via Me will use this after the user has been authenticated, to return to your app. In my example, I created one called "robviame://"
Register your app at http://via.me/developers. This will give you a client id and a client secret:
When you want to authenticate the user, you call:
NSString *redirectUri = [[self redirectURI] stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"https://api.via.me/oauth/authorize/?client_id=%#&redirect_uri=%#&response_type=code", kClientID, redirectUri];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
What that will do is fire up your web browser and give the user a chance to log on and grant permissions to your app. When user finishes that process, because you've defined your custom URL scheme, it will call the following method in your app delegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// do whatever you want here to parse the code provided back to the app
}
for example, I'll call a handler for my Via Me response:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
ViaMeManager *viaMeManager = [ViaMeManager sharedManager];
if ([[url host] isEqualToString:viaMeManager.host])
{
[viaMeManager handleViaMeResponse:[self parseQueryString:[url query]]];
return YES;
}
return NO;
}
// convert the query string into a dictionary
- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSArray *queryParameters = [query componentsSeparatedByString:#"&"];
for (NSString *queryParameter in queryParameters) {
NSArray *elements = [queryParameter componentsSeparatedByString:#"="];
NSString *key = [elements[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [elements[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
value = [[value componentsSeparatedByString:#"+"] componentsJoinedByString:#" "];
[dictionary setObject:value forKey:key];
}
return dictionary;
}
That handler might, for example, save the code and then request the access token:
- (void)handleViaMeResponse:(NSDictionary *)parameters
{
self.code = parameters[#"code"];
if (self.code)
{
// save the code
[[NSUserDefaults standardUserDefaults] setValue:self.code forKey:kViaMeUserDefaultKeyCode];
[[NSUserDefaults standardUserDefaults] synchronize];
// now let's authenticate the user and get an access key
[self requestToken];
}
else
{
NSLog(#"%s: parameters = %#", __FUNCTION__, parameters);
NSString *errorCode = parameters[#"error"];
if ([errorCode isEqualToString:#"access_denied"])
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Via Me functions will not be enabled because you did not authorize this app"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
else
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Unknown Via Me authorization error"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
}
and the code to retrieve the token might look like:
- (void)requestToken
{
NSURL *url = [NSURL URLWithString:#"https://api.via.me/oauth/access_token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSDictionary *paramsDictionary = #{#"client_id" : kClientID,
#"client_secret" : kClientSecret,
#"grant_type" : #"authorization_code",
#"redirect_uri" : [self redirectURI],
#"code" : self.code,
#"response_type" : #"token"
};
NSMutableArray *paramsArray = [NSMutableArray array];
[paramsDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[paramsArray addObject:[NSString stringWithFormat:#"%#=%#", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
}];
NSData *paramsData = [[paramsArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:paramsData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
{
NSLog(#"%s: NSURLConnection error = %#", __FUNCTION__, error);
return;
}
NSError *parseError;
id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError)
{
NSLog(#"%s: NSJSONSerialization error = %#", __FUNCTION__, parseError);
return;
}
self.accessToken = results[#"access_token"];
if (self.accessToken)
{
[[NSUserDefaults standardUserDefaults] setValue:self.accessToken forKey:kViaMeUserDefaultKeyAccessToken];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
Hopefully this will be enough to get you going. This is described in greater detail at the http://via.me/developers page.
I'm working on my app but i need some help.
I need a 'php-like session' in Objective C (without using connection to the internet)
I've thought about global vars, but my app seems to reset them when reloading the view.
This is my current code
SecondViewController.h
#interface SecondViewController : UIViewController
{
NSString * string;
}
SecondViewController.m
#interface SecondViewController ()
#end
#implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (! [string isEqualToString:#"Hello"])
{
NSLog(#"Hello");
string = #"Hello";
}
else
{
NSLog(#"Bye");
}
}
#end
But everytime I reload SecondViewController the 'string' is reseted to its default value.
I'm looking for something that we use in php (a.e. $_SESSION['string'] = 'hello')
It could be helpful to you . It stores the values until unless delete the app from your device .
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
**Retrieving**
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
I have an NSMutableArray being saved with NSUserDefaults, when appLaunched is called the array returns null but when called by any other function it returns what is in the array. Anybody know what's happening?
- (id)init
{
[super init];
theArray = [[NSMutableArray alloc] init];
theArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"TheArray"];
if(!theArray) {
theArray = [[NSMutableArray alloc] init];
} else {
theArray = [[NSMutableArray alloc] initWithArray:theArray];
};
// NSLog(#"%#", theArray);
[[NSUserDefaults standardUserDefaults] setObject:theArray forKey:#"TheArray"];
// NSLog(#"Is saving");
return self;
}
-(IBAction)addNewProcess:(id)sender
{
NSString *newProcess = [theField stringValue];
[theArray addObject:newProcess];
[theField setStringValue:#""];
NSLog(#"%#", theArray);
[theTable reloadData];
}
-(IBAction)removeProcess:(id)sender
{
int listRow = [theTable selectedRow];
NSLog(#"%d", listRow);
if (listRow < 0) return;
[theArray removeObjectAtIndex:listRow];
[theTable reloadData];
}
-(IBAction)save:(id)sender
{
NSLog(#"%#", theArray);
int count = [theArray count];
NSLog(#"%i", count);
[[NSUserDefaults standardUserDefaults] setObject:theArray forKey:#"TheArray"];
NSLog(#"Is saving");
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
return [theArray count];
}
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
{
return [theArray objectAtIndex:row];
}
- (void)tableView:(NSTableView *)tableView
setObjectValue:(id)object
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
{
[theArray replaceObjectAtIndex:row
withObject:object];
}
-(void)appLaunched:(NSNotification *)note
{
NSLog(#"%#", theArray);
}
#end
You didn't synchronize your NSUserDefaults.
Every time you use [[NSUserDefaults standardUserDefaults] setObject:someObject forKey:#"someKey"]; you have to use [[NSUserDefaults standardUserDefaults] synchronize]; afterwords.