How to check the latest version of the app with NSUserDefaults - objective-c

I want to check if user is using the latest version of the app. If so, i should color the background of some cells.
This is the code i'm using:
appDelegate.m
NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:#"lastVer"];
method where i want to check:
NSString *lastVersion = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:#"lastVer"];
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
lastVersion = #"1.3.4";
if(![lastVersion isEqualToString:version]){
cell.backgroundColor = [UIColor yellowColor]; ;
cell.imageView.image = [UIImage imageNamed:#"image.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
}
Am i doing it right? Is my code checking for the latest version or? How can i simulate this behavior in the simulator \ on device?
What i want to do is check if the user is using the latest version of the app, in order to call in another NSUserDefaults key to show the cells of my tableView with a different background color.
EDIT
Code i'm using to change the cells background if the user is using the latest version of my app and if the user has used the app less than three times:
NSString *cellValue = cell.textLabel.text;
NSNumber *runNumber = (NSNumber *)[[NSUserDefaults standardUserDefaults] objectForKey:#"runNum"];
NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:#"lastVer"];
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
if (!runNumber) {
runNumber = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject:runNumber forKey:#"runNum"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
if([lastVersion isEqualToString:version]){ //check if the user is using the latest version
if ([runNumber intValue] < 4) { //check if user has used the app less than 3 times
if ([cellValue isEqual: "someText"] ){
cell.backgroundColor = [UIColor yellowColor]; ;
cell.imageView.image = [UIImage imageNamed:#"image.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
}
}

this code will not set anything..
NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:#"lastVer"];
lastVersion = #"1.3.4";
you need a setter:
[[NSUserDefaults standardUserDefaults] setObject: #"1.3.4" forKey:#"lastVer"];//in memory
[[NSUserDefaults standardUserDefaults] synchronize];//to disk
and a getter:
NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:#"lastVer"];
edit:
remember that lastVersion is a pointer and you just set it to point somewhere else, that doesn't set it in stdUserDefaults and it doesn't synchronize it to disk.

Surely if you want to check if the user is using the latest version of the app you would need to check with an external resource.
e.g.
Simple HTTP request to your own server, which returns your latest app version.
Then compare this against your current version [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
Store the result of this test in NSUserDefaults

Related

Accessing imageurl using userdefaults in objective c

I have fetched the image from image picker and uploaded the image to web service and i have a image url.I have saved the imageurl using user defaults as given below:
-(void)postSignupService {
[NewJsonHelperClass postExecuteWithParams:#"signup" secondParm:[self signUpParams] onCompletion:^(NSDictionary *json){
if ([[json valueForKey:#"status"] isEqualToString:#"success"]) {
NSDictionary *dataDict =[NSDictionary new];
dataDict =[json valueForKey:#"user"];
[[NSUserDefaults standardUserDefaults] setObject:#"sucess" forKey:#"LoginStatus"];
[[NSUserDefaults standardUserDefaults] setObject:[dataDict valueForKey:#"_id"] forKey:#"user_Id"];
[[NSUserDefaults standardUserDefaults] setObject:[dataDict valueForKey:#"userName"] forKey:#"userName"];
[[NSUserDefaults standardUserDefaults] setObject:[dataDict valueForKey:#"password"] forKey:#"Password"];
[[NSUserDefaults standardUserDefaults] setObject:[dataDict valueForKey:#"email"] forKey:#"email_Id"];
[[NSUserDefaults standardUserDefaults] setObject:[dataDict valueForKey:#"profile_pic"] forKey:#"image_Str"];
NSLog(#"datadict is %#",dataDict);
SelectFoodVC *selectVc = [appDelegateRef.storyBoard instantiateViewControllerWithIdentifier:#"SelectFoodVC"];
[self.navigationController pushViewController:selectVc animated:YES];
// TabBarController *tabVc = [appDelegateRef.storyBoard instantiateViewControllerWithIdentifier:#"TabBarController"];
// [self.navigationController pushViewController:tabVc animated:YES];
}
else{
[reUse showAlertWithTitle:[json valueForKey:#"status"] message:[json valueForKey:#"user"] thirdParam:self];
}
}];
}
-(NSDictionary *)signUpParams {
NSMutableDictionary *params =[NSMutableDictionary new];
params[#"userName"] =self.userNameTf.text;
params[#"email"] =self.emailTf.text;
params[#"password"] =self.passwordTf.text;
NSLog(#"imgstr is %#",imgStr);
params[#"profile_pic"] =imgStr;
return params;
}
Here profile pic value is imgStr which is got as imageurl from web service.
When i try to retrieve the imageurl in different viewcontroller,the value of userdefault is null as it shows error.
NSString *urlstring = [[NSUserDefaults standardUserDefaults] objectForKey:#"image_Str"];
NSLog(#"urlstring is %#",urlstring);
Here urlstring is null and the error is Error: Request failed: not found (404)
NSString *str = [NSString stringWithFormat:#"http://swiftdeveloperblog.com/wp-content/uploads/2015/07/1.jpeg"];
NSURL *url = [NSURL URLWithString:str];
[[NSUserDefaults standardUserDefaults]setURL:url forKey:#"URL"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSString *getURL = [[NSUserDefaults standardUserDefaults]URLForKey:#"URL"];
NSLog(#"url is %#",getURL);

IOS how to query Username and Password like from a plist

I want to code a LoginView in Xcode, to query the Password and Username i want to use a Textfile or plist. How can i use it?
Generally passwords are either taken from service call or from userdefaults:
You can do something as :
- (IBAction)submitPressed:(id)sender {
NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
if (userName == NULL) {//no user pwd exists. create a new one
if (self.userTextField.text.length>0 && self.passwordTextField.text.length>0) {
NSLog(#"Create a user+pwd in server. Now for showing purpose we are saving it in userdefaults.");
[[NSUserDefaults standardUserDefaults] setObject:self.userTextField.text forKey:#"userName"];
[[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:#"password"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else{ //some user pwd exists, now check that with json value.
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
if ([userName isEqualToString:self.userTextField.text] &&
[password isEqualToString:self.passwordTextField.text]) {
NSLog(#"logged in successfully");
//[self performSegueWithIdentifier:#"HomeView" sender:nil];
}
else{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Login"
message:#"Invalid username and/or password"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
}
}
}
Edit:
If you still want to read user/password from text file of plist you can use :
//PLIST
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Credentials" ofType:#"plist"]];
NSString *user = dictionary[#"username"];
NSString *password = dictionary[#"password"];
//TEXT
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Credentials" ofType:#"txt"];
NSString *contents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];
//then use NSString api's to extract user and password from contents
Here is the lines you need to write to save the username and password to save in the PList which is in the Documents Directory..
- (IBAction)saveToPlist:(id)sender {
NSDictionary *loginDetails=[[NSDictionary alloc]initWithObjects:#[self.userName.text,self.password.text] forKeys:#[#"username",#"password"]];
if ([loginDetails writeToFile:[self plistPath] atomically:YES]) {
NSLog(#"successfully entered");
}
else{
NSLog(#"something wrong");
}
}
//code to retrieve the data from plist
NSDictionary *details=[[NSDictionary alloc]initWithContentsOfFile:[self plistPath]];
where the [self plistPath] is
-(NSString*)plistPath{
NSArray *arr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[arr objectAtIndex:0]stringByAppendingPathComponent:#"login.plist"];
}
Happy Coding :)

Save and load text color

I looked and looked and looked for this and when i finally find something it does not work. I am trying to save and load text color that the user selects. Here is my save button:
-(IBAction)save123456 {
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:textview];
[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:#"myColor"];
}
And here is my load:
-(IBAction)load123456 {
NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:#"myColor"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
}
My text view is textview if that helps. Also i am linking everything via tuchupinside so let me know if i should change anything.
Also if anyone knows how to save text font that the user selects would also be helpful. Thanks so much!!
Well , you could save the RGB of the color. And the font-name of the font.
So when you're saving , store these values for font: font.fontName , font.pointSize
and RGB of the color. Here you can see how to get the RGB of a UIColor object.
These are all NSString and float values so you shouldn't have any problem in saving them.
- (NSString *) pahtForFile:(NSString*) filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:filename];
}
- (void) save
{
//get RGB and fontName , fontSize like I explained above
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:fontName forKey:#"fontName"];
[dictionary setObject:[NSNumber numberWithFloat:fontSize] forKey:#"fontSize"];
[dictionary setObject:[NSNumber numberWithFloat:red] forKey:#"red"];
[dictionary setObject:[NSNumber numberWithFloat:green] forKey:#"green"];
[dictionary setObject:[NSNumber numberWithFloat:blue] forKey:#"blue"];
NSString *filepath = [self pathForFile:#"save.plist"];
[dictionary writeToFile:filepath atomically:TRUE];
}
- (void) load
{
float red,green,blue,fontSize;
NSString *fontName;
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[self pahtForFile:#"save.plist"]];
red = [[dictionary objectForKey:#"red"] floatValue];
green = [[dictionary objectForKey:#"green"] floatValue];
blue = [[dictionary objectForKey:#"blue"] floatValue];
fontSize = [[dictionary objectForKey:#"fontSize"] floatValue];
fontName = [dictionary objectForKey:#"fontName"];
//now rebuild color and font like this:
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1];
UIFont *font = [UIFont fontWithName:fontName size:fontSize];
}
Hope this helps.
BTW: If you find the answer useful , mark it as correct.
Cheers,
George

Objective-C save NSColor in NSUserDefaults

How do you save the color of the dot so that when the app is opened and closed the dot is the color it was last set to by the user?
Could someone explain to me how to use NSUserDefaults and in which methods to declare NSUserDefaults.
So far i have this:
NSData *data = [NSArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"MyColor"];
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:#"MyColor"];
NSColor *color = [NSUnarchiver unarchiveObjectWithData:data];
Link for tutorial I followed:
http://www.mactech.com/articles/mactech/Vol.25/25.04/2504RoadtoCode/index.html
This is what I use:
- (NSColor *)colorForKey:(NSString *)key
{
NSData *data;
NSColor *color;
data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
color= [NSUnarchiver unarchiveObjectWithData:data];
if( ! [color isKindOfClass:[NSColor class]] )
{
color = nil;
}
return color;
}
- (void)setColor:(NSColor *)color forKey:(NSString *)key
{
NSData *data = [NSArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
[BFChatWindow refresh];
}

Xcode Saving NSMutableArray of String & BOOL values

I've got a little problem with an Application i am designing at the min but i'm a complete beginner, first of all a little information on what i am trying to accomplish.
I have a plist which populates an NSMutableArray which contains many values each one has a string and a BOOL inside, i can make the program save a copy of the file upon opening the app and load the data into the tableview along with an accessoryview of a checkmark.
now the checkmark works ok and you can select different items and the checkmark only appears on those items none of the others and if you inspect the log the details for each of the items check BOOL is changed but when i come to save a second time the checkmark state is not persisted for when i open the application a second time it just saves it as a 0 everytime.
here is some of my code, any help would be appreciated.
Thanks
Brad
- (void)viewDidLoad {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"CustomChecklist.plist"];
success = [fileManager fileExistsAtPath:filePath];
NSLog(#"STATUS OF SUCCESS %d",success);
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"OriginalChecklist" ofType:#"plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:NULL];
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"IF STATEMENT CREATING THE FILE");
}else {
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"IF STATEMENT READING THE FILE");
}
NSLog(#"location information %#", filePath);
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"cell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame; // match the button's size with the image size
[button setBackgroundImage:image forState:UIControlStateNormal];
// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)viewWillDisappear:(BOOL)animated
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savePath = [documentsDirectory stringByAppendingPathComponent:#"CustomChecklist.plist"];
NSLog(#"View Will Disappear SAVE location information %#", savePath);
[dataArray writeToFile:savePath atomically:YES];
}
BOOL is not an object, it is a primitive type. Therefore, it cannot be saved (properly) in an array or dictionary. You need to use the NSNumber class to wrap it:
[NSNumber numberWithBool:checked] //this should be added to the dictionary
I am writing this from my phone, so I can't really see all of your code. But I just wanted to say that what you are trying to achieve can probably be solved by using NSUserdefaults instead of saving a file. Have you looked into that?
Oh, and just like Evan said, bool isn't an object. Only objects can be stored in an array.
Is there a reason you are adding the cell to your dictionary? A UITableViewCell is not a property list compatible object, so it could keep your array from saving properly.