Credential editing in Plist if Correct - iphone

In plist I have stored Credentials from that I need to check for the correct Credential and if the correct Credential match then replace the password field with the new..for this I Have 3 UITextField . A for new email-id ,b for current password and c for new password ..if a==b means current password == email id then new password entered in the c textfield should replace in the current password field in plist
.
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
// what should be the condition to replace current password to new password
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}

Check if this will work for you.
- (void)authenticateCredentials {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *plistArray = [dict objectForKey:#"title"];
NSMutableArray *plistUpdatedArray = [NSMutableArray arrayWithArray:plistArray];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithDictionary:objDict];
[dict1 setObject:newPassword forKey:#"title"];
[plistUpdatedArray replaceObjectAtIndex:i withObject:dict1];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithDictionary:dict];
[dict2 setObject:plistUpdatedArray forKey:#"title"];
[dict2 writeToFile:documentPlistPath atomically:YES];
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}

If your plist is in bundle you can't change the value stored in it.
So copy it to document directory before doing any change.
Answer to your question:
if([emailField.text isEqualToString:currntPwd.txt])
{
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
[newDict addEntriesFromDictionary:objDict];
[newDict setObject:#"Midhun" forKey:#"pass"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *plistPath = [docDirectory stringByAppendingPathComponent:#"yourPlist.plist"];
[[NSFileManager defaultManager] removeItemAtPath:plistPath];
[newDict writeToFile:plistPath atomically:YES];
}

Related

How to sort plist by its value

I have Plist with list with List of Dictionaries(item0,item1,item2).and I populate this plist in the Graph..its works fine.and in Plist key (date)-> Value(i store by using NSDate) .Now I need to sort the Plist in such a way that:-
graph should display for only one week.
say if first value is 26-Dec-12 than only upto 1-Jan-13(1 week) values plist should display
.
code :
- (NSArray *)readFromPlist
{
// get paths from root direcory
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"calori.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
valueArray = [dict objectForKey:#"title"];
return valueArray;
}
and
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef _context = UIGraphicsGetCurrentContext();
ECGraph *graph = [[ECGraph alloc] initWithFrame:CGRectMake(10,10, 480, 320)
withContext:_context isPortrait:NO];
NSMutableArray *Array=[NSMutableArray arrayWithArray:[self readFromPlist]];
NSMutableArray *items = [[NSMutableArray alloc] init];
for (id object in [Array reverseObjectEnumerator]){
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
NSString*str1=[objDict objectForKey:#"date"];
NSLog(#" str values2-- %#",str1);
tempItemi.isPercentage=YES;
tempItemi.yValue=f;
tempItemi.name=str1;
[items addObject: tempItemi];
}
}
[graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];
}
As your requirement is to filter date within 7 days,
I am giving you a logic, try this way:
- (NSArray *)readFromPlistForOneWeek {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"calori.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
//loop through each of the item
//and check if <8 then add that keyValue to array
NSMutableArray *tempValueArray=[NSMutableArray new];
for (NSDictionary *subDict in [dict objectForKey:#"title"]) {
// NSLog(#"=> %#",subDict);
NSString *plistDateString=[subDict objectForKey:#"date"];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"dd-MMM-yy"];
NSDate *plistDate=[dateFormatter dateFromString:plistDateString];
NSString *currentDateString=[dateFormatter stringFromDate:currentDate];
NSTimeInterval secondsBetween = [plistDate timeIntervalSinceDate:currentDate];
NSInteger dateDiff = secondsBetween / 86400;
if( dateDiff<8 ){ //within 0-7 days
[tempValueArray addObject:subDict];
}
}
NSLog(#"valuArray : %#",tempValueArray);
return tempValueArray;
}
Have you tried with NSSortDescriptor?
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"DATE" ascending:YES selector:#selector(compare:)];
[yourDictionary sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
Try this
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourfile" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
// sort it
NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
// iterate and print results
for(NSString *key in sortedArray) {
NSLog(#"key=%#,value=%#", key, [dict objectForKey:key]);
}

How to fetch data from pList in Label

I have a RegistrationController screen to store email-id ,password,DOB,Height,Weight and logininController screen to match email-id and password to log-in purpose.
Now, In some third screen I have to fetch only the Height,Weight from the plist of the logged-in user to display it on the label.now if I Store the values of email-id and password in from LoginViewController in string and call it in the new screen to match if matches then gives Height,Weight ..if it corrects then how to fetch Height,Weight from the plist of the same one.
How can I fetch from the stored plist in a string?
Here is my code:
-(NSArray*)readFromPlist
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *valueArray = [dict objectForKey:#"title"];
return valueArray;
}
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}
First get whole value from your plist file after that store this NSArray into NSMutableArray and get the value with its objectAtIndex and valueForKey property..see whole example bellow..
UPDATE :
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"yourFileName" ofType:#"plist"];
NSArray *contentArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithArray:contentArray];
for (int i = 0; i< [yourArray count]; i++)
{
id object = [yourArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
yourLableWeight.text = [[objDict objectForKey:#"Weight"];// set index with your requirement
yourLableHeight.text = [[objDict objectForKey:#"Height"];
}
hope this help you...
When you enter credentials on login screen to check when it match the credentials with the fetched plist then pass that plist to the next controller. Do something like this
UserViewController *controller = [[UserViewController alloc] initWithNibName:#"UserViewController" bundel:nil];
[controller setUserDictionary:yourPlistDictionary];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
in UserViewController you would have a NSDictionary instance to store the data to show, hope that will help you

read and write using NSKeyedArchiver, ios

Below is a class to read and write data using nsarchive
Data.m
-(id)init {
self = [super init];
if(self) {
arr = [[NSMutableArray alloc] init];
}
return self;
}
-(NSString *)getPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath;
if ([paths count] > 0)
documentPath = [paths objectAtIndex:0];
NSString *draftDataPath = [documentPath stringByAppendingPathComponent:#"draftData.dat"];
return draftDataPath;
}
-(void)saveDataToDisk {
NSString *path = [self getPath];
[NSKeyedArchiver archiveRootObject:arr toFile:path];
}
-(void)loadDataFromDisk {
NSString *path = [self getPath];
self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
At later on, I am adding some objects into arr by doing
CustomerClass.m
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data.arr addObject:myObject1]
[data.arr addObject:myObject2]
[data.arr addObject:myObject3]
[data saveDataToDisk];
}
At DisplayData.m, I want to check data.arr by
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data loadDataFromDisk];
NSLog(#"length of array is %d",[data.arr count]);
}
On the console, I am getting
length of array is 1
I thought it should be 3 after all.
Please point out what I have just made a mistake in the middle of work if you have any clues about it.
So, I suspect that your "myObjects" are not NSCoding compliant. I just did this:
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
[arr addObject:#"Hello"];
[arr addObject:#" "];
[arr addObject:#"World"];
BOOL ret = [NSKeyedArchiver archiveRootObject:arr toFile:[self getPath]];
NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPath]];
NSLog(#"count = %d", [arr2 count]);
And the results was "count = 3"
I feel like there's too much code here to do what you're looking for. I think all you need is:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dataClass] forKey:NSUserDefaultString];
[[NSUserDefaults standardUserDefaults] synchronize];
to save it.
And:
NSData *someData = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultString];
if (settingsData != nil)
{
dataClass = [NSKeyedUnarchiver unarchiveObjectWithData:settingsData];
}
to retrieve it.

how to capture the required values from a URL

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
http://gmail.com?access_token=ab8w4azq2xv3dr4ab37vvzmh&token_type=bearer&expires_in=3600
How can I capture the value of the access_token which in this example is ab8w4azq2xv3dr4ab37vvzmh?
This code should do it:
- (NSString *)extractToken:(NSURL *)URL
{
NSString *urlString = [URL absoluteString];
NSRange start = [urlString rangeOfString:#"access_token="];
if (start.location != NSNotFound)
{
NSString *token = [urlString substringFromIndex:start.location+start.length];
NSRange end = [token rangeOfString:#"&"];
if (end.location != NSNotFound)
{
//trim off other parameters
token = [token substringToIndex:end.location];
}
return token;
}
//not found
return nil;
}
Alternatively, here is a more general solution that will extract all the query parameters into a dictionary:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([parts count] > 1)
{
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result setObject:value forKey:key];
}
}
return result;
}
Good Category for NSDictionary:
#import "NSDictionary+URL.h"
#implementation NSDictionary (URL)
+ (NSDictionary *)dictionaryWithUrlString:(NSString *)urlString{
NSRange urlRange = [urlString rangeOfString:#"?"];
if(urlRange.length>0){
urlString = [urlString substringFromIndex:urlRange.length+urlRange.location];
}
NSArray *pairsArray = [urlString componentsSeparatedByString:#"&"];
NSMutableDictionary *parametersDictionary = [[NSMutableDictionary alloc] initWithCapacity:[pairsArray count]];
for(NSString *pairString in pairsArray){
NSArray *valuesArray = [pairString componentsSeparatedByString:#"="];
if([valuesArray count]==2){
[parametersDictionary setValue:[valuesArray objectAtIndex:1] forKey:[valuesArray objectAtIndex:0]];
}
}
return [parametersDictionary autorelease];
}
#end
NSMutableDictionary *querycomponent = [[NSMutableDictionary alloc] init];
if (![query isEqualToString:#""]){
NSArray *queryArray = [query componentsSeparatedByString:#"&"];
for (NSString *subquery in queryArray){
NSArray *subqueryArray = [subquery componentsSeparatedByString:#"="];
NSString *key = [subqueryArray objectAtIndex:0];
NSString *val = [subqueryArray objectAtIndex:1];
[querycomponent setObject:val forKey:key];
}
NSLog(#"querycomponent %#",querycomponent);
}

How to sort files by modified date in iOS

I used NSFileManager to retrieve the files in a folder, and I want to sort them by modified date. How to do that ?
Thanks.
What have you tried so far?
I haven't done this, but a quick look at the docs makes me think that you should try the following:
Call -contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: and specify NSURLContentModificationDateKey as one of the keys.
You'll get back an array of NSURL objects which you can then sort using an NSArray method like -sortedArrayUsingComparator:.
Pass in a comparator block that looks up the modification date for each NSURL using -getResourceValue:forKey:error:.
Update: When I wrote the answer above, -getResourceValue:forKey:error: existed in iOS but didn't do anything. That method is now functional as of iOS 5. The following code will log an app's resource files followed by a list of corresponding modification dates:
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtURL:[[NSBundle mainBundle] resourceURL]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
options:nil
error:nil];
NSMutableArray *dates = [NSMutableArray array];
for (NSURL *f in files) {
NSDate *d = nil;
if ([f getResourceValue:&d forKey:NSURLContentModificationDateKey error:nil]) {
[dates addObject:d];
}
}
NSLog(#"Files: %#", files);
NSLog(#"Dates: %#", dates);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *originalImage = [[NSMutableArray alloc]init];
for (int i = 1; i < [imageFilenames count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[imageFilenames objectAtIndex:i] ];
}
//---------sorting image by date modified
NSArray* filelist_date_sorted;
filelist_date_sorted = [imageFilenames sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSDictionary* first_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:#"%#/%#", documentsDirectory, obj1] error:nil];
NSDate *first = [first_properties objectForKey:NSFileCreationDate];
NSDictionary *second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:#"%#/%#", documentsDirectory, obj2] error:nil];
NSDate *second = [second_properties objectForKey:NSFileCreationDate];
return [second compare:first];
}];
NSLog(#" Date sorted result is %#",filelist_date_sorted);
static static NSInteger contentsOfDirSort(NSString *left, NSString *right, void *ptr) {
(void)ptr;
struct stat finfo_l, r_finfo_r;
if(-1 == stat([left UTF8String], &finfo_l))
return NSOrderedSame;
if(-1 == stat([right UTF8String], &finfo_r))
return NSOrderedSame;
if(finfo_l.st_mtime < finfo_r.st_mtime)
return NSOrderedAscending;
if(finfo_l.st_mtime > finfo_r.st_mtime)
return NSOrderedDescending;
return NSOrderedSame;
}
Now, later on in your code.
NSMutableArray *mary = [NSMutableArray arrayWithArray:filePathsArray];
[mary sortUsingFunction:contentsOfDirSort context:nil];
// Use mary...
Quick Method:
-(void)dateModified
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
int num;
//-- Listing file name with modified dated
for (NSString *s in fileList)
{
NSString *filestring = [documentsDirectory stringByAppendingFormat:#"/%#",s];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:filestring error:nil];
NSString *modifiedDate = [filePathsArray1 objectForKey:NSFileModificationDate];
NSLog(#"\n Modified Day : %#", modifiedDate);
num=num+1;
}
}
In a category over NSFileManager:
static NSInteger contentsOfDirSort(NSURL *leftURL, NSURL *rightURL, void *ptr)
{
(void)ptr;
NSDate * dateLeft ;
[leftURL getResourceValue:&dateLeft
forKey:NSURLContentModificationDateKey
error:nil] ;
NSDate * dateRight ;
[rightURL getResourceValue:&dateRight
forKey:NSURLContentModificationDateKey
error:nil] ;
return [dateLeft compare:dateRight];
}
- (NSArray *)contentsOrderedByDateOfDirectoryAtPath:(NSURL *)URLOfFolder ;
{
NSArray *files = [self contentsOfDirectoryAtURL:URLOfFolder
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
options:0
error:nil];
return [files sortedArrayUsingFunction:contentsOfDirSort
context:nil] ;
}