Some questions about fetch core data - ios

I'm a new guy with iOS, I made an APP and used Core Data.I could save data in Entity,but I can't fetch it.It's worry grammar or other reason.
I want to fetch data and show in TableViewCell
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:SectionsTableIdentifier];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:#"Entity"];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"showName" ascending:NO];
request.sortDescriptors = #[sort];
request.fetchLimit = 100;
request.fetchOffset= 0;
NSError *error = nil;
NSArray *array = [self.context executeFetchRequest:request error:&error];
NSMutableDictionary *names = [NSMutableDictionary dictionaryWithCapacity:1];
if(!error){
for (Entity *emp in array ) {
NSLog(#"output:%#",emp.showName);
names =[NSMutableDictionary dictionaryWithObjectsAndKeys:emp.showName, nil];
self.keys =[[self.names allKeys]sortedArrayUsingSelector:#selector(compare:)];
}
}
else{
NSLog(#"%#",error);
}
}
and this is my code with save data
-(IBAction)addButton:(id)sender{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSInteger seasonRow = [self.dataPicker selectedRowInComponent:kSeason];
NSInteger episodeRow = [self.dataPicker selectedRowInComponent:kEpisode];
Entity * tvShow1 =[NSEntityDescription insertNewObjectForEntityForName:#"Entity"
inManagedObjectContext:context];
NSError * error = nil;
NSString *name = self.nameField.text;
NSString *introduction = self.introductionField.text;
NSString *dateSeason = self.seasonNumber[seasonRow];
NSString *dateEposide = self.episodeNumber[episodeRow];
NSString *date;
date = [dateSeason stringByAppendingString:dateEposide];
tvShow1.showName =name;
tvShow1.showIntroduction = introduction;
tvShow1.showLastedData = date;
if (!error) {
NSLog(#"保存成功");
NSString *message = [[NSString alloc]initWithFormat:#"你的新剧:%#已经成功添加",name];
UIAlertController *alert=
[UIAlertController alertControllerWithTitle:#"恭喜,添加成功"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"好嘞!"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
[self.contenxt save:&error];
}
[appDelegate saveContext];
}
Thank you very much!

Related

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"]
}

Download data from JSON and store to CoreData and Display in the same time when data downloads in background

I am parsing data from JSON and Storing to CoreData in the same time i am displaying the the data to tableview but the problem i am having is data is displaying only after download completed but i dont want like this i want to download the data in background and display the data while downloading is processed also how can i do this
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
arrayData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSError *error;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
context = [appDelegate managedObjectContext];
for (int i = 0; i < [arrayData count]; i++) {
idNum = [arrayData objectAtIndex:i][#"id"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Discount"];
[request setPredicate:[NSPredicate predicateWithFormat:#"cID = %#",idNum]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound) {
NSLog(#"ERROR");
}else if (count == 0) {
NSLog(#"New Data Coming");
name = [arrayData objectAtIndex:i][#"name"];
summary = [arrayData objectAtIndex:i][#"summary"];
region = [arrayData objectAtIndex:i][#"region"];
imageURL = [arrayData objectAtIndex:i][#"images"][#"logo"];
id benefits1 = [arrayData objectAtIndex:i][#"benefits"];
benefiteString = [NSString stringWithFormat:#"%# %#",[benefits1 objectAtIndex:0][#"key"],[benefits1 objectAtIndex:0][#"value"]];
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
dateUpdate = [arrayData objectAtIndex:i][#"updated_at"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat: #"yyyy-MM-dd'T'HH:mm:ss.sssZ"];
NSDate *date =[dateFormatter dateFromString:dateUpdate];
[dateFormatter setDateFormat:#"yyyy/MM/dd HH:mm:ss"];
NSLog(#"DAte : %#",date);
Discount * d = [NSEntityDescription insertNewObjectForEntityForName:#"Discount" inManagedObjectContext:context];
d.name = name;
d.summary = summary;
d.regions = region;
d.cID = idNum;
d.imageLogo = data;
d.updated_at = date;
d.benefits = benefiteString;
if (![context save:&error]) {
NSLog(#"Getting error while saving data");
}
else{
NSLog(#"Saved");
}
}
}
[sharedAppDelegate dismissGlobalHUD];
[listTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_myArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCellClass = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (customCellClass == nil)
{
customCellClass = [[CellCustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
customCellClass.nameLabel.text = [[_myArray objectAtIndex:indexPath.row]name];
customCellClass.cityLabel.text =[[_myArray objectAtIndex:indexPath.row]regions];
customCellClass.detailLabel.text = [[_myArray objectAtIndex:indexPath.row]summary];
NSData * d = [[_myArray objectAtIndex:indexPath.row]imageLogo];
customCellClass.mainImage.image = [UIImage imageWithData:d];
customCellClass.benefitsLabel.text = [[_myArray objectAtIndex:indexPath.row]benefits];
[sharedAppDelegate dismissGlobalHUD];
return customCellClass;
}
-(void)dataDidSave
{
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Discount" inManagedObjectContext:context]; [fetchRequest setEntity:entity];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
self.myArray = result;
[listTableView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
[sharedAppDelegate showGlobalProgressHUDWithTitle:#"Loading..."];
[self dataDidSave];
}
In connectionDidFinishLoading: try something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
// Process your data and then incrementally call
dispatch_async(dispatch_get_main_queue(),^ {
[listTableView reloadData];
});
}
});

Registert New User to Openfire server using XMPP in iOS

I am trying to register a new user to an open fire WITHOUT using inbound registration, also some other settings are:
bool allowSelfSignedCertificates = NO; bool allowSSLHostNameMismatch = NO; bool useSSL = NO. I sow a few examples on stackoverflow but none of them was good for me or I didn't grasp the concept...
Here is my code:
-> .h file:
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "XMPP.h"
#import "XMPPRoster.h"
#interface SignUpViewController : UIViewController <UITextFieldDelegate, UIApplicationDelegate, XMPPRosterDelegate, XMPPStreamDelegate>
{
XMPPStream *xmppStream;
}
#property (nonatomic, strong, readonly) XMPPStream *xmppStream;
#end
-> .m file
- (void)signUpButtonFunction{
NSLog(#"SignUp function");
[[self xmppStream] setHostName:#"IP_ADDRESS"];
[[self xmppStream] setHostPort:5222];
XMPPJID *jid=[XMPPJID jidWithString:emailTextField.text];
[[self xmppStream] setMyJID:jid];
[[self xmppStream] connectWithTimeout:3.0 error:nil];
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:[NSXMLElement elementWithName:#"username" stringValue:#"venkat"]];
[elements addObject:[NSXMLElement elementWithName:#"password" stringValue:#"dfds"]];
[elements addObject:[NSXMLElement elementWithName:#"name" stringValue:#"eref defg"]];
[elements addObject:[NSXMLElement elementWithName:#"email" stringValue:#"abc#bbc.com"]];
[ xmppStream registerWithElements:elements error:nil];
}
//server connect delegate methods are not working at least it doesn't enter in them
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration" message:#"Registration Successful!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
DDXMLElement *errorXML = [error elementForName:#"error"];
NSString *errorCode = [[errorXML attributeForName:#"code"] stringValue];
NSString *regError = [NSString stringWithFormat:#"ERROR :- %#",error.description];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration Failed!" message:regError delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
if([errorCode isEqualToString:#"409"]){
[alert setMessage:#"Username Already Exists!"];
}
[alert show];
}
These is the library that I am using:
git library
and also I want to point out that my code is not entering the delegate methods
UPDATE:
changed the signUpButtonFunction to:
xmppStream = [[XMPPStream alloc] init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[[self xmppStream] setHostName:#"IP_ADDRESS"];
[[self xmppStream] setHostPort:5222];
[[self xmppStream] setMyJID:[XMPPJID jidWithString:#"abc#newrosoft.com"]];
[[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:nil];
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:[NSXMLElement elementWithName:#"username" stringValue:#"username"]];
[elements addObject:[NSXMLElement elementWithName:#"password" stringValue:#"password"]];
[elements addObject:[NSXMLElement elementWithName:#"name" stringValue:#"eref defg"]];
[elements addObject:[NSXMLElement elementWithName:#"email" stringValue:#"abc#newrosoft.com"]];
[ xmppStream registerWithElements:elements error:nil];
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"%#",error);
And I get the error:
Error Domain=XMPPStreamErrorDomain Code=1 "Attempting to connect while already connected or connecting." UserInfo=0x7fdc2af1f1c0 {NSLocalizedDescription=Attempting to connect while already connected or connecting.}
And if I comment the line:
[ xmppStream registerWithElements:elements error:nil];
then the error disappears, but it stills doesn't enter the delegate methods.
So, after search on the matter I found out that on the openFire can be installed a plugin that allows normal registration, so I have implemented the next method for the registration:
NSString *urlToCall = #"http://MyIP:9090/plugins/userService/userservice?type=add&secret=BigSecretKey&username=testUser&password=testPass&name=testName&email=test#gmail.com";
NSURL *url = [NSURL URLWithString:urlToCall];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"GET"];
NSError *error = nil;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if ([responseString isEqual: #"<result>ok</result>\r\n"]) {
NSLog(#"user created");
} else {
NSLog( #"user NOT created");
NSLog(#"%#",responseString);
}
#Laur Stefan
First Download New Demo From https://github.com/robbiehanson/XMPPFramework
Then
in - (void)goOnline Change
#warning Set here Server Name...
if([domain isEqualToString:#"rakeshs-mac-mini.local"])
{
NSXMLElement *priority = [NSXMLElement elementWithName:#"priority" stringValue:#"24"];
[presence addChild:priority];
}
Then
in - (BOOL)connect Method..
#warning Set Username as username#servername
myJID = [NSString stringWithFormat:#"%##rakeshs-Mac-mini.local",myJID];
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSLog(#"username: %#,Password : %#",myJID,myPassword);
After Connection to YOur Server From OpenFire ,
You can Got Response From Below Method.
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
//Try Above tested Code, if any problem tell us..
//this method is used at Sing UP view controller
-(BOOL)createNewAccountForXmppWithUserName:(NSString*)userNameJID andPassword:(NSString*)userPassword{
if (userNameJID == nil || userPassword == nil) {
return NO;
}
NSString *domain = #"abc.com";
self.xmppStream.hostName = domain;
int port = 5222;
self.xmppStream.hostPort = port;
useSSL = NO;
customCertEvaluation = NO;
NSString * userName = [NSString stringWithFormat:#"%##abc.com",userNameJID];
XMPPJID *jid = [XMPPJID jidWithString:userName resource:nil];
self.xmppStream.myJID = jid;
NSError *error = nil;
BOOL success;
success = [[self xmppStream] registerWithPassword:password error:&error];
if(![[self xmppStream] isConnected])
{
if (useSSL)
success = [[self xmppStream] oldSchoolSecureConnectWithTimeout:XMPPStreamTimeoutNone error:&error];
else
success = [[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:&error];
password = userPassword;
success = [[self xmppStream] registerWithPassword:password error:&error];
}
else
{
password = userPassword;
success = [[self xmppStream] registerWithPassword:password error:&error];
}
if (success)
{
isRegistering = YES;
NSLog(#"Successfully Register on XMPP Server");
}
return YES;
}
To show online/offline status we have to implement "NSFetchedResultsControllerDelegate"
#interface AKSMessageViewController : UIViewController<UITableViewDataSource,UITableViewDelegate, NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
}
And implement
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
//remove previous data or clear array
[[self xmppUserArray] removeAllObjects];
[[[AKSGetCareerGlobalClass SharedInstance] onlineUserArray] removeAllObjects];
//get data from core data
self.xmppUserArray=[[[self fetchedResultsController] fetchedObjects] mutableCopy];
for (int i=0; i<[[self xmppUserArray] count]; i++) {
if ([[[[self xmppUserArray] objectAtIndex:i] valueForKey:#"sectionNum"] integerValue]==0) {
//this is user is online
[[[AKSGetCareerGlobalClass SharedInstance] onlineUserArray] addObject:[[[self xmppUserArray] objectAtIndex:i] valueForKey:#"nickname"]];
}
}
[[self msgTableView] reloadData];
}
//And
#pragma mark NSFetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPUserCoreDataStorageObject"
inManagedObjectContext:moc];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
//NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
//NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:#"userJID"];
//NSLog(#"My JID ====>%#",myJID);
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subscription=='both'"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:#"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(#"Error performing fetch: %#", error);
}
}
return fetchedResultsController;
}

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..

I want to call alert view first then go to further NSManagedObject

I am trying to call alert view first then go to NSManagedObject. But when i click on button then it skip alert view and call this at the end of rest code.
Any one know's how can i force this uialertview to load first
Thanks
- (IBAction)confirmOrder:(UIButton *)sender
{
#pragma PopUp Alert Box
_alert = [MLTableAlert tableAlertWithTitle:#"Select Your Table" cancelButtonTitle:nil numberOfRows:^NSInteger (NSInteger section)
{
return 6;
}
andCells:^UITableViewCell* (MLTableAlert *anAlert, NSIndexPath *indexPath)
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [anAlert.table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = [NSString stringWithFormat:#"Table # %d", indexPath.row];
return cell;
}];
[_alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
NSLog(#"Index is = %d", selectedIndex.row);
selectedTable = [NSString stringWithFormat:#"%d",selectedIndex.row];
#pragma Hit Url For New Order
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"Got udid from appdelegate = %#",appDelegate.passUdid);
NSString *new_order = [NSString stringWithFormat: #"http://localhost/food/submit_new_order.php?id=NULL&customer_id=%#&table_id=%#&order_datetime=%#&customer_instruction=Normal&estimated_time_min=30-45&actual_time=40&created_on=%#&updated_on=NULL&STATUS=new", appDelegate.passUdid,selectedTable,dateStr,dateStr];
NSString* urlTextEscaped = [new_order stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlTextEscaped];
NSData *myNSData=[NSData dataWithContentsOfURL:url];
} andCompletionBlock:^{
NSLog(#"Cancel Button Pressed\nNo Cells Selected");
}];
_alert.height = 260;
[_alert show];
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"PendingOrder" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
//e
if (![selectedTable isEqualToString:NULL]) {
for (NSManagedObject *info in fetchedObjects) {
NSMutableString *pDishID = [info valueForKey:#"dishid"];
NSMutableString *pDishQuantity = [info valueForKey:#"quantity"];
NSMutableString *time = [info valueForKey:#"time"];
NSManagedObject *newDevices = [NSEntityDescription insertNewObjectForEntityForName:#"RunningOrder" inManagedObjectContext:context];
[newDevices setValue:pDishID forKey:#"dishid"];
[newDevices setValue:pDishQuantity forKey:#"quantity"];
[newDevices setValue:time forKey:#"time"];
NSLog(#"Getting ID From pending Order = %#",[info valueForKey:#"dishid"]);
#pragma Get Order ID from Order_Main
//s
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *ordrMain=#"http://localhost/food/get_order_id.php?id=";
ordrMain = [ordrMain stringByAppendingString:appDelegate.passUdid];
NSURL *urls=[NSURL URLWithString:ordrMain];
NSData *myNSData=[NSData dataWithContentsOfURL:urls];
allItemss = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:myNSData options:NSJSONReadingMutableContainers error:nil];
NSString *get_order_id = [[allItemss objectAtIndex:0] objectForKey:#"id"];
NSString *new_order_detail = [NSString stringWithFormat: #"http://localhost/food/order_detail.php?order_id=%#&dish_id=%#&quantity=%#&created_on=%#&updated_on=%#", get_order_id,pDishID,pDishQuantity,dateStr,dateStr];
NSString* urlTextEscaped = [new_order_detail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlTextEscaped];
NSData *myNSDatas=[NSData dataWithContentsOfURL:url];
[context deleteObject:info];
}
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
[_alert show] displays the alert window and returns immediately. The "selection block"
is then called when an alert item has been pressed, or the "cancel block" is called
when the Cancel button has been pressed.
Therefore you have to move the code that fetches the managed object into the "selection block":
[_alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
NSLog(#"Index is = %d", selectedIndex.row);
// ...
// Fetch object depending on selectedIndex.
// ...
} andCompletionBlock:^{
NSLog(#"Cancel Button Pressed\nNo Cells Selected");
}];

Resources