Coredata fetching concept - ios

Hello i am just creating an sample project in which i have Login and signup class.i created a signup class with all textfields and registered it successfully with coredata.The problem is i need to get the registered user into login class to make it successfull into next page.i have to check whether the user exist or not in my Login class.
Signup.m
#implementation CoreSignup
#synthesize managesObjectContext=_managesObjectContext;
#synthesize managesObjectModel=_managesObjectModel;
#synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
#pragma mark Insert Row In CoreData
-(void)insertSignUpList:(NSMutableDictionary *)details_Ary
{
BOOL isInserted=[self insertRowForSignUp:[details_Ary valueForKey:#"Firstname"] Lastname:[details_Ary valueForKey:#"Lastname"] password:[details_Ary valueForKey:#"Password"] emailid:[details_Ary valueForKey:#"Emailid"] phoneNo:[details_Ary valueForKey:#"Phoneno"] city:[details_Ary valueForKey:#"City"]];
if (isInserted)
{
//inserted Successfully
NSLog(#"inserted Successfully");
}
}
-(BOOL)insertRowForSignUp:(NSString *)firstName Lastname:(NSString *)LastName password:(NSString *)password emailid:(NSString *)emailid phoneNo:(NSString *)phoneNo city:(NSString *)city{
AppDelegate *appDelegate =[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
SignUp *signUpInfo=[NSEntityDescription insertNewObjectForEntityForName:#"SignUp" inManagedObjectContext:context];
signUpInfo.firstName=firstName;
signUpInfo.lastName=LastName;
signUpInfo.password=password;
signUpInfo.phoneno=#([phoneNo intValue]);
signUpInfo.city=city;
signUpInfo.emailid=emailid;
NSError *error;
if (![context save:&error]) {
NSLog(#"Oops coudnt save");
return NO;
}
return YES;
}
-(NSMutableArray*)fetchAll{
AppDelegate *appDelegate =[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
NSEntityDescription *entity1=[NSEntityDescription entityForName:#"SignUp" inManagedObjectContext:context];
[request setEntity:entity1];
NSArray *emptyArray=[self.managesObjectContext executeFetchRequest:request error:nil];
NSMutableArray *AllHistory=[NSMutableArray new];
for (SignUp*signUpHistory in emptyArray) {
NSMutableDictionary *tempDict=[[NSMutableDictionary alloc]init];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.firstName] forKey:#"firstname"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.lastName] forKey:#"lastName"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.password] forKey:#"password"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.emailid] forKey:#"emailid"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.city] forKey:#"city"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.phoneno] forKey:#"phoneno"];
[AllHistory addObject:tempDict];
}
return AllHistory;
}
Login.m
#interface ViewController ()<UITextFieldDelegate>
#end
#implementation ViewController
#synthesize JJuser;
#synthesize JJpassword;
#synthesize managesObjectContext=_managesObjectContext;
#synthesize managesObjectModel=_managesObjectModel;
#synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self jjtext];
[self jjpass];
}
-(void)jjtext{
JJuser.delegate=self;
[JJuser enableMaterialPlaceHolder:YES];
}
-(void)jjpass{
JJpassword.delegate=self;
[JJpassword enableMaterialPlaceHolder:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSMutableArray*)fetchLogin{
AppDelegate *appDelegate =[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
NSEntityDescription *entity1=[NSEntityDescription entityForName:#"SignUp" inManagedObjectContext:context];
[request setEntity:entity1];
NSArray *emptyArray=[self.managesObjectContext executeFetchRequest:request error:nil];
NSMutableArray *AllHistory=[NSMutableArray new];
for (SignUp*signUpHistory in emptyArray) {
NSMutableDictionary *tempDict=[[NSMutableDictionary alloc]init];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.firstName] forKey:#"firstname"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.lastName] forKey:#"lastName"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.password] forKey:#"password"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.emailid] forKey:#"emailid"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.city] forKey:#"city"];
[tempDict setObject:[NSString stringWithFormat:#"%#",signUpHistory.phoneno] forKey:#"phoneno"];
[AllHistory addObject:tempDict];
}
return AllHistory;
}
- (IBAction)Login:(id)sender {
AppDelegate *appDelegate =[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSFetchRequest *FindIt=[[NSFetchRequest alloc]init];
NSEntityDescription *entity1=[NSEntityDescription entityForName:#"SignUp" inManagedObjectContext:context];
[FindIt setEntity:entity1];
NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"firstName = \"%#\"",FindIt]];
[FindIt setPredicate:pred];
NSUInteger count = [context countForFetchRequest:FindIt error:nil];
if (count == NSNotFound)
{
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:#"Hello" message:#"No Such id exist" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}else if (count == 1)
{
}
else{
}
}
- (IBAction)Signup:(id)sender
{
UIStoryboard *board = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SignUpViewController*SignUp = [board instantiateViewControllerWithIdentifier:#"SignUp"];
[self.navigationController pushViewController:SignUp animated:YES];
}
#end

You can use a Fetch Request for checking whether the user is already present and if present then if the passwords match
Try this and tell me if it works
-(BOOL)searchDatabaseForUser:(NSString *)username andPassword:(NSString *)password{
AppDelegate *appDelegate =[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"EntityName"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"username = %#",username];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if([result count]){
for (NSManagedObject *obj in result) {
if([[obj valueForKey:#"password"]isEqualToString:password]){
return YES;
}
}
return NO;
//passwords doesnt match even though username found
}
else {
return NO;
// No such Username found
}
}
Now call this method as to where you want to validate the user should to the next screen or not, Like this
Login.m
-(IBAction)someButtonToCheckLogin:(id)sender{
BOOL shouldUserLogin = [self searchDatabaseForUser:UserNameTextField.txt andPassword:passwordTextField.txt];
if(shouldUserLogin){
//navigate to the next screen.
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title of the application" message:#"Password mismatch, Please check again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
I guess this is pretty self explainable. Hope this helps you to understand.

Related

Store NSDictionary In CoreData ios not working

Since I get into a requirement of saving NSDictionary offline and populate the table from it when the user is offline.
This is the code I have so far:
Everytime the resulting NSDictionary was getting as nil
I have made this attribute set as transformable
+ (void) insertIntoCoredata :(NSString *) table : (NSString *) attribute : (NSArray *) dic {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dic];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:table
inManagedObjectContext:context];
[object setValue:myData forKey:attribute];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
}
+ (id) getFromCoredata :(NSString *) table : (NSString *) attribute {
AppDelegate *appDelegate =(AppDelegate*)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
appDelegate.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:table
inManagedObjectContext:context];
[fetch setEntity:entityDescription];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}
What went wrong with this code.

Getting Null Value From Database NSManagedObject

I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}

TableView not displaying Cell Content

I am Using core data as my data base. Inside my UITableView I have a button to add projects , But at this moment I only Use it to add names. But the names I add do not display on the tableview.
I think my problem is that I need to repopulate my projectArray, how and where do I do that.
Here is my code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_projectArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Project* project = _projectArray[indexPath.row];
static NSString *cellID = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
cell.textLabel.text = project.name;
cell.detailTextLabel.text = #"prooo";
self.tableView.delegate = self;
self.tableView.dataSource = self;
return cell;
}
Here is my button code:
- (IBAction)addProjectButton:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Enter new project name."
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
UITextField *textField = [alert textFieldAtIndex:0];
textField.placeholder = #"Project Name";
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != alertView.cancelButtonIndex) {
UITextField *field = [alertView textFieldAtIndex:0];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object =[NSEntityDescription insertNewObjectForEntityForName:#"Project" inManagedObjectContext:context];
[object setValue:field.text forKey:#"name"];
NSError *error;
[context save:&error];
if (![context save:&error]) {
NSLog(#"Whoops %# %#", error, [error localizedDescription]);
}
[self.tableView reloadData];
} else {
NSLog(#"cancel");
}
}
And here is my ViewWillAppear Code , where I fetch info:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:nil];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
//load project
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSError *error;
_projectArray = [context executeFetchRequest:fetch error:&error];
}
There are many things you can do. To make it a good code, I will suggest write a method that reloads your array. Like this
-(void) reloadArray
{
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
//load project
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSError *error;
_projectArray = [context executeFetchRequest:fetch error:&error];
}
Then replace your viewDidAppear like this -
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:nil];
[self reloadArray];
}
Also in your numberOfSectionsInTableView: method, make this change -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
[self reloadArray];
return 1;
}
And it should do the magic...
Have you set the dataSource and delegate properties of tableView?
self.tableView.delegate = self;
self.tableView.dataSource = self;
Change This :
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSError *error;
_projectArray = [context executeFetchRequest:fetch error:&error];
To:
_projectArray = [[NSMutableArray alloc]init];
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSManagedObject *object = nil;
NSError *error;
NSArray *result = [context executeFetchRequest:fetch error:&error];
for (int i = 0; i < [result count]; i ++) {
object = [result objectAtIndex:i];
[_projectArray setObject:[object valueForKey:#"name"]
}

issues with Searching in Core Data

I am using this piece of code to find the existance of data. But i am getting this error that Use of Undeclared Identifier "appDelegate".
- (IBAction)findContact:(id)sender {
CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Contacts"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(name = %#)",
_name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request
error:&error];
if ([objects count] == 0) {
_status.text = #"No matches";
} else {
matches = objects[0];
_address.text = [matches valueForKey:#"address"];
_phone.text = [matches valueForKey:#"phone"];
_status.text = [NSString stringWithFormat:
#"%lu matches found", (unsigned long)[objects count]];
}
}
I have included the #import <CoreData/CoreData.h> .Will I have to include some other file. When i save data it works fine.
Ensure you have imported the app delegate header
#import "CoreDataAppDelegate.h"
Try casting the AppDelegate as CoreDataAppDeleage
CoreDataAppDelegate *appDelegate = (CoreDataAppDelegate*)[[UIApplication sharedApplication] delegate];
CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
Replace above line to below line
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
For deleting text based on Id
#pragma mark - delete tracking details
- (void)deleteTrackingId:(NSString *)trackingId
{
appDelegate = [[UIApplication sharedApplication] delegate];
managedObjectContext = appDelegate.managedObjectContext;
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityOne = [NSEntityDescription entityForName:#"TrackingList" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entityOne];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"trackingId == %#",trackingId];
[fetchRequest setPredicate:predicate];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(#"Could not delete Entity Objects");
}
for (TrackingList *trackingObject in fetchedObjects) {
[managedObjectContext deleteObject:trackingObject];
}
[appDelegate saveContext];
}

Fetching UIImage from Core Data

I am using a Core Data to save a UIImage that i get from my UIImagePickerController (source type = image library). I then Place or rather want to place the photo in a UICollectionViewCell, Please help and check to see what I am doing wrong.
Here is my UIImagePickerController it is called by a delegate.
-(void)requestAddScreen {
_picker = [[UIImagePickerController alloc] init];
_picker.delegate = self;
_picker.allowsEditing = NO;
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:_picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSEntityDescription* entityDescription = [NSEntityDescription entityForName:#"Screen" inManagedObjectContext:context];
Screen* newScreen = [[Screen alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];
NSData *imageData = UIImagePNGRepresentation(image);
newScreen.image = imageData;
[_project addProjectScreensObject:newScreen];
NSError *error;
[context save:&error];
if (![context save:&error]) {
NSLog(#"Whoops %# %#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:_picker completion:^{
[_collectionView reloadData];
}];
}
And Here is my ViewWillAppear meted. this is where I fetch the data from Core Data, id it Correct?
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:nil];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
//load project
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", #"EMO-KIT"];
[fetch setPredicate:predicate];
NSError *error;
NSArray *array = [context executeFetchRequest:fetch error:&error];
if (array.count == 1) {
_project = array[0];
} else {
_project = [NSEntityDescription insertNewObjectForEntityForName:#"Project" inManagedObjectContext:context];
[_project setValue:#"EMO-KIT" forKey:#"name"];
}
NSArray* screens = [[_project projectScreens] array];
NSIndexPath *bottomIndexPath=[NSIndexPath indexPathForRow:screens.count inSection:0];
[self.collectionView scrollToItemAtIndexPath: bottomIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
}
You can convert UIImage to NSData and save into Core Data as below
Saving
NSData * imageData = UIImagePNGRepresentation(image);
[newsObj setValue:imageData forKey:#"Image"];
Retrieving
UIImage *image = [UIImage imageWithData:[screenObj valueForKey:#"Image"]];
Hope it helps you..

Resources