iOS

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

Note: If this is the first time you learn about Core Data, we recommend you to read the first tutorial. But for those who do not want to start from the very beginning, you can download this Xcode project to continue to work on the below tutorial.

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:

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

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.

MyStore - Add UpdateDevice Segue

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:

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.

Note: If you have no idea about what the segue is, go back to check out the tutorial about passing data between view controllers with segue.

Next, add a new properties in the DeviceDetailViewController.h for saving the selected device:

As always, add the synthesis statement in the DeviceDetailViewController.m:

To display the information of the selected device, we have to change the “viewDidLoad” method:

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.

MyStore - Display Detail Device Info

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:

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:

MyStore - Update Device Info Sample

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

Xcode 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:

Xcode add SQL Debug 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 output debug

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.

iOS
Introduction to Firebase: Building a Simple Social App in Swift
iOS
AdMob Tutorial: Displaying Banner Ads in iOS Apps with Swift 3
iOS
Parse Migration: How to Setup and Deploy Parse Server on Heroku or AWS
  • Curlypaws

    CurlypawsCurlypaws

    Author Reply

    Thanks 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

    ArieArie

    Author Reply

    I 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

      stuartstuart

      Author Reply

      I am also getting error in the same area


      • NameTest

        NameTestNameTest

        Author Reply

        You must include ‘DeviceDetailViewController.h’ file to DeviceViewController.m.
        #import “DeviceDetailViewController.h”


  • Arie

    ArieArie

    Author Reply

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

      Simon NgSimon Ng

      Author Reply

      In 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

    MarianMarian

    Author Reply

    Hi!
    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

      Simon NgSimon Ng

      Author Reply

      Great suggestion. I’ll put it in my todo list.


  • Bob

    BobBob

    Author Reply

    I 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

    Can you include iCloud compatibility in Part 3? Your tutorial’s have been very helpful, thanks a lot.


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      We’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

    xcdrxcdr

    Author Reply

    Thank you very much it is perfect tutorial


  • Redkigs

    RedkigsRedkigs

    Author Reply

    Thanks a lot! This turial us exactlt what I’m looking for.


  • Sodbileg Gansukh

    That’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

    JumanjiJumanji

    Author Reply

    just want to say thank you very much this is a great tutorials!!! keep on posting !!!


  • Maciek Macie

    It’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

      Simon NgSimon Ng

      Author Reply

      I am still editing part 3 but it should be available later this month. Stay tuned 🙂


  • Wouter

    WouterWouter

    Author Reply

    I 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

      Hello
      i had a problem in segue.
      Although i had imported proper .h file


  • sumy

    sumysumy

    Author Reply

    Thankz!!! Great Tutorial…..How can add image to core data in this application(along with each device)?


  • sumy

    sumysumy

    Author Reply

    How can add umage to core data in this appln( for each new device added)?


  • azma

    azmaazma

    Author Reply

    Great 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

    pointerpointer

    Author Reply

    Excellent tutorial. Looking forward to seeing part 3.


  • Vladislav Kovalyov

    This 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

      TimTim

      Author Reply

      Me too, did you find an answer to this?


  • Hugo

    HugoHugo

    Author Reply

    Hi,

    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

      Crazy8sCrazy8s

      Author Reply

      If 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

    FelixFelix

    Author Reply

    excellent tutorials! Please when will session 3 be available? Thanks


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      I’ve drafted the 3rd article but need some editing before releasing it here. Stay tuned.


      • Luwen Huang

        This 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

        Thanks 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

    asafasaf

    Author Reply

    Great 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

    Aamir khanAamir khan

    Author Reply

    best tutorials but sir only little information about database so you should to uploaded the complete set of the database tutorials………….


  • HLA

    HLAHLA

    Author Reply

    Thanks a lot…
    I would like to know how to dismiss keyboard after typing text in text box.


  • Owen Andrews

    Fantastic tutorials! Beats Apples docs 😉


  • Robert

    RobertRobert

    Author Reply

    Great guide for Core Data basics and complete source code that works too! Thanks, been searching all morning for a good tutorial.


  • Abrar

    AbrarAbrar

    Author Reply

    Hey, 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

    i 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

      Make Your StoryBoard as Main in project Setting…………


  • sankar ram

    sankar ramsankar ram

    Author Reply

    Hey I got a error define the Identifier Please help me in this


  • Mạnh Hiền Lành

    thanks a lot, can you write about core data part 3 for series guide,it’s how to use coreData in the app, please!


  • pradeep

    pradeeppradeep

    Author Reply

    Could 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

    Thanks alot..such a nice tutorial..clearly explained step by step..


  • Marco Boldetti

    Hello, 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

    mark rmark r

    Author Reply

    My 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

      mark rmark r

      Author Reply

      I 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

    thanks you very very very much for your tutorials.It helped me alot. I am so lucky to visit you site 🙂


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Great to hear that 🙂 Keep coming back. You’ll find even more tutorials in coming weeks.


  • ish3lan

    ish3lanish3lan

    Author Reply

    how lucky I am for finding this tutorial
    thanx for the help


  • Annapurna priya

    great 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

    IrisIris

    Author Reply

    Hi! 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

    how 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

    GouravGourav

    Author Reply

    thanku bro…i did use yours source code..bt now i want know abt , how to perform many to many relationship in cvoredata …..

    yhnks


  • Venkatraman

    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


  • rana

    ranarana

    Author Reply

    when 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

      pradeeppradeep

      Author Reply

      Hi Rana, Use this [self.navigationController popViewControllerAnimated:YES];

      instead of [self dismissViewControllerAnimated:YES completion:nil];

      for both save and cancel


  • Ali E.

    Ali E.Ali E.

    Author Reply

    Simon, 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

      Simon NgSimon Ng

      Author Reply

      Thank you for your kind words 🙂


  • swetha

    swethaswetha

    Author Reply

    How to view the devices that we added to the list in the sql database?


  • Wingle Wong

    At 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

    Mahesh MMahesh M

    Author Reply

    You 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

    Omer HarelOmer Harel

    Author Reply

    error:

    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

    table view cell create in storyboard and its delegate and data source


  • Atinderpal singh

    tableview cell also in storybord name “Cell”
    otherwise not show data in tableview


  • Atinderpal singh

    otherwise not show data in tableview


  • Nagarjuna

    NagarjunaNagarjuna

    Author Reply

    nice tutorial


  • saran

    saransaran

    Author Reply

    JSON===

    //

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

    saransaran

    Author Reply

    COREDATA===

    //

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

    saransaran

    Author Reply

    COREDATA 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

    Sasi KumarSasi Kumar

    Author Reply

    @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

    saransaran

    Author Reply

    Facebook 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

    saransaran

    Author Reply

    FacebookDisplayName


  • saran

    saransaran

    Author Reply

    logindemo


  • saran

    saransaran

    Author Reply

    FacebookAppID


  • saran

    saransaran

    Author Reply

    401043023425939


  • nalamala saiteja

    unable to delete selected text field but.


  • nalamala saiteja

    even 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

    i really very help full this thanks for admin


  • Alfredo Lopez

    I 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

    Great work.
    Was a year ago sinds my last work with iOS but you helped me getting it again.

    Thanks a lot.


Shares