Friday, 28 February 2014

Save data into NsuserDefault using objective C


- (IBAction)SaveUsingNsuserDefault:(id)sender
{

NSMutableArray* mutableArry   =  [[NSMutableArray allocinit];

    NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
    [array setObject:txtName.text forKey:@"name"];
    [array setObject:txtCity.text forKey:@"city"];
    [array setObject:txtPass.text forKey:@"pass"];
    
    NSMutableArray *studentArray;
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *previousSavedArray = [currentDefaults objectForKey:@"saveStudents"];
    if (previousSavedArray != nil)
        studentArray = [[NSMutableArray alloc] initWithArray:previousSavedArray];
    else
        studentArray = [[NSMutableArray alloc] init];
    
    NSMutableArray* arrStudentDetails = [currentDefaults objectForKey:@"saveStudents"];

    
    mutableArry = arrStudentDetails;
    
    if([[txtName.text checkNullFromString:txtName.text] isEqualToString:@""]|| [[txtCity.text checkNullFromString:txtCity.text] isEqualToString:@""]|| [[txtPass.text checkNullFromString:txtPass.text] isEqualToString:@""])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Required" message:@"Empty Field not allowed !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        if([mutableArry count]>0)
        {
            [self.tblEmpDetails reloadData];
        }
        return;
    }
   
        int j = [previousSavedArray count];
        for (int i = 0; j>i; i++) 
        {
            NSString* strName = [[previousSavedArray objectAtIndex:i]valueForKey:@"name"];
            if([strName isEqualToString:txtName.text])
            {
                
                UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Exist" message:@"Record allready exist !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
        }
    
    [studentArray addObject:array];
    [currentDefaults setObject:studentArray forKey:@"saveStudents"];
    [currentDefaults synchronize];
    
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Saved successfully !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    
     arrStudentDetails = [currentDefaults  objectForKey:@"saveStudents"];

    mutableArry = arrStudentDetails;
    if([mutableArry count]>0)
    {
        [self.tblEmpDetails reloadData];
    }


}

Thursday, 27 February 2014

Code for insert,retrieve and delete data using coredata using objective C in IOS


Before start coding we have to follow some steps..

1. Create a new empty project with coredata.
   . open xcode
   . go to file create new project and select empty application
   . Click next and do not miss to check the coredata chekbox..
    next...



2. if needed we have to add CoreData.framework(by default added with core data project..)

TestAppDelegate* appdelegate = [[UIApplication sharedApplication]delegate];
   NSManagedObject* context = appdelegate.managedObjectContext; 

// Insert into
NSMutableArray*  mutableArry = [[NSMutableArray alloc]init]
-(void)insertIntoCoreData
{
    if([[self exstingrecord] isEqualToString:[txtName.text lowercaseString]])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Exist" message:@"Record allready exist !" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        txtName.text = [[mutableArry objectAtIndex:0]valueForKey:@"name"];
        txtCity.text = [[mutableArry objectAtIndex:0]valueForKey:@"city"];
        txtPass.text = [[mutableArry objectAtIndex:0]valueForKey:@"pass"];
        return;
    }
    else
    {
        
        
            // Create a new object
            object = [NSEntityDescription insertNewObjectForEntityForName:@"Emp" inManagedObjectContext:context];
            [object setValue:self.txtName.text forKey:@"name"];
            [object setValue:self.txtCity.text forKey:@"city"];
            [object  setValue:self.txtPass.text forKey:@"pass"];
        
        NSError *err ;
        if(![context save:&err])
        {
            NSLog(@"Faild");
        }
        else
        {
            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Saved" message:@"Data saved successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            txtName.text = @"";
            txtCity.text = @"";
            txtPass.text = @"";
            
        }
    }
    
    [self fetchrecord];
    
    
    
}

// Retrieve from
-(void)fetchrecord
{
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Emp" inManagedObjectContext:context];
    [request setEntity:entity];
    NSError *error = nil;
    arr = [context executeFetchRequest:request error:&error];
    mutableArry = [[NSMutableArray alloc]init];
    [mutableArry addObjectsFromArray:arr];
    
    [self.tblEmpDetails reloadData];
}

// Delete from 


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        
        if (editingStyle == UITableViewCellEditingStyleDelete)
        {
            // Delete object from database
            [context deleteObject:[mutableArry objectAtIndex:indexPath.row]];
            
            NSError *error = nil;
            if (![context save:&error]) 
            {
                NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
                return;
            }
            
            // Remove device from table view
            [mutableArry removeObjectAtIndex:indexPath.row];
            [self.tblEmpDetails deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }

}


code for Save data into plist using objective C and retrieve from and display with uitableview..


/*
 1) Create a list of paths.
 2) Get a path to your documents directory from the list.
 3) Create a full file path.
 4) Check if file exists.
 5) Get a path to your plist created before in bundle directory (by Xcode).
 6) Copy this plist to your documents directory.
 */



- (IBAction)SaveUsingPlist:(id)sender 
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"plist.plist"];
    NSMutableArray *friend = [NSMutableArray arrayWithContentsOfFile:plistPath];
    
    mutableArry = friend;

    
     if([[txtName.text checkNullFromString:txtName.text] isEqualToString:@""]|| [[txtCity.text checkNullFromString:txtCity.text] isEqualToString:@""]|| [[txtPass.text checkNullFromString:txtPass.text] isEqualToString:@""])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Required" message:@"Empty Field not allowed !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        if([mutableArry count]>0)
        {
            [self.tblEmpDetails reloadData];
        }
        return;
    }
    
    if (nil == friend)
    {
        friend = [[NSMutableArray alloc] initWithCapacity:0];
        
        NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
        [array setObject:txtName.text forKey:@"name"];
        [array setObject:txtCity.text forKey:@"city"];
        [array setObject:txtPass.text forKey:@"pass"];
        [friend addObject:array];
        [friend writeToFile:plistPath atomically: TRUE];
        
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Saved successfully !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    else 
    {
       int j = [friend count];
        for (int i = 0; j>i; i++) 
        {
             NSString* strName = [[friend objectAtIndex:i]valueForKey:@"name"];
            if([strName isEqualToString:txtName.text])
            {
                
                UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Exist" message:@"Record allready exist !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
        }
        NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
        [array setObject:txtName.text forKey:@"name"];
        [array setObject:txtCity.text forKey:@"city"];
        [array setObject:txtPass.text forKey:@"pass"];
        [friend addObject:array];
        [friend writeToFile:plistPath atomically: TRUE];
        
        
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Saved successfully !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    friend = [NSMutableArray arrayWithContentsOfFile:plistPath];
    mutableArry = friend;
    if([mutableArry count]>0)
    {
        [self.tblEmpDetails reloadData];
    }
    
}

Wednesday, 19 February 2014

AFNetworking




Note:  Before start coding download the afnetworking archive and add in your project from following link...

http://four-developers.com/documents/AFNetworking.zip

#pragma mark- AFNetworking

-(void)makeRestuarantRequests
{
    NSURL *url = [NSURL URLWithString:@"http://four-developers.com/service1.svc/getdata/aa"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //AFNetworking asynchronous url request
    AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                         JSONRequestOperationWithRequest:request
                                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
                                         {
                                             arrEmp = [[NSArray alloc]initWithObjects:responseObject, nil];
                                    
                                             
                                             [self generateTableView];
                                             tblemployee.dataSource = self;
                                         }
                                         failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                         {
                                             NSLog(@"Request Failed: %@, %@", error, error.userInfo);
                                         }];
    
    [operation start];
    
}