Core Data Part 2: Update, Delete Managed Objects and View Raw SQL Statement
This is the second article for our Core Data series. Previously, we gave you a brief introduction of Core Data and created a simple app to store all your device information. However, we only showed you how to insert records into data store through Core Data API and left out the update & delete operations.
In this tutorial, we’ll continue to work on the app and focus on the following areas of Core Data:
- Updating or deleting an object using Core Data API
- Viewing the raw SQL statement for debugging purpose
Updating or Delete an Object using Core Data
In the last tutorial, we already discussed how to fetch and save a managed object using Core Data API. So how can you update or delete an existing managed object from database?
Deleting an Object
Let’s talk about the delete operation first. To allow user to delete a record from the table view, as you know, we can simply implement the “canEditRowAtIndexPath” and “commitEditingStyle” methods. Add the following code to the DeviceViewController.m:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSManagedObjectContext *context = [self managedObjectContext]; if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete object from database [context deleteObject:[self.devices objectAtIndex:indexPath.row]]; NSError *error = nil; if (![context save:&error]) { NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); return; } // Remove device from table view [self.devices removeObjectAtIndex:indexPath.row]; [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } |
We’ll not go into the details about how to remove a row from table view as we’ve already covered in our earlier tutorial. Let’s focus on the code of commitEditingStyle method for deleting the managed object from database.
Like saving data, we first grab the manage object context. The context provides a method called “deleteObject” that allows you to delete the specific object from database. Lastly, we invoke the “save” method to commit the change. Following the removal of the object from database, we also remove the record from the table view.
Now, let’s run the app and try to remove a record from database. Your app should look similar to the following:

Delete a device from database
Updating an Object
Next, we’ll enhance the app to let user update the device information. Go to the Storyboard and add a new segue for the table cell. This segue is used to connect a table cell and the detail view controller. When user selects any device in the table view, the detail view controller will be displayed to show the information of the selected device.

Add a new segue for updating device
To differentiate the segue from the one for adding a new device, we set an identifier as “UpdateDevice”. Next, add the prepareForSegue method in DeviceViewController.m:
1 2 3 4 5 6 7 8 |
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"UpdateDevice"]) { NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]]; DeviceDetailViewController *destViewController = segue.destinationViewController; destViewController.device = selectedDevice; } } |
When user selects a specific device in the table view, it’ll go through the “UpdateDevice” segue. We then retrieve the selected device and pass it to the detail view controller.
Next, add a new properties in the DeviceDetailViewController.h for saving the selected device:
1 |
@property (strong) NSManagedObject *device; |
As always, add the synthesis statement in the DeviceDetailViewController.m:
1 2 |
@implementation DeviceDetailViewController @synthesize device; |
To display the information of the selected device, we have to change the “viewDidLoad” method:
1 2 3 4 5 6 7 8 9 10 11 |
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. if (self.device) { [self.nameTextField setText:[self.device valueForKey:@"name"]]; [self.versionTextField setText:[self.device valueForKey:@"version"]]; [self.companyTextField setText:[self.device valueForKey:@"company"]]; } } |
Let’s stop here and try to run the app again. As your app launches, tap any of the device records and the device information should appear in the detail view.

Display Detailed Device Information
However, the app is not finished yet. If you try to edit the information of an existing device, it will not update the device information properly. Go back to the DeviceDetailViewController.m and modify the “save:” method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
- (IBAction)save:(id)sender { NSManagedObjectContext *context = [self managedObjectContext]; if (self.device) { // Update existing device [self.device setValue:self.nameTextField.text forKey:@"name"]; [self.device setValue:self.versionTextField.text forKey:@"version"]; [self.device setValue:self.companyTextField.text forKey:@"company"]; } else { // Create a new device NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context]; [newDevice setValue:self.nameTextField.text forKey:@"name"]; [newDevice setValue:self.versionTextField.text forKey:@"version"]; [newDevice setValue:self.companyTextField.text forKey:@"company"]; } NSError *error = nil; // Save the object to persistent store if (![context save:&error]) { NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]); } [self dismissViewControllerAnimated:YES completion:nil]; } |
We’ll update the device information if any of the devices is selected. If there is no selected device, we’ll then create a new device and add it into the database.
Try to test the app again. The update feature should now work properly:

Now you can update the device info properly!
Viewing the Raw SQL Statement
Thanks to Core Data. Even without learning SQL and database, you’re able to perform create, select, update and delete operation. However, for those with database background, you may want to know the exact SQLs executed behind the scene.
To enable SQL output for debugging purpose, click “MyStore” and select “Edit Scheme”.

Edit scheme in Xcode project
Under “Argument Passed on Launch” section, click the “+” button and add the “-com.apple.CoreData.SQLDebug 1” parameter:

Add SQL Debug Parameter
Click “OK” to confirm. Now run your app again and you’ll see the raw SQL statement (e.g. SELECT and UPDATE) displayed in the output window.

SQL statement for Core Data Debugging
What’s Coming Next
We hope you enjoy the tutorial and have a better understanding about Core Data. For your reference, you can download the complete source code here.
In the later tutorials, we’ll talk about object relationship and show you how to optimize the app using NSFetchedResultsController.
Comments
Curlypaws
AuthorThanks very much Simon. It is really helpful to see the combination of storyboards and Core Data as so many of the example I’ve seen have been pre iOS5.
Arie
AuthorI keep getting errors with – (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:@”UpdateDevice”]) {
NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
DeviceDetailViewController *destViewController = segue.destinationViewController;
destViewController.device = selectedDevice;
}
}
stuart
AuthorI am also getting error in the same area
NameTest
AuthorYou must include ‘DeviceDetailViewController.h’ file to DeviceViewController.m.
#import “DeviceDetailViewController.h”
Arie
Author2012-12-25 17:51:28.604 MyStore[1967:c07] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 “The operation couldn’t be completed. (Cocoa error 134100.)” UserInfo=0xa057fa0 {metadata={
NSPersistenceFrameworkVersion = 419;
NSStoreModelVersionHashes = {
Device = ;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
“”
);
NSStoreType = SQLite;
NSStoreUUID = “CAC08A0E-5C74-499B-BA50-A14AC5E803EA”;
“_NSAutoVacuumLevel” = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store}, {
metadata = {
NSPersistenceFrameworkVersion = 419;
NSStoreModelVersionHashes = {
Device = ;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
“”
);
NSStoreType = SQLite;
NSStoreUUID = “CAC08A0E-5C74-499B-BA50-A14AC5E803EA”;
“_NSAutoVacuumLevel” = 2;
};
reason = “The model used to open the store is incompatible with the one used to create the store”;
}
(lldb)
Simon Ng
AuthorIn the iOS simulator, click “iOS simulator” from the menu and select “Reset Content and Settings…”. Then try to build your project and run the app again. This may resolve the issue.
Marian
AuthorHi!
I like your Tutorials very much. Thank you! I have an idea for a new tutorial, can you explain how to record the voice in an app?
Marian
Simon Ng
AuthorGreat suggestion. I’ll put it in my todo list.
Bob
AuthorI just got here from your previous post. As payback for your great article here is a tool I have found very helpful for understanding Core Data
https://github.com/yepher/CoreDataUtility
Justin Bush
AuthorCan you include iCloud compatibility in Part 3? Your tutorial’s have been very helpful, thanks a lot.
Simon Ng
AuthorWe’ll cover relationships of Core Data in the next tutorial. But it’s good suggestion. We’ll write one about iCloud in the future.
xcdr
AuthorThank you very much it is perfect tutorial
Redkigs
AuthorThanks a lot! This turial us exactlt what I’m looking for.
Sodbileg Gansukh
AuthorThat’s really good tutorial. Can you please show us how to sync Core Data with MySQL web services with relationship? I’ve already read syncing tutorial on Raywenderlich, but it looks too difficult for me.
Jumanji
Authorjust want to say thank you very much this is a great tutorials!!! keep on posting !!!
Maciek Macie
AuthorIt’s not easy to find a table view + core data tutorial working on latest iOS. Thank you. I hope part 3 will be published soon
Simon Ng
AuthorI am still editing part 3 but it should be available later this month. Stay tuned 🙂
Wouter
AuthorI feel like you’re intentionally leaving more and more little steps out during your tutorial, and then I get errors, but then I can fix them because of what I got from your earlier lessons!
In this case for example, adding the segue gaven an error because he didn’t recognize the DeviceDetailViewController then, but of course importing the correct .h file at the top of DeviceViewController.m fixed that!
Wonderful feeling 🙂
Parag Bharambe
AuthorHello
i had a problem in segue.
Although i had imported proper .h file
sumy
AuthorThankz!!! Great Tutorial…..How can add image to core data in this application(along with each device)?
sumy
AuthorHow can add umage to core data in this appln( for each new device added)?
azma
AuthorGreat Tutorial. In the next one, maybe discuss how to allow re-ordering of the tableview cells, having a heck of a time with that.
pointer
AuthorExcellent tutorial. Looking forward to seeing part 3.
Vladislav Kovalyov
AuthorThis is a really great and simple tutorials. But I met a problem. I create another view for edit my data. When I tap “save”, it saves edited data and show on my table view. But when I restart my app, it doesn’t save my changes. How can I fix it?
P.S. Sorry for my bad English.
Tim
AuthorMe too, did you find an answer to this?
Hugo
AuthorHi,
First of all, two great introductions to Core Data ! I wish you’d write some more about relationships and iCloud sync.
Anyway, I would like to know how the method save: is invoked if we are only checking if the data has been saved/removed by writing : if(![context save:&error]) { … } ???
Thanks !
Crazy8s
AuthorIf you are still interested, it appears the -(BOOL)save: method both invokes the save and returns YES on completion. It is not simply a check to see if the record has already been saved.
Felix
Authorexcellent tutorials! Please when will session 3 be available? Thanks
Simon Ng
AuthorI’ve drafted the 3rd article but need some editing before releasing it here. Stay tuned.
Luwen Huang
AuthorThis is truly great stuff – the annotated graphics and explanations make these tutorials the best available online – can’t wait for the next article!
Priyal Jain
AuthorThanks for the excellent tutorial. It explains all the concepts very well. Although, I couldn’t find the link for third tutorial. Is it still there ?
asaf
AuthorGreat tutorial
Help me so much.
but i have a problem with my assignment.
i have an Students db (core data), i have one main view controller that contains the TableView with all context and Fetch.
to add Student, i have addStudentViewController.
the insert work great.
But, i have an editStudentViewController, when i click on accessoryButtonTappedForRowWithIndexPath i send the relevant information but the Edited data not store.
my question: how can i pass the nsmanagedObject to another viewController or how can i do the edit by another viewController.
Thanks
Aamir khan
Authorbest tutorials but sir only little information about database so you should to uploaded the complete set of the database tutorials………….
HLA
AuthorThanks a lot…
I would like to know how to dismiss keyboard after typing text in text box.
Owen Andrews
AuthorFantastic tutorials! Beats Apples docs 😉
Robert
AuthorGreat guide for Core Data basics and complete source code that works too! Thanks, been searching all morning for a good tutorial.
Abrar
AuthorHey, awesome tutorial!! Really enjoyed it. I was wondering one more thing… what if I wanted to sort the results by device? so all the apples up top and the rest below. How would I go about doing that?
jacob banks
Authori did both tutorials and at the end of this one i tried to run it and i got a black screen i have no errors or warnings can you help me.
shalin pandey
AuthorMake Your StoryBoard as Main in project Setting…………
sankar ram
AuthorHey I got a error define the Identifier Please help me in this
Mạnh Hiền Lành
Authorthanks a lot, can you write about core data part 3 for series guide,it’s how to use coreData in the app, please!
pradeep
AuthorCould somebody help me please ? I’m getting the below error when i’m trying to update the device details (i.e., when i select device in the table view). I’m using xcode 5. Additional point : I have embedded ‘navigation controller’ to the view controller.
2014-02-27 00:54:54.537 MyStore[3595:70b] -[UINavigationController setDevice:]: unrecognized selector sent to instance 0x8c824b0
2014-02-27 00:54:54.540 MyStore[3595:70b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[UINavigationController setDevice:]: unrecognized selector sent to instance 0x8c824b0’
*** First throw call stack:
(
0 CoreFoundation 0x01aa05e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x018238b6 objc_exception_throw + 44
2 CoreFoundation 0x01b3d903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x01a9090b ___forwarding___ + 1019
4 CoreFoundation 0x01a904ee _CF_forwarding_prep_0 + 14
5 MyStore 0x000043ba -[MSDeviceViewController prepareForSegue:sender:] + 458
6 UIKit 0x00ac606c -[UIStoryboardSegueTemplate _perform:] + 156
7 UIKit 0x00ac60f9 -[UIStoryboardSegueTemplate perform:] + 115
8 UIKit 0x00673775 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1453
9 UIKit 0x00673924 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 279
10 UIKit 0x00677908 __38-[UITableView touchesEnded:withEvent:]_block_invoke + 43
11 UIKit 0x005ae183 ___afterCACommitHandler_block_invoke + 15
12 UIKit 0x005ae12e _applyBlockToCFArrayCopiedToStack + 403
13 UIKit 0x005adf5a _afterCACommitHandler + 532
14 CoreFoundation 0x01a684ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
15 CoreFoundation 0x01a6841f __CFRunLoopDoObservers + 399
16 CoreFoundation 0x01a46344 __CFRunLoopRun + 1076
17 CoreFoundation 0x01a45ac3 CFRunLoopRunSpecific + 467
18 CoreFoundation 0x01a458db CFRunLoopRunInMode + 123
19 GraphicsServices 0x039019e2 GSEventRunModal + 192
20 GraphicsServices 0x03901809 GSEventRun + 104
21 UIKit 0x00591d3b UIApplicationMain + 1225
22 MyStore 0x000052ed main + 141
23 libdyld.dylib 0x020de70d start + 1
24 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Program ended with exit code: 0
Tabish Sohail
AuthorThanks alot..such a nice tutorial..clearly explained step by step..
Marco Boldetti
AuthorHello, i have a question….
if i want to load a Core Data database on a previously loaded data, as i make? Thank’s.
mark r
AuthorMy software errors on:
[self.device setValue:self.nameTextField.text forKey:@”name”];
in:
if (self.device) {
// Update existing device
[self.device setValue:self.nameTextField.text forKey:@”name”];
[self.device setValue:self.versionTextField.text forKey:@”version”];
[self.device setValue:self.companyTextField.text forKey:@”company”];
}
What would be the preseason for this?
mark r
AuthorI get the error on line return UIApplicationMain(argc, argv, nil, NSStringFromClass([EyePrescriptionTrackerAppDelegate class])); Does anyone have any ideas why is errors here when I press the button to update my core data? Any thoughts would be appreciated.
Quân Chùa
Authorthanks you very very very much for your tutorials.It helped me alot. I am so lucky to visit you site 🙂
Simon Ng
AuthorGreat to hear that 🙂 Keep coming back. You’ll find even more tutorials in coming weeks.
ish3lan
Authorhow lucky I am for finding this tutorial
thanx for the help
Annapurna priya
Authorgreat tutorial.!! Explains Core Data very easily..:)
But suppose i am getting data from server and inserting the server data in core data. Now what i want is that, when some new data comes from the server i will update my core data database. In that case what should i do??
Iris
AuthorHi! Great tutorial! They’re a big help. Though I’m still having trouble fully understanding the Objective C language, little by little, I’m gaining more confidence in iOS programming thanks to you. 🙂 Maybe you could do a tutorial on Magical Record next? Hehe. I’ll look forward to it.
Ejiro Ogagarue
Authorhow do you update the object from a button placed in the cell instead of using the table cell row to update the object i really need help in doing that
Gourav
Authorthanku bro…i did use yours source code..bt now i want know abt , how to perform many to many relationship in cvoredata …..
yhnks
Venkatraman
AuthorCan you please show us how to sync Core Data with MySQL web services with relationship? I’ve already read syncing tutorial on Raywenderlich, but it looks too difficult for me
rana
Authorwhen i click on data it goes to update view controller, but when i update data nd press save , it not comes back to list view controller..(data even updated on list vier controller,,)
can anyone help me in this?
pradeep
AuthorHi Rana, Use this [self.navigationController popViewControllerAnimated:YES];
instead of [self dismissViewControllerAnimated:YES completion:nil];
for both save and cancel
Ali E.
AuthorSimon, I just want to say thank you! I’ve been looking for almost 3 days for Core Data tutorials, I saw many long ones but this one is the BEST ONE! Very simple! I highly recommend it for Core Data beginners. Thanks again! 🙂
Simon Ng
AuthorThank you for your kind words 🙂
swetha
AuthorHow to view the devices that we added to the list in the sql database?
Wingle Wong
AuthorAt the end of this article , you said “In the later tutorials, we’ll talk about object relationship and show you how to optimize the app using NSFetchedResultsController.”. But I can not find the later tutorial about this, could you give me a link?
Mahesh M
AuthorYou Guys are AweSome Yaar this tutorial is very understandable i understood CoreData and am going to learn From You
and One more thing as a request from me
Please proceed the CoreData Tutorial for saving Images also because now am developing the application for storing the images and and some string values and implementing some search in the table view
But know what i want is to save image data in to the database thats it
Once Again Thanks 🙂
Omer Harel
Authorerror:
No visible @interface for ‘NSManagedObject’ declares the selector ‘objectAtIndex:’
—————–
(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:@”UpdateItem”]) {
NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow]row]];
MenuViewController *destViewController = segue.destinationViewController;
destViewController.devices = selectedDevice;
}
}
Atinderpal singh
Authortable view cell create in storyboard and its delegate and data source
Atinderpal singh
Authortableview cell also in storybord name “Cell”
otherwise not show data in tableview
Atinderpal singh
Authorotherwise not show data in tableview
Nagarjuna
Authornice tutorial
saran
AuthorJSON===
//
// ViewController.m
// JSON pr
//
// Created by apple on 26/10/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “ViewController.h”
#import “ViewController1.h”
@interface ViewController ()
{
UIActivityIndicatorView *indicator;
int searching;
NSArray * search_ary;
}
@property(nonatomic,strong)IBOutlet UITableView *tlb_name;
@property(nonatomic,strong)NSMutableArray *array;
@property(nonatomic,strong)NSMutableArray *aaray_name;
@property(nonatomic,retain)NSString *rooturl;
@property(nonatomic,strong)NSDictionary *dict1;
@end
@implementation ViewController
@synthesize rooturl;
– (void)viewDidLoad {
[super viewDidLoad];
searching=[[UISearchBar alloc]initWithFrame:CGRectMake(20, 40, 250, 60)];
indicator=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
indicator.color=[UIColor blackColor];
[self.view addSubview:indicator];
rooturl=@”http://www.elitedoctorsonline.com/api_mob/browser/search/search.aspx?cou_id=211&lang=en”;
[self Getmethod];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)Getmethod
{
NSURL *url=[NSURL URLWithString:rooturl];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod=@”GET”;
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
// [indicator startAnimating];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// if (connectionError) {
// } else
// {
// NSHTTPURLResponse *res=(NSHTTPURLResponse *)response;
// if (res.statusCode==200) {
if (data) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
// NSLog(@”keys:%@”,[dict allKeys]);
self.array=[[NSMutableArray alloc]initWithArray:[dict valueForKey:@”doctor_data”]];
[self.tlb_name reloadData];
}
//}
// }
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *idtifier=@”cell”;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:idtifier];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:idtifier];
}
self.dict1=[self.array objectAtIndex:indexPath.row];
NSLog(@”%@”,self.dict1);
cell.textLabel.text=[self.dict1 valueForKey:@”fullname”];
NSString *str=[self.dict1 valueForKey:@”doc_thumbnail”];
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
cell.imageView.image=[UIImage imageWithData:data];
[indicator stopAnimating];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ViewController1 *first=[self.storyboard instantiateViewControllerWithIdentifier:@”ViewController1″];
self.dict1=[self.array objectAtIndex:indexPath.row];
first.ArrayCarry=self.dict1;
[self.navigationController pushViewController:first animated:NO];
}
– (void)filterContentForSearchText:(NSString*)searchText
{
[self.array removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@”SELF contains[cd] %@”,
searchText];
self.array = [NSMutableArray arrayWithArray:[self.aaray_name filteredArrayUsingPredicate:resultPredicate]];//
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[searchBar setShowsCancelButton:YES];
[self filterContentForSearchText:searchText];
searching=(int)[searchText length];
[self.tlb_name reloadData];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
NSLog(@”searchBarSearchButtonClicked”);
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO];
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
SECOND===============
#import
@interface ViewController1 : UIViewController
@property(nonatomic,strong)NSDictionary *ArrayCarry;
@end
//
// ViewController1.m
// JSON pr
//
// Created by apple on 26/10/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “ViewController1.h”
@interface ViewController1 ()
@property(nonatomic,retain)IBOutlet UITextField *Txtfiled;
@property(nonatomic,strong)IBOutlet UITextField *txt1;
@property(nonatomic,strong)IBOutlet UITextField *txt2;
@property(nonatomic,strong)IBOutlet UITextField *txt3;
@property(nonatomic,strong)IBOutlet UITextField *txt4;
@property(nonatomic,strong)IBOutlet UIImageView *img;
@end
@implementation ViewController1
– (void)viewDidLoad {
[super viewDidLoad];
self.Txtfiled.text=[self.ArrayCarry valueForKey:@”doc_id”];
self.txt1.text=[self.ArrayCarry valueForKey:@”cou_name”];
self.txt2.text=[self.ArrayCarry valueForKey:@”cit_name”];
self.txt3.text=[self.ArrayCarry valueForKey:@”cou_code”];
self.txt4.text=[self.ArrayCarry valueForKey:@”degree”];
NSString *str1=[self.ArrayCarry valueForKey:@”doc_thumbnail”];
NSURL *url1=[NSURL URLWithString:str1];
NSData *data1=[NSData dataWithContentsOfURL:url1];
self.img.image=[UIImage imageWithData:data1];
// Do any additional setup after loading the view.
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark – Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
saran
AuthorCOREDATA===
//
// ViewController.m
// coredatasimple s
//
// Created by apple on 03/11/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “ViewController.h”
#import “AppDelegate.h”
#import “nextViewController.h”
@interface ViewController ()
@property(nonatomic,strong)IBOutlet UITextField *nametxt;
@property(nonatomic,strong)IBOutlet UITextField *versiontxt;
@property(nonatomic,strong)IBOutlet UITextField *companytxt;
– (IBAction)savebt:(id)sender;
– (IBAction)cancelbt:(id)sender;
@end
@implementation ViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context=[delegate managedObjectContext];
}
return context;
}
– (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
– (IBAction)savebt:(id)sender {
NSManagedObjectContext *context=[self managedObjectContext];
NSManagedObject *newvalue=[NSEntityDescription insertNewObjectForEntityForName:@”Device” inManagedObjectContext:context];
[newvalue setValue:self.nametxt.text forKey:@”name”];
[newvalue setValue:self.versiontxt.text forKey:@”version”];
[newvalue setValue:self.companytxt.text forKey:@”company”];
NSLog(@”save”);
NSError *error=nil;
if (![context save:&error]) {
NSLog(@”Can’t Save! %@ %@”, error, [error localizedDescription]);
}
NSFetchRequest *req=[[NSFetchRequest alloc]initWithEntityName:@”Device”];
NSArray*ary=[[context executeFetchRequest:req error:nil] mutableCopy];
NSLog(@”ary%@”,ary);
nextViewController *next=[self.storyboard instantiateViewControllerWithIdentifier:@”nextViewController”];
[self.navigationController pushViewController:next animated:nil];
}
– (IBAction)cancelbt:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
SECOND=========
//
// nextViewController.m
// coredatasimple s
//
// Created by apple on 03/11/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “nextViewController.h”
#import “AppDelegate.h”
#import “ViewController.h”
@interface nextViewController ()
{
IBOutlet UITableView *tlb;
}
@property(nonatomic,strong)NSMutableArray *array;
@end
@implementation nextViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context=[delegate managedObjectContext];
}
return context;
}
– (void)viewDidLoad {
[super viewDidLoad];
NSManagedObjectContext *managedObjectContext=[self managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@”Device”];
self.array=[[managedObjectContext executeFetchRequest:request error:nil]mutableCopy];
// Do any additional setup after loading the view.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellname=@”cell”;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellname];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellname];
NSManagedObject *devices=[self.array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@”%@ %@”, [devices valueForKey:@”name”],[devices valueForKey:@”version”]]];
[cell.detailTextLabel setText:[devices valueForKey:@”company”]];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context=[self managedObjectContext];
if (editingStyle==UITableViewCellEditingStyleDelete) {
[context deleteObject:[self.array objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@”Can’t Delete! %@ %@”, error, [error localizedDescription]);
return;
}
[self.array removeObjectAtIndex:indexPath.row];
[tlb deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark – Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
saran
AuthorCOREDATA WITH images
#import
@interface ViewController : UIViewController
{
__weak IBOutlet UIImageView *img_imagview;
__weak IBOutlet UITextField *txtfld_Name;
}
@end
//
// ViewController.m
// coredatasimple s
//
// Created by apple on 03/11/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “ViewController.h”
#import “AppDelegate.h”
#import “nextViewController.h”
@interface ViewController ()
@property(nonatomic,strong)IBOutlet UITextField *nametxt;
@property(nonatomic,strong)IBOutlet UITextField *phonenotxt;
@property(nonatomic,strong)IBOutlet UITextField *locationtxt;
@property (nonatomic, strong) NSData *imageData;
– (IBAction)savebt:(id)sender;
@end
@implementation ViewController
NSManagedObjectContext *managedObjectContext;
NSMutableArray *arr_data;
NSString *str_image;
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context=[delegate managedObjectContext];
}
return context;
}
– (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)SaveData_Database
{
NSManagedObjectModel *table = [NSEntityDescription insertNewObjectForEntityForName:@”Device” inManagedObjectContext:managedObjectContext];
[table setValue:txtfld_Name.text forKey:@”name”];
[table setValue:_imageData forKey:@”img”];
self.nametxt.text = @””;
}
-(void)GetValues_From_Databse
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@”Device”];
[fetchRequest setReturnsObjectsAsFaults:NO];
[fetchRequest setAccessibilityElementsHidden:YES];
arr_data = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(@”Array Value Image %@”,[arr_data valueForKey:@”image”]);
NSLog(@”Array Value %@”,[arr_data valueForKey:@”names”]);
}
– (IBAction)savebt:(id)sender {
NSManagedObjectContext *context=[self managedObjectContext];
NSManagedObject *newvalue=[NSEntityDescription insertNewObjectForEntityForName:@”Device” inManagedObjectContext:context];
NSString * strimg=[NSString stringWithFormat:@”savedImage.png”];
NSLog(@”%@”,strimg);
UIImage * str=[UIImage imageNamed:strimg];
NSLog(@”%@”,str);
NSData * dataimg=UIImageJPEGRepresentation(str, 1);
NSLog(@”%@”,dataimg);
[newvalue setValue:_imageData forKey:@”img”];
img_imagview.image=[UIImage imageWithData:dataimg];
NSLog(@”save iamge%@”,dataimg);
int age=(int)[self.phonenotxt.text integerValue];
[newvalue setValue:self.nametxt.text forKey:@”name”];
[newvalue setValue:[NSNumber numberWithInt:age] forKey:@”phoneno”];
[newvalue setValue:self.locationtxt.text forKey:@”location”];
NSLog(@”save”);
NSError *error=nil;
if (![context save:&error]) {
NSLog(@”Can’t Save! %@ %@”, error, [error localizedDescription]);
}
NSFetchRequest *req=[[NSFetchRequest alloc]initWithEntityName:@”Device”];
NSArray*ary=[[context executeFetchRequest:req error:nil] mutableCopy];
NSLog(@”ary%@”,ary);
nextViewController *next=[self.storyboard instantiateViewControllerWithIdentifier:@”nextViewController”];
[self.navigationController pushViewController:next animated:nil];
}
– (IBAction)btnclk_ViewController:(UIButton *)sender {
switch (sender.tag) {
case 1:
[self SaveData_Database];
break;
case 2:
[self GetValues_From_Databse];
break;
}
}
– (IBAction)btnclk_Image:(UIButton *)sender {
if (sender.tag == 1)
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
picker.delegate = self;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self presentViewController:picker animated:NO completion:nil];
}];
}
else {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@”savedImage.png”];
NSLog(@”image111 %@”,savedImagePath);
UIImage *image = img_imagview.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
}
– (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
NSLog(@”EditInfor %@”,editingInfo);
str_image = [NSString stringWithFormat:@”%@”,selectedImage];
img_imagview.image = selectedImage;
img_imagview.contentMode = UIViewContentModeScaleAspectFit;
_imageData = [[NSData alloc] init];
_imageData = UIImagePNGRepresentation(selectedImage);
NSLog(@”_image data :%@”, _imageData);
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
SECOND======
//
// nextViewController.m
// coredatasimple s
//
// Created by apple on 03/11/15.
// Copyright (c) 2015 Ndot. All rights reserved.
//
#import “nextViewController.h”
#import “AppDelegate.h”
#import “ViewController.h”
@interface nextViewController ()
{
IBOutlet UITableView *tlb;
}
@property(nonatomic,strong)NSMutableArray *array;
@end
@implementation nextViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context=[delegate managedObjectContext];
}
return context;
}
– (void)viewDidLoad {
[super viewDidLoad];
NSManagedObjectContext *managedObjectContext=[self managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@”Device”];
self.array=[[managedObjectContext executeFetchRequest:request error:nil]mutableCopy];
// Do any additional setup after loading the view.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellname=@”cell”;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellname];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellname];
NSManagedObject *devices=[self.array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@”%@ %@”, [devices valueForKey:@”name”],[devices valueForKey:@”phoneno”]]];
[cell.detailTextLabel setText:[devices valueForKey:@”location”]];
cell.imageView.image=[UIImage imageWithData:[devices valueForKey:@”img”]];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context=[self managedObjectContext];
if (editingStyle==UITableViewCellEditingStyleDelete) {
[context deleteObject:[self.array objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@”Can’t Delete! %@ %@”, error, [error localizedDescription]);
return;
}
[self.array removeObjectAtIndex:indexPath.row];
[tlb deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark – Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
Sasi Kumar
Author@implementation ViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if([delegate performSelector:@selector(managedObjectContext)])
{
context=[delegate managedObjectContext];
}
return context;
}
– (void)viewDidLoad {
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
NSManagedObjectContext *context=[self managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@”Details”];
aray=[[context executeFetchRequest:request error:nil]mutableCopy];
[table reloadData];
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return aray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *celll=@”Cell”;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:celll];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:celll];
}
NSManagedObject *display=[aray objectAtIndex:indexPath.row];
cell.textLabel.text=[display valueForKey:@”name”];
cell.detailTextLabel.text=[display valueForKey:@”phone”];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context=[self managedObjectContext];
if (editingStyle==UITableViewCellEditingStyleDelete)
{
[context deleteObject:[aray objectAtIndex:indexPath.row]];
NSError *error;
if (![context save:&error])
{
return;
}
[aray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
NEXTVIEWCONTROLLER————->
@implementation NextViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context=nil;
id delegate=[[UIApplication sharedApplication]delegate];
if([delegate performSelector:@selector(managedObjectContext)])
{
context=[delegate managedObjectContext];
}
return context;
}
@synthesize object;
– (void)viewDidLoad {
[super viewDidLoad];
if (self.object) {
[name setText:[self.object valueForKey:@”name”]];
[phone setText:[self.object valueForKey:@”phone”]];
}
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
{
if ([name.text length ]>4 && ([phone.text length]<10)) {
if ([name.text isEqualToString:@" "]) {
return YES;
}
}
return NO;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
– (IBAction)save:(id)sender
{
NSManagedObjectContext *context=[self managedObjectContext];
if (self.object) {
[self.object setValue:name.text forKey:@"name"];
[self.object setValue:phone.text forKey:@"phone"];
}
else{
NSManagedObject *insert=[NSEntityDescription insertNewObjectForEntityForName:@"Details" inManagedObjectContext:context];
[insert setValue:name.text forKey:@"name"];
[insert setValue:phone.text forKey:@"phone"];
}
NSError *error;
if (![context save:&error])
{
}
[self dismissViewControllerAnimated:NO completion:nil];
}
– (IBAction)cancel:(id)sender
{
[self dismissViewControllerAnimated:NO completion:nil];
}
saran
AuthorFacebook iD-====
//
// ViewController.m
// facebookdemo
//
// Created by IOS on 01/11/15.
// Copyright © 2015 gnanam105. All rights reserved.
//
#import “ViewController.h”
#import
#import
#import
@interface ViewController ()
{
FBSDKLoginButton *fbloginbutton;
FBSDKProfilePictureView *fbprofilepicture;
UILabel *lbl_name;
FBSDKShareButton *sharebutton;
FBSDKSendButton *sentbutton;
}
@property (nonatomic,strong) FBSDKGraphRequest *request;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
//FBLOGINBUTTON
fbloginbutton=[[FBSDKLoginButton alloc]initWithFrame:CGRectMake(120, 50, 100, 30)];
fbloginbutton.delegate=self;
fbloginbutton.readPermissions=@[@”public_profile”,@”user_friends” ];
[self.view addSubview:fbloginbutton];
//Profilepicture
fbprofilepicture = [[FBSDKProfilePictureView alloc]initWithFrame:CGRectMake(10, 100, 100, 100)];
[self.view addSubview:fbprofilepicture];
//loginname
lbl_name=[[UILabel alloc]initWithFrame:CGRectMake(10, 220, 100, 30)];
[self.view addSubview:lbl_name];
lbl_name.text=[FBSDKProfile currentProfile].name;
//take friends list
UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(130, 220, 100, 30)];
button.backgroundColor=[UIColor redColor];
[button setTitle:@”Friends List” forState:UIControlStateNormal];
[button addTarget:self action:@selector(friendslist) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//shareButton
sharebutton=[[FBSDKShareButton alloc]initWithFrame:CGRectMake(10, 260, 100, 40)];
[self.view addSubview:sharebutton];
UISegmentedControl *segment=[[UISegmentedControl alloc]initWithFrame:CGRectMake(130, 100, 150, 30)];
[segment addTarget:self action:@selector(segmentaction:) forControlEvents:UIControlEventValueChanged];
[segment insertSegmentWithTitle:@”SHARELIKETITLE” atIndex:0 animated:YES];
[segment insertSegmentWithTitle:@”Photo” atIndex:1 animated:YES];
[segment insertSegmentWithTitle:@”VideoURL” atIndex:2 animated:YES];
[self.view addSubview:segment];
//Like Button
FBSDKLikeControl *likeButton = [[FBSDKLikeControl alloc] initWithFrame:CGRectMake(10, 310, 50, 40)];
likeButton.objectID = @”https://www.facebook.com/ajithaddicted/?fref=ts”;
[self.view addSubview:likeButton];
sentbutton=[[FBSDKSendButton alloc]initWithFrame:CGRectMake(110, 260, 100, 40)];
[self.view addSubview:sentbutton];
UIButton *buttonfb = [[UIButton alloc]init];
buttonfb.frame = CGRectMake(30, 400, 100, 30);
buttonfb.backgroundColor = [UIColor blueColor];
[buttonfb setTitle:@”Login FaceBook” forState:UIControlStateNormal];
[buttonfb addTarget:self action:@selector(fblogin) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonfb];
}
-(void)fblogin{
NSLog(@”fblogin”);
//[self loginButtonClicked];
}
-(void)loginButtonClicked
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: @[@”public_profile”,@”user_friends”,@”email”]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(@”Process error”);
} else if (result.isCancelled) {
NSLog(@”Cancelled”);
} else {
NSLog(@”Logged in”);
[[[FBSDKGraphRequest alloc] initWithGraphPath:@”me” parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(@”fetched user:%@ and Email : %@”, result,result[@”email”]);
}
}];
}
}];
}
-(void)segmentaction:(UISegmentedControl*)sender{
if (sender.selectedSegmentIndex==0) {
[self sharingLikecontent];
}
if (sender.selectedSegmentIndex==1) {
[self sharingPhotocontent];
}
if (sender.selectedSegmentIndex==2) {
[self sharingvideocontent];
}
}
-(void)sharingLikecontent{ //FBSDKShareLinkContent
sharebutton.shareContent=nil;
FBSDKShareLinkContent *content1=[[FBSDKShareLinkContent alloc]init];
content1.contentTitle=@”DEMO TITLE”;
content1.contentURL=[NSURL URLWithString:@”http://www.facebook.com”];
content1.contentDescription=@”Context Description”;
sentbutton.shareContent=content1; //send button
content1.imageURL=[NSURL URLWithString:@”http://rack.0.mshcdn.com/media/ZgkyMDEyLzEyLzAzL2VhL2ZhY2Vib29rdGVzLjZJay5qcGcKcAl0aHVtYgk5NTB4NTM0IwplCWpwZw/aca78780/274/facebook-tests-photo-sync-for-ios-video–33d810072a.jpg”];
sharebutton.shareContent=content1;
//Diaglog if needed
[FBSDKShareDialog showFromViewController:self withContent:content1 delegate:nil];
}
-(void)sharingPhotocontent{ //FBSDKSharePhotoContent
//this method not working
sharebutton.shareContent=nil;
//image file maximum 12MB
FBSDKSharePhotoContent *content2=[[FBSDKSharePhotoContent alloc]init];
FBSDKSharePhoto *photo=[[FBSDKSharePhoto alloc]init];
photo.image=[UIImage imageNamed:@”sharephoto”];
photo.userGenerated=YES;
content2.photos=@[photo];
sharebutton.shareContent=content2;
//Diaglog if needed
[FBSDKMessageDialog showWithContent:content2 delegate:nil];
}
-(void)sharingvideocontent{ //FBSDKShareVideoContent
sharebutton.shareContent=nil;
//video file maximum 12MB
// NSURL *videoURL = [info objectForKey:UIImagePickerControllerReferenceURL];
//
// FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
// video.videoURL = videoURL;
// FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
// content.video = video;
//FBSDKShareOpenGraphContent ////FBSDKShareOpenGraphContent
NSDictionary *properties = @{
@”og:type”: @”fitness.course”,
@”og:title”: @”Sample Course”,
@”og:description”: @”This is a sample course.”,
@”fitness:duration:value”: @100,
@”fitness:duration:units”: @”s”,
@”fitness:distance:value”: @12,
@”fitness:distance:units”: @”km”,
@”fitness:speed:value”: @5,
@”fitness:speed:units”: @”m/s”,
};
FBSDKShareOpenGraphObject *object = [FBSDKShareOpenGraphObject objectWithProperties:properties];
FBSDKShareOpenGraphAction *action = [[FBSDKShareOpenGraphAction alloc] init];
action.actionType = @”fitness.runs”;
[action setObject:object forKey:@”fitness:course”];
FBSDKShareOpenGraphContent *content = [[FBSDKShareOpenGraphContent alloc] init];
content.action = action;
content.previewPropertyName = @”fitness:course”;
sharebutton.shareContent=content;
}
/*
– (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (![[FBSDKAccessToken currentAccessToken] hasGranted:@”user_friends”])
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@”user_friends”]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if ([result.grantedPermissions containsObject:@”user_friends”]) {
[self friendslist];
} else {
[self dismissViewControllerAnimated:YES completion:NULL];
}
}];
} else {
[self friendslist];
}
}*/
-(void)friendslist{
self.request=[[FBSDKGraphRequest alloc] initWithGraphPath:@”me/taggable_friends?limit=100″
parameters:@{ @”fields” : @”id,name,picture.width(100).height(100)”}];
NSLog(@”Request:%@”,self.request);
[self.request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(@”Picker loading error:%@”, error);
if (!error.userInfo[FBSDKErrorLocalizedDescriptionKey]) {
NSLog(@”%@”,error.description);
}} else {
NSLog(@”result:%@ data:%@”,result,result[@”data”]);
}
}];
}
#pragma mark ==========>FBSDKLOGINBUTTONDELEGATE
-(void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error{
NSLog(@”didCompleteWithResult”);
}
-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
NSLog(@”loginButtonDidLogOut”);
}
– (BOOL) loginButtonWillLogin:(FBSDKLoginButton *)loginButton{
NSLog(@”loginButtonWillLogin”);
return YES;
}
– (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
saran
AuthorFacebookDisplayName
saran
Authorlogindemo
saran
AuthorFacebookAppID
saran
Author401043023425939
nalamala saiteja
Authorunable to delete selected text field but.
nalamala saiteja
Authoreven though it is deleted. if i run my code again tableview still presenting old data. in your code u r just removing devices array. not data in database
Suresh Devineni
Authori really very help full this thanks for admin
Alfredo Lopez
AuthorI wonder if it’s a good idea to separate the Core Data stack into it’s own file so it’s not inside AppDelegate? Also any other tricks to make it more “professional” looking would be great 🙂
Erich Snijder
AuthorGreat work.
Was a year ago sinds my last work with iOS but you helped me getting it again.
Thanks a lot.