Parse.com saveInBackgroundWithBlock not getting called at all - parse-platform

saveInBackgroundWithBlock stopped working after I upgraded parse library. Please check the code below, this used to work before but not anymore. Am I doing something wrong here?
PFQuery* query = [PFQuery queryWithClassName: #"FoodDaily"];
[query whereKey: #"user_id" equalTo: [[PFUser currentUser] objectId]];
[query whereKey: #"date" equalTo: [dicItem valueForKey: #"date"]];
m_loadingView.hidden = NO;
[query findObjectsInBackgroundWithBlock:^(NSArray *result, NSError *error)
{
if(error)
{
NSLog(#"error");
m_loadingView.hidden = YES;
[[AppDelegate getDelegate] showMessage: NETWORK_DISCONNECT_ERROR];
return;
}
if (!error) {
NSLog(#"result: %#", result);
m_loadingView.hidden = YES;
PFObject* objRecord = [PFObject objectWithClassName:#"FoodDaily"];
if ([result count]>0) {
objRecord = [result objectAtIndex: 0];
}
[objRecord setObject: [dicItem valueForKey: #"breakfast_food"] forKey: #"breakfast_food"];
m_loadingView.hidden = NO;
[objRecord saveInBackgroundWithBlock: ^(BOOL succeeded, NSError* error)
{
if(succeeded)
{
m_loadingView.hidden = YES;
NSLog(#"Success Updating New Food Daily Item");
[self.navigationController popToViewController: [AppDelegate getDelegate].m_viewFoodDaily animated: YES];
}
else
{
m_loadingView.hidden = YES;
[[AppDelegate getDelegate] showMessage: NETWORK_DISCONNECT_ERROR];
NSLog(#"Failed Saving New Food Item");
}
}];
}
}];
In log I am only getting
result: (
)
which is by NSLog(#"result: %#", result); but nothing from saveInBackgroundWithBlock

Your problem is not with saveInBackgroundWithBlock but your query in findObjectsInBackgroundWithBlock is not fetching any result. Please run the same query on prase UI and check if your getting any result over there.

Related

Get UTI of NSPasteboardTypeFileURL

NSFilenamesPboardType got deprecated on 10.14 and the suggestion is to use NSPasteboardTypeFileURL. This gives me filename as
file:///.file/id=6571367.12885025918
and NSWorkspace is unable to get UTI out of it.
How to get UTI from NSPasteboardTypeFileURL?
Old code:
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
NSDragOperation resultingDragMask = NSDragOperationNone;
NSPasteboard *pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSFilenamesPboardType]) {
NSArray <NSString *>*list = [pboard propertyListForType:NSFilenamesPboardType];
NSString *firstItem = [list objectAtIndexedSubscript:0];
NSError *error;
NSString *UTI = [[NSWorkspace sharedWorkspace] typeOfFile:firstItem error:&error];
if (!error) {
if ([[NSImage imageTypes] containsObject:UTI]) {
resultingDragMask = NSDragOperationCopy;
}
}
} else if ([[pboard types] containsObject:NSPasteboardTypeTIFF]) {
resultingDragMask = NSDragOperationCopy;
}
if (sourceDragMask & NSDragOperationCopy && resultingDragMask & NSDragOperationCopy) {
return NSDragOperationCopy;
}
return NSDragOperationNone;
}
With NSPasteboardTypeFileURL I get error which states file doesn't exist. Dragged from pasteboard:
Printing description of error:
Error Domain=NSCocoaErrorDomain Code=260 "The file “id=6571367.12885025918” couldn’t be opened because there is no such
file." UserInfo={NSURL=file:/.file/id=6571367.12885025918 --
file:///Users/xxx/Library/Containers/com.xxx.imageviewfix/Data/,
NSFilePath=/Users/xxx/Library/Containers/com.xxx.imageviewfix/Data/file:/.file/id=6571367.12885025918,
NSUnderlyingError=0x600000c70d80 {Error Domain=NSPOSIXErrorDomain
Code=2 "No such file or directory"}}
I am late to this question but I found this works:
NSArray<Class> *classes = #[[NSURL class]];
NSDictionary *options = #{};
NSArray<NSURL*> *files = [pboard readObjectsForClasses:classes options:options];
for (NSURL *url in files)
{
NSString *str = [url path];
// TODO: do something with str.
}
Unlike the other answer, dropping multiple files works with this approach.
Getting path of NSURL object gets the original filename. The only thing missing is the array of file paths which NSFilenamesPboardType used to give.
NSString *fileURL = [[NSURL URLFromPasteboard:pboard] path];
Updated code:
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
NSDragOperation resultingDragMask = NSDragOperationNone;
NSPasteboard *pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSPasteboardTypeFileURL]) {
NSString *fileURL = [[NSURL URLFromPasteboard:pboard] path];
NSError *error;
NSString *UTI = [[NSWorkspace sharedWorkspace] typeOfFile:fileURL error:&error];
if (!error) {
if ([[NSImage imageTypes] containsObject:UTI]) {
resultingDragMask = NSDragOperationCopy;
}
}
} else if ([[pboard types] containsObject:NSPasteboardTypeTIFF]) {
resultingDragMask = NSDragOperationCopy;
}
if (sourceDragMask & NSDragOperationCopy && resultingDragMask & NSDragOperationCopy) {
return NSDragOperationCopy;
}
return NSDragOperationNone;
}

Error for request to endpoint 'me/feed': An open FBSession must be specified for calls to this endpoint

I know this question is posted many times but truly i didn't get any suggestion that can solve my problem. I wasted my two days on this problem but till now i didn't get any solutions. Please give your valuable guidance.
I want to post status on Facebook.
if ([PostType isEqual:#"article"])
{
[dict setObject:PostTitle forKey:#"message"];
params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
PostTitle, #"message", nil];
if (FBSession.activeSession.isOpen) {
// Yes, we are open, so lets make a request for user details so we can get the user name.
if ([[[FBSession activeSession] permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] requestNewPublishPermissions:[NSArray arrayWithObjects: #"publish_actions",nil] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
[self promptUserWithAccountName];
}];
}else{
[self promptUserWithAccountName];
}
// a custom method - see below:
} else {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
[self promptUserWithAccountName]; // a custom method - see below:
}
}];
}
Custom method:
-(void)promptUserWithAccountName {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error){
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"Photo Uploaded"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
} else {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Some error happened"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
}
}];
}
}];
}

saveInBackgroundWithBlock not calling the block when it finished working

I'm trying to do a simple chat in iOS with Obj-C, and when I press the "send" button, I save the object into Parse and I retrieve all the messages.
When it succeeds, I retrieve all the messages so the last one (mine) should be retrieved as well, but the last one never gets called. What should I do?
This is my code:
NSMutableArray *messagesArray;
- (IBAction)sendButtonTapped:(id)sender {
self.sendButton.enabled = false;
self.textField.enabled = false;
PFObject *objectChat = [PFObject objectWithClassName: #"ChatClass"];
objectChat[#"text"] = self.textField.text;
[objectChat saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
self.sendButton.enabled = true;
self.textField.enabled = true;
if (succeeded) {
self.textField.text = #"";
[self retrieveMessages];
NSLog(#"success!");
} else {
NSLog(error.description);
}
}];
}
-(void) retrieveMessages {
NSDate *now = [NSDate date];
PFQuery *query = [PFQuery queryWithClassName:#"ChatClass"];
[query whereKey:#"createdAt" lessThanOrEqualTo:now];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error == nil) {
messagesArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [objects count]; i++) {
[messagesArray addObject:[[objects objectAtIndex:i] objectForKey:#"text"]];
}
runOnMainQueueWithoutDeadlocking(^{
[self.messageTableView reloadData];
});
}
}];
}
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_async(dispatch_get_main_queue(), block);
}
}
Thank you very much in advance.
Regards.
Perhaps there's enough of a clock difference with the parse server that the time qualification misses the object just created. Removing that line should do the trick.

Using multiple imagepickers on one view

I have a working imagepicker that upon button click and hold gesture, allows the user to upload an image to the disk, and the user can change the image using the same gesture. The only issue is, however, I need this to be done twice on the same view (i.e. I have two imageviews, two buttons to change each of the imageviews, etc.), and I am stumped on how to get the second one to work. This is essentially what the view looks like:
Here is my current code:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//
// Saving into Documents folder
//
NSString* path = [NSHomeDirectory() stringByAppendingString:#"/Documents/first.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok) {
NSLog(#"Error creating file %#", path);
} else {
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(info [UIImagePickerControllerOriginalImage])];
[myFileHandle closeFile];
}
//
// Loading from documents
//
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
self.chosenImage = loadedImage;
[self.imageView setImage:self.chosenImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)onLongTile:(UILongPressGestureRecognizer *)gesture
{
switch ([gesture state]) {
case UIGestureRecognizerStateBegan:{
NSString *actionSheetTitle = #"Photo Options"; //Action Sheet Title
NSString *type = #"Upload Photo";
NSString *cancelTitle = #"Cancel";
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:actionSheetTitle
delegate:self
cancelButtonTitle:cancelTitle
destructiveButtonTitle:nil
otherButtonTitles:type, nil];
[actionSheet showInView:self.view]; }
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:#"Photo"]) {
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:self.imagePicker animated:YES completion:nil];
}
}
Updated code with tags:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if (self.imageViewOne.tag == 100)
{
//
// Saving into Documents folder
//
NSString* path = [NSHomeDirectory() stringByAppendingString:#"/Documents/one.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok) {
NSLog(#"Error creating file %#", path);
} else {
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(info [UIImagePickerControllerOriginalImage])];
[myFileHandle closeFile];
}
//
// Loading from documents
//
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
self.chosenImageOne = loadedImage;
[self.imageViewOne setImage:self.chosenImageOne];
[self dismissViewControllerAnimated:YES completion:nil];
}
if (self.imageViewTwo.tag == 200)
{
//
// Saving into Documents folder
//
NSString* path = [NSHomeDirectory() stringByAppendingString:#"/Documents/two.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok) {
NSLog(#"Error creating file %#", path);
} else {
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(info [UIImagePickerControllerOriginalImage])];
[myFileHandle closeFile];
}
//
// Loading from documents
//
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
self.chosenImageTwo = loadedImage;
[self.imageViewTwo setImage:self.chosenImageTwo];
[self dismissViewControllerAnimated:YES completion:nil];
}
}
From what I understood of the question, set tags to your UIImageView and change is accordingly. something like:
[self.imageViewOne setTag:100];
[self.imageViewTne setTag:200];
And then in your delegates you can check the tag value and do the needful:
if ( imageView.tag == 100)
{
// Code for first imageView
}

Change value of selected field from SQlite3 using Xcode

The purpose when I select a row from a tableView, having data loaded from sqlite, to be capable of changing the value of a certain field.
Manipulating through two views, the first one loads the entire database into a mutable array, and when I press a certain field, I go to another view. In this second view, I have a button. How to obtain the result of when pressing this button the field in the database will change value.
TableviewController know as AuthorVC.m
#import "AuthorVC.h"
#import "Author.h"
#import <sqlite3.h>
#import "SearchVC.h"
//#import "DetailViewController.h"
#import "Details.h"
#implementation AuthorVC
#synthesize theauthors;
#synthesize author;
NSString *authorNAme;
NSString *authorNAme2;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{ searchBar.delegate = (id)self;
[self authorList];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[searchBar release];
searchBar = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Author* author in theauthors)
{ //[NSPredicate predicateWithFormat:#"SELECT * from books where title LIKE %#", searchBar.text];
NSRange nameRange = [author.name rangeOfString:text options:NSAnchoredSearch];
NSRange descriptionRange = [author.genre rangeOfString:text options:NSAnchoredSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:author];
}
}
}
[self.tableView reloadData];
}
/*
-(void) showDetailsForIndexPath:(NSIndexPath*)indexPath
{
NSLog(#"This is the showDetailsForIndexPath");
[self->searchBar resignFirstResponder];
Details* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"Details"];
AuthorVC* author;
if(isFiltered)
{
author = [filteredTableData objectAtIndex:indexPath.row];
}
else
{
author = [theauthors objectAtIndex:indexPath.row];
}
vc.author = author;
[self.navigationController pushViewController:vc animated:true];
NSLog(author);
}
*/
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self->isFiltered)
rowCount = filteredTableData.count;
else
rowCount = theauthors.count;
return rowCount;
// Return the number of rows in the section.
//return [self.theauthors count];
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
// NSString *Title;
// Author *auth = (Author*)segue.destinationViewController;
Details *dv = (Details*)segue.destinationViewController;
dv.labelText.text = author.title;
NSLog(#"Did Enter prepareForSegue");
// labelText.text = #"Hy";
}
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"This is the one in authorVc");
static NSString *CellIdentifier = #"AuthorsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int rowCount = indexPath.row;
Author *author = [self.theauthors objectAtIndex:rowCount];
if(isFiltered){
author = [filteredTableData objectAtIndex:indexPath.row];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Filtered" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
}
else{
author = [theauthors objectAtIndex:indexPath.row];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Not filtered" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
}
cell.textLabel.text = author.name;
// cell.detailTextLabel.text = author.genre;
//NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",author.name] autorelease];
return cell;
}
-(NSMutableArray *) authorList{
theauthors = [[NSMutableArray alloc] initWithCapacity:1000000];
NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000];
// authorNAme = theauthors.sortedArrayHint.description;
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Author * author = [[Author alloc] init];
//NSString *authorName = author.name;
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,4)];
author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 6)];
new2 = author.genre;
// NSLog(new2);
authorNAme=author.genre;
//NSLog(author.genre);
[theauthors addObject:author];
}
// authorNAme = author.genre;
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
sqlite3_close(db);
// authorNAme = Nil;
return theauthors;
}
}
- (void)dealloc {
[searchBar release];
[super dealloc];
//[authorNAme release];
}
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//
// /*
// When a row is selected, the segue creates the detail view controller as the destination.
// Set the detail view controller's detail item to the item associated with the selected row.
// */
// if ([[segue identifier] isEqualToString:#"ShowSelectedPlay"]) {
//
// NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
// Details *detailViewController = [segue destinationViewController];
// detailViewController.author = [dataController objectInListAtIndex:selectedRowIndex.row];
// }
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"This is the showDetailsForIndexPath");
[self->searchBar resignFirstResponder];
Details* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"Details"];
AuthorVC* author;
if(isFiltered)
{
author = [filteredTableData objectAtIndex:indexPath.row];
}
else
{
author = [theauthors objectAtIndex:indexPath.row];
}
vc.author = author;
authorNAme = vc.author.genre;
authorNAme2 = vc.author.name ;
NSLog(#"This is the details %#",vc.author.genre);
NSLog(#"This is the authorNAme Variable %#" , authorNAme);
vc.labelText.text = vc.author.genre;
vc.text2.text = vc.author.name;
NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",indexPath.row] autorelease];
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:authorNAme2 delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[messageAlert show];
[self.navigationController pushViewController:vc animated:true];
/*
//Get the selected country
NSString *selectedAuthors = [theauthors objectAtIndex:indexPath.row];
//NSLog(selectedAuthors);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
Details *dvController = [storyboard instantiateViewControllerWithIdentifier:#"Details"]; //Or whatever identifier you have defined in your storyboard
//authorNAme = selectedAuthors.description;
//Initialize the detail view controller and display it.
//Details *dvController = [[Details alloc] init/*WithNibName:#"Details" bundle:nil*///];
/*
dvController.selectedAuthors = selectedAuthors;
NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",indexPath.row] autorelease];
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[messageAlert show];*/
// NSString *elem = [new2 objectAtIndex:0];
//NSLog(dvController.labelText.text);
// NSString *titleString = [[[NSString alloc] initWithFormat:#"Author title : %d",indexPath.row] autorelease];
// NSString *titleString2 = [[new2 objectAtIndex:indexPath.row] autorelease];
// NSLog(#"this is the selected row , %s",titleString2);
// authorNAme = titleString;
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BReak point of SQL Query!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/*
#try {
NSFileManager *fileMgr2 = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
NSString *dbPath2 = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
BOOL success = [fileMgr2 fileExistsAtPath:dbPath2];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath2);
}
if(!(sqlite3_open([dbPath2 UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
NSLog(#"access to the second DB is ok");
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql2 = "SELECT field7 FROM Sheet1 WHERE field1 = 'titleString' ";
//NSLog(sql2);
sqlite3_stmt *sqlStatement2;
if(sqlite3_prepare(db, sql2, -1, &sqlStatement2, NULL) != SQLITE_OK)
{ NSLog(#"Problem with prepare the db");
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
// while (sqlite3_step(sqlStatement2)==SQLITE_ACCESS_EXISTS) {
NSLog(#"Starting to prepare the result");
Author * author2 = [[Author alloc] init];
NSLog(#"Author 2 created");
author2.genre2 = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement2, 7 )];
NSLog(#"Initialistion of author 2 is ok");
// NSLog(author2.genre);
// authorNAme = author2.genre;
[theauthors addObject:author2];
// }
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
sqlite3_close(db);
// authorNAme = Nil;
return theauthors;
}
*/
//[self.navigationController pushViewController:dvController animated:YES];
}
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
//return UITableViewCellAccessoryDetailDisclosureButton;
return UITableViewCellAccessoryDisclosureIndicator;
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}
#end
DetailsView controller know as Details.m :
//
// Details.m
// AuthorsApp
//
// Created by georges ouyoun on 7/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "Details.h"
#import "Author.h"
#import "AuthorVC.h"
#import <sqlite3.h>
#interface Details ()
#end
#implementation Details
#synthesize Favo;
#synthesize text2;
#synthesize labelText;
#synthesize selectedAuthors;
#synthesize author , infoRequest;
BOOL PAss = NO;
BOOL SElected2 = NO;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// authorNAme = author.genre;
// self.labelText.text =authorNAme;
// Do any additional setup after loading the view.
self.labelText.text = authorNAme;
self.text2.text = authorNAme2;
/* This is where the label text APPearsssssssss */
NSLog(#"Everything is ok now !");
// NSLog(authorNAme);
}
- (void)viewDidUnload
{
// [self setLabelText:nil];
NSLog(#"U have entered view did unload");
[AddBut release];
AddBut = nil;
[self setText2:nil];
[super viewDidUnload];
[self setLabelText:Nil];
[authorNAme release];
// Release any retained subviews of the main view.
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"AuthorsCell"]) {
[segue.destinationViewController setLabelText:author.title];
}
}
*/
-(void)viewWillAppear:(BOOL)animated
{
//labelText.text = authorNAme;
NSLog(#"U have entered the viewWillAppear tag");
// detailsLabel.text = food.description;
//authorNAme=Nil;
//[self setauthorName:Nil];
}
/*
-(void) viewDidAppear:(BOOL)animated{
labelText.text = #"This is the DidAppearTag";
NSLog(#"U have entered the viewDidAppear tag");
}
*/
-(void) viewWillDisappear:(BOOL)animated{
NSLog(#"This is the view will disappear tag");
//authorNAme.release;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)dealloc {
[labelText release];
[AddBut release];
[text2 release];
[super dealloc];
}
- (IBAction)AddButClick:(UIButton *)sender {
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateSelected];
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateHighlighted];
Favo = [[NSMutableArray alloc] initWithCapacity:1000000];
NSLog(authorNAme);
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
NSLog(#"Successfully selected from database");
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
NSLog(#"Got in the else tag");
while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) {
NSLog(#"Got in the while tag");
Author * author = [[Author alloc] init];
NSLog(#"Author initialized");
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)];
NSLog(#"Initialization ok");
// NSLog(author.name);
if(/*author.name == #"NO" &&*/ HighLighted == NO){
//const char *sql2 = "INSERT INTO Sheet1 ";
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateNormal];
NSLog(#"We have not selected it as fav yet");
// [AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was NOt highlighted and now is");
HighLighted = YES;
// PAss = YES;
// [self release];
break;
}
else
{
NSLog(#"We have selected it as fav");
[AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
[AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was highlighted and now is NOt");
HighLighted = NO;
break;
// [self viewDidLoad];
// PAss = YES;
}
// [Favo release];
// NSLog(Favo);
// author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
// [theauthors addObject:author];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);
sqlite3_close(db);
return Favo;
}
// [AddBut setSelected:YES];
// if(SElected == YES){
// NSLog(#"The button was highlighted and now not");
//
// [AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
// [AddBut setSelected:NO]; //btn changes to highlighted åstate
// SElected = NO;
//
// }
//
// else{
//
// [AddBut setSelected:YES]; //btn changes to normal state
// NSLog(#"The button was NOt highlighted and now is");
// SElected = YES;
//
// }
}
#end
First you have to take the values of selected row;
This is in your TABLEVIEWCONTROLLER
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
if(listObject.count!=0){
//you will get the object from the list
ObjectType *selectedObject=(ObjectType*)[listObject objectAtIndex:indexPath.row];
//you can call your view controller (in my example init with nib)
yourDetailViewController = [[YourDetailViewController alloc] initWithNibName:#"YourDetailViewControllerNib" bundle:nil];
//you can set your selected object in order to use it on your detail view controller
yourDetailViewController.objectSelected = selectedObject;
[self.navigationController yourDetailViewController animated:YES];
}
}
And this is in your DETAILVIEWCONTROLLER;
-(void)objectUpdate:(Object*)selectedObject withDBPath:(NSString *)dbPath{
NSError *errMsg;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql_stmt = [#"CREATE TABLE IF NOT EXISTS iosobjecttable (yourcolumns INTEGER PRIMARY KEY NOT NULL , youranothercolumn VARCHAR)" cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_exec(database, sql_stmt, NULL, NULL, (__bridge void*)errMsg) == SQLITE_OK)
{
// SQL statement execution succeeded
}
if(updateStmt == nil) {
NSString *querySQL = [NSString stringWithFormat:
#"update iosobject set youranothercolumn=%# where p_event_id=%#", object.changedcomlumn,object.objectid];
const char *query_sql = [querySQL UTF8String];
if(sqlite3_prepare_v2(database, query_sql, -1, &updateStmt, NULL) != SQLITE_OK){
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
//NSLog(#"%#",errMsg);
}
}
#try {
if(SQLITE_DONE != sqlite3_step(updateStmt)){
NSAssert1(0, #"Error while updating data. '%s'", sqlite3_errmsg(database));
//NSLog(#"%#",errMsg);
}
else{
//NSLog(#"updatingupdatingedelementt %#",tEvent.eventid);
}
sqlite3_reset(updateStmt);
}
#catch (NSException* ex) {
//NSLog(#"Error while updating data. '%s'", sqlite3_errmsg(database));
}
}
}
and how you call this function is like this;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *dbPath=[appDelegate getDBPath];
[self objectUpdate:objectUpdate withDBPath:dbPath];
And in app delegate you have to write getDBPath in app delegate;
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"yourdbname.sqlite"];
}

Resources