Tuesday, December 13, 2016

How to do Web Service in iOS - Web Service Sample example


Import ApiCall Model object class in ViewController.h

Call delegate APIDelegate in ViewController.h to define the APICall delegate methods in our ViewController View


//=== 


#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "APICall.h"
@interface ViewController ()<APIDelegate>
{
    UILabel * lbl;
}

@end


//=== "ViewController.M"


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    APICall * api= [[APICall alloc] init];
    
    api.del = self;
    
    [api makeAPICallWithMethodName:@"greeting" methodTyep:@"GET" body:nil];
}

-(void)serviceSuccess:(NSData *)data methodName:(NSString *)method
{
    NSLog(@"Data : %@",data);
    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    NSLog(@"%@", jsonDict);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        lbl.text = [jsonDict objectForKey:@"id"];
    });
}
-(void)serviceError:(NSError *)error methodName:(NSString *)method{


}


//=== All the Magic is in APICall.h model objects to call the service calls


#import <Foundation/Foundation.h>
#define BASEURL @"http://rest-service.guides.spring.io/"
@protocol APIDelegate
@optional
-(void)serviceSuccess:(NSData *)data methodName:(NSString *)method;
-(void)serviceError:(NSError *)error methodName:(NSString *)method;
@end

@interface APICall : NSObject
{

}
@property (strong,nonatomic) id<APIDelegate> del;
-(void)makeAPICallWithMethodName:(NSString *)methodName methodTyep:(NSString *)methodType body:(NSData *)body;
@end

//=== APICAll.M


#import "APICall.h"

@implementation APICall

-(NSMutableURLRequest *)prepareRequestWithMethodName:(NSString *)methodName methodType:(NSString *)methodType body:(NSData *)bodyData
{
    NSDictionary *headers = @{ @"cache-control": @"no-cache",
                               @"postman-token": @"b559e00e-c5a5-e96e-63ea-40907d757a39",@"AUTHTOKEN":@"djajkdhakj" };
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@",BASEURL,methodName];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:methodType];
    [request setAllHTTPHeaderFields:headers];
    if ([methodType isEqualToString:@"PUT"] || [methodType isEqualToString:@"POST"]) {
        [request setHTTPBody:bodyData];
    }
    return request;
}


-(void)conncectWithServerRequest:(NSURLRequest *)request methodName:(NSString *)method
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        NSLog(@"%@", error);
                                                        [self.del serviceError:error methodName:method];
                                                    } else {
                                                        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                        NSLog(@"%@", httpResponse);
                                                        [self.del serviceSuccess:data methodName:method];
                                                    }
                                                }];
    [dataTask resume];
}

-(void)makeAPICallWithMethodName:(NSString *)methodName methodTyep:(NSString *)methodType body:(NSData *)body
{
    NSMutableURLRequest * request = [self prepareRequestWithMethodName:methodName methodType:methodType body:body];
    [self conncectWithServerRequest:request methodName:methodName];
}
@end

Monday, June 27, 2016

How to Start Coredata - Coredata Tutorial in Objective C


/*!
 Saving Data objects method
*/
-(void)savingDataIntoCoreData
{
    NSManagedObjectContext *context = [self managedObjectContext];
   
    // Create a new managed object
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
    [newDevice setValue:@"iPhone 5" forKey:@"name"];
    [newDevice setValue:[NSNumber numberWithInt:9.0] forKey:@"version"];
    [newDevice setValue:@"rBA" forKey:@"company"];
   
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [self fetchingDataFromCoreData];
}

/*!
Fetching Data from SQLITE using coredata
*/
-(void)fetchingDataFromCoreData
{
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
    NSArray * devicesArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    NSLog(@"Devices %@",devicesArray);
}

/*!
Getting  managedObjectContext object
*/
- (NSManagedObjectContext *)managedObjectContext {
   
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}


Deleting Object Using CoreData :

-(void)deleteObject:(NSManagedObject *)object
{
 NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:object];
 NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }
 
}


CoreData stack :

Managed Object Model :
It describes the schema that you use in the app. The schema is represented by a collection of objects (also known as entities). In Xcode, the Managed Object Model is defined in a file with the extension .xcdatamodeld. You can use the visual editor to define the entities and their attributes, as well as, relationships.
Persistent Store Coordinator :
SQLite is the default persistent store in iOS. However, Core Data allows developers to setup multiple stores containing different entities. The Persistent Store Coordinator is the party responsible to manage different persistent object stores and save the objects to the stores.
Managed Object Context  :
Its job is to manage objects created and returned using Core Data. Among the components in the Core Data Stack, the Managed Object Context is the one you’ll work with for most of the time. In general, whenever you need to fetch and save objects in persistent store, the context is the first component you’ll talk to. 

Saving Objects using Core Data :

Every object that Core Data stores is inherited from NSManagedObject. So we first create a new instance of NSManagedObject for the “Device” entity that we’ve defined in the object model. NSEntityDescription class provides a method named “insertNewObjectForEntityForName” for developer to create a managed object. Once you created the managed object (i.e. newDevice), you can set the attributes (name, version, company) using the user input. Lastly, we call up the “save:” method of the context to save the object into database. 
Fetching Data using Core Data :
First we need to get the managed object context. To fetch the device info from the database   
we need to create instance of NSFetchRequest  and set the entity Device and invokes method executeFetchRequest to retirve all the data related to Device  entity. Similar to SELECT caluse in relataion database.

CoreData Tutorial with Objective C


/*!
 Saving Data objects method
*/
-(void)savingDataIntoCoreData
{
    NSManagedObjectContext *context = [self managedObjectContext];
   
    // Create a new managed object
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
    [newDevice setValue:@"iPhone 5" forKey:@"name"];
    [newDevice setValue:[NSNumber numberWithInt:9.0] forKey:@"version"];
    [newDevice setValue:@"rBA" forKey:@"company"];
   
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [self fetchingDataFromCoreData];
}

/*!
Fetching Data from SQLITE using coredata
*/
-(void)fetchingDataFromCoreData
{
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
    NSArray * devicesArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    NSLog(@"Devices %@",devicesArray);
}

/*!
Getting  managedObjectContext object
*/
- (NSManagedObjectContext *)managedObjectContext {
   
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}


Deleting Object Using CoreData :

-(void)deleteObject:(NSManagedObject *)object
{
 NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:object];
 NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }
 
}


CoreData stack :

Managed Object Model :
It describes the schema that you use in the app. The schema is represented by a collection of objects (also known as entities). In Xcode, the Managed Object Model is defined in a file with the extension .xcdatamodeld. You can use the visual editor to define the entities and their attributes, as well as, relationships.
Persistent Store Coordinator :
SQLite is the default persistent store in iOS. However, Core Data allows developers to setup multiple stores containing different entities. The Persistent Store Coordinator is the party responsible to manage different persistent object stores and save the objects to the stores.
Managed Object Context  :
Its job is to manage objects created and returned using Core Data. Among the components in the Core Data Stack, the Managed Object Context is the one you’ll work with for most of the time. In general, whenever you need to fetch and save objects in persistent store, the context is the first component you’ll talk to. 

Saving Objects using Core Data :

Every object that Core Data stores is inherited from NSManagedObject. So we first create a new instance of NSManagedObject for the “Device” entity that we’ve defined in the object model. NSEntityDescription class provides a method named “insertNewObjectForEntityForName” for developer to create a managed object. Once you created the managed object (i.e. newDevice), you can set the attributes (name, version, company) using the user input. Lastly, we call up the “save:” method of the context to save the object into database. 
Fetching Data using Core Data :
First we need to get the managed object context. To fetch the device info from the database   
we need to create instance of NSFetchRequest  and set the entity Device and invokes method executeFetchRequest to retirve all the data related to Device  entity. Similar to SELECT caluse in relataion database.