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 ];


}