Thursday, 19 June 2014

IOS : Save Data using Rest Web services with POST method

- (IBAction)providerRegistration:(id)sender
{

@try 
{
    [self.txtClientId resignFirstResponder];
    if([[self.txtEmrName notNull:self.txtEmrName] isEqualToString:@""] || [[self.txtUserName notNull:self.self.txtUserName] isEqualToString:@""] || [[self.txtPassword notNull:self.self.txtPassword] isEqualToString:@""]|| [[self.txtProvider notNull:self.self.txtProvider] isEqualToString:@""]|| [[self.txtClientId notNull:self.self.txtClientId] isEqualToString:@""])
    {
  UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"empty" message:@"information   required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
        [alert show];
        return;
    }
    NSError *error;

    NSString *url = @"http://four-developers.com/service1.svc/GetData";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    

    
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
      [request setHTTPMethod:@"POST"];
    
    NSMutableDictionary* mapData = [[ NSMutableDictionary alloc ] init ];
    
    //[ mapData setObject :@"MEDPRIME" forKey : @"DataSourceName"];
    [ mapData setObject :self.txtEmrName.text forKey : @"aa"];
      
    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
    [request setHTTPBody:postData];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
                             
                               [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                   
                                  // UI Updation...
                               }];
                               
                               NSError *err = nil ;
                               NSDictionary   *responseDict = [ NSJSONSerialization JSONObjectWithData :data options : 0 error :&err];
                               NSString* strResult = [responseDict objectForKey : @"ProviderRegristrationResult" ];
                               
                               if([strResult isKindOfClass:[NSNull class]])
                               {
                                   UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"empty" message:@"Data save failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                                   [alert show];
                                   return;
                               }
                               else if([strResult isEqualToString:@""])
                               {
                                   UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"empty" message:@"Data save failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                                   [alert show];
                                   return;
                               }
                               else if([strResult isEqualToString:@"User Already Exist"])
                               {
                                   UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"empty" message:strResult delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                                   [alert show];
                                   return;
                               }
                               else if([strResult isEqualToString:@"Success"])
                               {
                                   UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"empty" message:@"Data save successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                                   [alert show];
                                   
                               }

                           }];
    

    
}
@catch (NSException *exception)
{
    NSLog(@"%@",exception.description);
    
}

}

Saturday, 7 June 2014

Custom activityIndicator using objective C

-(void)StartProgressBar:(NSString *)strMessgae superView:(UIView *)view
{
    
    UIView *alertView=[[UIView alloc] initWithFrame:CGRectMake((view.frame.size.width/2)-50, (view.frame.size.height/2)-80, 100, 70)];
    alertView.tag=505;
    [alertView setBackgroundColor:[UIColor blackColor]];
    [alertView setAlpha:.7];
    alertView.layer.cornerRadius=8.0f;
    
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    //[activityIndicator setFrame:CGRectMake((alertView.frame.size.width/2)-25, 10, 55, 30)]; // Commented on 28thJan2014
    [activityIndicator setFrame:CGRectMake((alertView.frame.size.width/2)-25, 20, 55, 30)];
    [activityIndicator startAnimating];
    [alertView addSubview:activityIndicator];
    
    // Commented on 28thJan2014 START --
//    UILabel *lbl=[[UILabel alloc] initWithFrame:CGRectMake(0, 40, alertView.frame.size.width, 30)];
//    lbl.text=strMessgae;
//    [lbl setBackgroundColor:[UIColor clearColor]];
//    [lbl setTextColor:[UIColor whiteColor]];
//    [lbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:11]];
//    [lbl setTextAlignment:NSTextAlignmentCenter];
//    [alertView addSubview:lbl];
    // -- END
    
    view.userInteractionEnabled = NO;
    self.navigationController.view.userInteractionEnabled = NO;
    [view addSubview:alertView];
    
    
}

-(void)StopProgressBar:(UIView *)view
{
    //[alertProgressBar dismissWithClickedButtonIndex:0 animated:YES];
    UIView *subView=(UIView *)[view viewWithTag:505];
    
    if (subView)
        [subView removeFromSuperview];
    
    view.userInteractionEnabled = YES;
    self.navigationController.view.userInteractionEnabled = YES;

}

Thursday, 29 May 2014

Complete code : Insert and retrieve data using sqlite

- (IBAction)saveWithSqlite:(id)sender
{
    [self initDBWithDataTable];
    [self storingDataIntoSqlite];
    [self getPersons];
}

-(void)initDBWithDataTable
{
    NSArray* arrPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* strDBPath = [arrPath objectAtIndex:0];
    
    strDBPath = [strDBPath stringByAppendingPathComponent:@"EmpDB.sqlite3"];
    BOOL isExist = [[NSFileManager defaultManager]fileExistsAtPath:strDBPath];
    
    if(sqlite3_open([strDBPath UTF8String], &sqlite)== SQLITE_OK)
    {
        if(!isExist)
        {
            
            char *error;
            const char *sqlStatement = "CREATE TABLE IF NOT EXISTS PERSON (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRSTNAME TEXT, LASTNAME TEXT, BIRTHDAY DATE)";
            if(sqlite3_exec(sqlite, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
            {
                // Create the ADDRESS table with foreign key to the PERSON table
                sqlStatement = "CREATE TABLE IF NOT EXISTS ADDRESS (ID INTEGER PRIMARY KEY AUTOINCREMENT, STREETNAME TEXT, STREETNUMBER INT, PERSONID INT, FOREIGN KEY(PERSONID) REFERENCES PERSON(ID))";
                if(sqlite3_exec(sqlite, sqlStatement, NULL, NULL, &error)== SQLITE_OK)
                {
                    NSLog(@"DataBase Created");
                }
                else
                {
                    NSLog(@"Error: %s", error);
                }
            }
            else
            {
                NSLog(@"Error: %s", error);
            }
        }
    }
    
    
}

-(void)storingDataIntoSqlite
{
    NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO PERSON (FIRSTNAME, LASTNAME, BIRTHDAY) VALUES (\"%@\", \"%@\", \"%@\")", @"Kiran",@"yadav", @"1987-02-24"];
    
    char *error;
    if ( sqlite3_exec(sqlite, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
    {
        int64_t personID = sqlite3_last_insert_rowid(sqlite);
        
        // Create insert statement for the address
        insertStatement = [NSString stringWithFormat:@"INSERT INTO ADDRESS (STREETNAME, STREETNUMBER, PERSONID) VALUES (\"%@\", \"%@\", \"%lld\")", @"Ghazipur", @"30", personID];
        if ( sqlite3_exec(sqlite, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
        {
            NSLog(@"Person inserted.");
        }
        else
        {
            NSLog(@"Error: %s", error);
        }
    }
    else
    {
        NSLog(@"Error: %s", error);
    }
}

-(NSArray*)getPersons
{
    // Allocate a persons array
    NSMutableArray *persons = [[NSMutableArray alloc]init];
    
    // Create the query statement to get all persons
    NSString *queryStatement = [NSString stringWithFormat:@"SELECT ID, FIRSTNAME, LASTNAME, BIRTHDAY FROM PERSON"];
    
    // Prepare the query for execution
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(sqlite, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
    {
        // Iterate over all returned rows
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            
            // Get associated address of the current person row
            // int personID = sqlite3_column_int(statement, 0);
            // Convert the birthday column to an NSDate
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            dateFormatter.dateFormat = @"yyyy-MM-dd";
            NSString *birthdayAsString = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 3)];
            NSDate *birthday = [dateFormatter dateFromString: birthdayAsString];
            NSLog(@"%@",birthday);
            // Create a new person and add it to the array
            
            NSString* str1 =    [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
            NSString* str2 =    [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 2)];
            
            [persons addObject:str1];
            [persons addObject:str2];
            
            
        }
        sqlite3_finalize(statement);
    }
    return persons;
    
}

Tuesday, 15 April 2014

Binary Search in IOS using objective C

-(void)binary_searchh
{
    NSMutableArray* arr = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"7",@"10",@"45",@"90",nil];
    int value =  90;
    int min = 0;
    int max = 5;
    for (int i=0; i<[arr count]; i++)
    {
        int mid = (min+max)/2;
        if(value>[[arr objectAtIndex:mid] integerValue] )
        {
            min = mid+1;
        }
        else if(value<[[arr objectAtIndex:mid] integerValue])
        {
            max = mid -1;
        }
        else if(value==[[arr objectAtIndex:mid] integerValue])
        {
            NSLog(@"Found %@",[arr objectAtIndex:mid]);
             NSLog(@"Found %d",i);
            break;
        }
    }

}

Friday, 11 April 2014

Example of NSXMLParser in IOS

#pragma mark - XML Data

-(void)XMLData
{
    NSURL *url = [[NSURL alloc]initWithString:@"http://four-developers.com/service1.svc/GetXmlData/aa"];
    NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
    [parser setDelegate:self];
    BOOL result = [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{

          if ( [elementName isEqualToString:@"root"])
          {
                       return;
          }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
              if ([elementName isEqualToString:@"root"])
              {
                  NSLog(@"rootelement end");
              }
              
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
              NSString *tagName = @"column";
              
              if([tagName isEqualToString:@"column"])
              {
                  NSLog(@"Value %@",string);
              }
              

}

Wednesday, 9 April 2014

Integration Of Facebook in IOS

Step 1: Install the Facebook SDK for iOS

Download the SDK and install the package by following the instruction wizard. The default install location is ~/Documents/FacebookSDK.
Download


1. Login to facebook.
2. Go to https://developers.facebook.com
3. Create new App taping  "Create a New App".
4. Write down the Appid for further use in your code some where else.
5. Now Create new project with Xcode.
6. Add the  FacebookSDK.framework from /Documents/FacebookSDK
7. Make some changes in your plist.
 
  -> FacebookAppID
 -> URL types
 -> Display Name(Optional)
8. Import header #import <FacebookSDK/FacebookSDK.h>
9. Create a property in your header of view controller
 @interface ViewController : UIViewController
@property (strong, nonatomic) FBSession *session;
@end

10 . Check the session on viewDidLoad.

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!self.session.isOpen)
    {
        // create a fresh session object
        self.session = [[FBSession alloc] init];
        [self.session openWithCompletionHandler:^(FBSession *session,
                                                         FBSessionState status,
                                                         NSError *error)
        {
            [self updateView];
        }];
    }
    else
    {
         [self updateView];
    }


}
11. If session is open then

- (void)updateView
{
  
    if (self.session.isOpen)
    {
        [FBRequestConnection startWithGraphPath:@"me/friends" parameters:[NSDictionary  dictionaryWithObjectsAndKeys:self.session.accessTokenData.accessToken,@"access_token", nil]  HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *conn ,id result ,NSError *err)
         {
             NSLog(@"%@",result);
         }];
        
    }
    else
    {
        
    }

}

Tuesday, 8 April 2014

NSOperationQueue and GCD

NSOperationQueue and GCD
NSOperationQueue predates Grand Central Dispatch and on iOS it doesn't use GCD to execute operations (this is different on Mac OS X). It uses regular background threads which have a little more overhead than GCD dispatch queues.
On the other hand, NSOperationQueue gives you a lot more control over how your operations are executed. You can define dependencies between individual operations for example, which isn't possible with plain GCD queues. It is also possible to cancel operations that have been enqueued in an NSOperationQueue (as far as the operations support it). When you enqueue a block in a GCD dispatch queue, it will definitely be executed at some point.
To sum it up, NSOperationQueue can be more suitable for long-running operations that may need to be cancelled or have complex dependencies. GCD dispatch queues are better for short tasks that should have minimum performance and memory overhead.

Monday, 7 April 2014

Category and Subclassing

Category and Subclassing

An objective-c category is useful if you want to alter the behavior of ALL instances of the class, with minimal code. Subclassing is more useful if you want to alter the behavior of only certain instances, and retain the original method for others.
Categories can be dangerous, especially if you cannot view the source of the original method, so you should generally use subclasses on third-party and private frameworks rather than a category.

Friday, 4 April 2014

Getting data from web services using NSURLSession

-(void)getMethodUsingNSURLSession
{
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:@"http://four-developers.com/service1.svc/GetData/aa"]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {
                
                NSError *err = nil ;
                NSDictionary   *responseDict = [ NSJSONSerialization JSONObjectWithData :data options : 0 error :&err];
                dict = [responseDict objectForKey : @"GetDataResult" ];
                NSLog(@"%@",dict);
           
                
            }] resume];

}

Getting data from web services using sendAsynchronousRequest with NSOperationQueue


-(void)getMethod
{
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://four-developers.com/service1.svc/GetData/aa"]];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *connectionError)
    {
        NSError *err = nil ;
        NSMutableDictionary* arr = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
       NSMutableDictionary*  dict = [arr objectForKey:@"GetDataResult"];
 NSLog(@"%@",dict);
    }];

}

Tuesday, 1 April 2014

Getting Data from server in json format using POST method


-(void)httpPostWithCustomDelegate
{
    NSError *error;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL * url = [NSURL URLWithString:@"http://four-developers.com/service1.svc/GetPostData"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPMethod:@"POST"];
    NSMutableDictionary* mapData = [[ NSMutableDictionary alloc ] init ];
    [ mapData setObject :@"aa" forKey : @"value" ];
    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
    [request setHTTPBody:postData];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        NSError *err = nil ;
        
        NSDictionary   *responseDict = [ NSJSONSerialization JSONObjectWithData :data options : 0 error :&err];
        
        NSDictionary *dict = [responseDict objectForKey : @"GetPostDataResult" ];
        NSLog(@"%@",dict);
    }];
    
    [postDataTask resume];
    
}

        OR


Note: before starting coding for retreiveDataFromPOST you must be need to import afnetworking library...


OR

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


-( void )retreiveDataFromPOST
{
    NSURL *url = [[ NSURL alloc ] initWithString :@"http://four-developers.com/service1.svc/GetPostData"];
    AFHTTPClient *httpClient = [[ AFHTTPClient alloc ] initWithBaseURL :url];
    
    [httpClient setParameterEncoding : AFJSONParameterEncoding ];
    
    [httpClient registerHTTPOperationClass :[ AFHTTPRequestOperation class ]];
    
    [httpClient setDefaultHeader : @"Content-Type" value : @"application/json" ];
    
    NSMutableDictionary* LoginDict = [[ NSMutableDictionary alloc ] init ];
    [ LoginDict setObject :@"aa" forKey : @"value" ];
    
    NSMutableURLRequest *request = [httpClient requestWithMethod : @"POST"
                                    
                                                            path :[url path ]
                                    
                                                      parameters : LoginDict ];
    
    [request setTimeoutInterval : 200 ];
    
    AFHTTPRequestOperation *operation = [[ AFHTTPRequestOperation alloc ] initWithRequest :request];
    
    [operation setCompletionBlockWithSuccess :^( AFHTTPRequestOperation *operation, id responseObject) {
        
        // Print the response body in text
        
        NSError *err = nil ;
        
        NSDictionary   *responseDict = [ NSJSONSerialization JSONObjectWithData :responseObject options : 0 error :&err];
      
        NSDictionary *dict = [responseDict objectForKey : @"GetPostDataResult" ];
        NSLog(@"%@",dict);
       
        
    }
    failure :^( AFHTTPRequestOperation *operation, NSError *error)
     
     {
         
         NSLog ( @"error login %@" ,error);
         UIAlertView *alert = [[ UIAlertView alloc ] initWithTitle : @"Alert" message : @"Network Failure" delegate : nil cancelButtonTitle : @"OK" otherButtonTitles : nil , nil ];
         
         [alert show ];
         
               self . view . userInteractionEnabled = YES ;
     }];
    
    [operation start ];


}