Wednesday, 3 October 2012

Difference between Nil , nil and NULL

Difference between Nil , nil and NULL


nil is a null pointer to an Objective-C object
Nil is a null pointer to an Objective-C class. 
NULL is  a null pointer to anything else
 Actually all the three have the numeric value of 0.
  • nil == (id) 0 
  • Nil == (Class) 0 
  • NULL == (void *) 0 

simply can say that nil is a pointer to an object
    for example : 
     NSArray *array = [NSArray arrayWithObjects:@"karthik", @"prabhu", nil];

Friday, 28 September 2012

Types of Webservices

Big Webservice
     Big web service uses SOAP standard to communicate between client and server. SOAP is a XML based protocol running on top of HTTP. SOAP(Simple Object Access Protocol) is a communication protocol allow us to bypass firewall, main advantage is a platform independent and language independent.

   SOAP Message is a XML document
Four Tags in SOAP are
  • An Envelope (required) element that identifies the XML document as a SOAP message
  • An optional Header element that contains header information
  • A Body (required) element that contains call and response information
  • An optional Fault element containing errors and status information
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
<soap:Header>

</soap:Header>
<soap:Body>

  <soap:Fault>
 
  </soap:Fault>
</soap:Body>
</soap:Envelope>

WSDL (Web Services Description Language) is an XML-based language for locating and describing Web services.
     By using online tool http://sudzc.com/ we can convert our WSDL to ObjectiveC for iOS Project. This will automatically create and handle SOAP request , SOAP response respectively based on the WSDL.


RESTful Webservice
         REST stands for Representational State Transfer . RESTful web services are based on HTTP protocol and its methods are GET, POST,PUT and DELETE. REST is not a protocol and not a standard just a architecture style to communicate between client and server.

UIKeyBoard SplitView mode notification in iPAD

NSNotificationCenter is used to find the UIKeyBoard show or hide notification. From iOS5 can get the keyboard change notification (UIKeyboardDidChangeFrameNotification). Normally UIKeyboard have three modes are
 

  •        Dock
  •        UnDock
  •        Split


 Can find the keyboard show or hide notification by using name UIKeyboardWillHideNotification and UIKeyboardDidShowNotification for DOCK and UNDOCK mode.
In the split view, have to use UIKeyboardDidChangeFrameNotification to find the keyboard showor hide notification.


Register the notification in your  view controller to find keyboard changes in split view mode


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

NSString *version = [[UIDevice currentDevice] systemVersion]; 
    float version_float = [version floatValue];

        if( version_float > 5.0])  //use notification if system version iOS5 and above
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShoworHide:) name:UIKeyboardDidChangeFrameNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil]; 


In the keyboardWillShoworHide method implementation have to check for the keyboard showing or hiding

BOOL wasKeyboardVisible;
- (void) keyboardWillShoworHide:(NSNotification *)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    
    CGRect currentKbRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    BOOL keyboardVisible = CGRectIntersectsRect(currentKbRect, screenRect);
    
    if (keyboardVisible && !wasKeyboardVisible) {
        
     //keyboard visible
        
    } else if (!keyboardVisible && wasKeyboardVisible) {
    //keyboard hidden
    }
  
    wasKeyboardVisible = keyboardVisible;
   
}


Thursday, 27 September 2012

How to Custom UIKeyBoard for UITextField


                          Custom UIKeyboard 


   UITextField contains two properties

   
       // set while first responder, will not take effect until reloadInputViews is called.
@property (readwrite, retain) UIView *inputView;             
@property (readwrite, retain) UIView *inputAccessoryView;


inputView


Can use our custom UIView instead of system keyboard by using inputView property, create your own  UIView and assign to the inputView property.
  
              yourtxtfield.inputView = yourCustomKeyboardUIView;  
      
can switch our custom keyboard and  system keyboard by using  reloadInputViews (Updates the custom input and accessory views when the object is the first responder)

  change custom keyboard to system keyboard

            yourtxtfield.inputView = nil;
            [yourtxtfield  reloadInputViews];

 change system keyboard to custom keyboard
    
            youttxtfield.inputView = yourCustomKeyboardUIView;
            [self.kbtxtfield reloadInputViews];

       
replaced system keyboard by our custom UIView

inputAccessoryView

Can add a toolbar like view on top of system keyboard by using inputAccessoryView property, create your own UIView and assign to the property.

              yourtxtfield.inputAccessoryView = yourCustomtoolbarlikeUIView;
       
added toolbar like view on top of system keyboard using inputAccessoryView




This sample describes how to add a toolbar(input AccessoryView) on top of system keyboard and how to add a custom keyboard by replacing system UIKeyboard. you can also switch between custom view and system keyboard ,this sample used xib for custom keyboardview and inputAccessoryView, also describes that how to use Custom UIView and  XIB UIView.


download source code : https://github.com/karthikprabhuA/CustomKeyboardInputView-Sample
   

TOAST in iOS

iOS toast is a small popup without ok button which is similar to Android TOAST. It only fills the amount of space required for the message and the current view remains visible and interactive.

Download the source code from my github https://github.com/karthikprabhuA/Toast_iOS/

By using AKPToast class you can easily create a Android like TOAST message in iPhone/iPad application.
How to use :-
//center position toast
AKPToast* toast = [[AKPToast alloc]initWithText:@"Please wait.." toastView:self.view position:CENTER duration:SHORT];
toast.delegate = self; //you can get the toast completion event in the delegate -(void)toastCompletionDelegate
[toast show];

iPhone Currency Converter using Google RESTful services

Google providing REST URI for currency calculator

 http://www.google.com/ig/calculator?hl=en&q=10USD=?INR

We have to pass the above two arguments to get JSON result

{lhs: "10 U.S. dollars",rhs: "536.912752 Indian rupees",error: "",icc: true}

The above returned JSON is invalid so convert into a valid JSON by adding '"' to lhs , rhs, error and icc.

How to handle JSON in iOS5 and later:

            NSJSONSerialization class used to convert JSON to Foundation objects like NSDictionary, NSArray etc and vice versa. It is only available iOS5 and above.

 NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:data 
                          options:kNilOptions 
                          error:&error];  //data is NSData sent from google server
now get the resulted json in NSDictionary then we can get the result by giving the key.

 NSString* convertedvalue = [json objectForKey:@"rhs"]; 

Difference between NSURLConnection and NSData initWithContentsOfURL :-

NSURLConnection is a asynchronous request by default , it will start a thread automatically and delegates are called from that thread. 
Also NSURLConnection has a convenience class method, sendSynchronousRequest:returningResponse:error:, to load a URL request synchronously.

NSData initWithCOntentsOfURL is a synchronous method call ,so it will block the thread.
Better use dispatch_async block to run the code in separate thread, once operation completed call the main thread.

find the iphone currency converter source code :-  https://github.com/karthikprabhuA/CurrencyConverter-GoogleRESTAPI

iphone
Currency converter 




- (IBAction)convertButtonCLicked:(UIButton *)sender {
    
     if([self.progressIndicator isAnimating]  == NO)
     {
    if(self.amountTxtField.text.length > 0 && self.fromTxtField.text.length >0 && self.toTxtField.text.length > 0)
    {
        [self.progressIndicator startAnimating];
        
        dispatch_queue_t downloadQueue = dispatch_queue_create("google downloader", NULL);
        
    dispatch_async(downloadQueue, ^{
        
        NSString* amount =self.amountTxtField.text;
        NSString *fromstr = self.fromTxtField.text ;
        NSRange fromrange ;
        fromrange.length = 3;
        fromrange.location = fromstr.length - 4;
        fromstr = [fromstr substringWithRange:fromrange];
        
        NSString *tostr = self.toTxtField.text ;
        NSRange torange ;
        torange.length = 3;
        torange.location = tostr.length -4;
        tostr = [tostr substringWithRange:torange];
        
        NSString *urlAddress = [[NSString alloc] initWithFormat:GOOGLERESTURL,[NSString stringWithFormat:@"%@%@",amount,fromstr],tostr];
        NSString* escapedUrlString =
        [urlAddress stringByAddingPercentEscapesUsingEncoding:
         NSUTF8StringEncoding];
    
        NSData* data = [NSData dataWithContentsOfURL
                        [NSURL URLWithString:escapedUrlString]];
        [self performSelectorOnMainThread:@selector(updateConvertedValue:) 
                               withObject:data waitUntilDone:YES];
        
    });
        dispatch_release(downloadQueue);
    }
    else {
        [self alertMessage:@"Enter all values !"];
    }
     }
}

-(void)updateConvertedValue: (NSData*)receivedData
{
    NSString *result = [[NSString alloc] initWithBytes:[receivedData bytes] length:[receivedData length] encoding:NSUTF8StringEncoding];
    NSError *error = NULL;
    //google is not sending valid JSOn so convert into valid JSON
    NSString *resultdata = result;
    resultdata = [resultdata stringByReplacingOccurrencesOfString:@"{" withString:@"{\""];
     resultdata = [resultdata stringByReplacingOccurrencesOfString:@"," withString:@",\""];
     resultdata = [resultdata stringByReplacingOccurrencesOfString:@":" withString:@"\":"];

    NSData* data = [resultdata dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:data 
                          options:kNilOptions 
                          error:&error];
    
    NSString* convertedvalue = [json objectForKey:@"rhs"]; 
    if(error == nil)
        outputLabel.text = convertedvalue;
    else {
        outputLabel.text = @"conversion not available";
    }
     [self.progressIndicator stopAnimating];
    
}





Monday, 24 September 2012

Create UITableViewCell Shadow

How to Create UITableViewCell Shadow :-

The following code helps you to create a UITableViewCell Shadow on the rightside


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSLog(@"new cell");

UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(320, 0, 10, 44)];
shadowView.layer.shadowColor = [UIColor darkGrayColor].CGColor;
shadowView.layer.shadowRadius = 5.0;
shadowView.layer.shadowOffset = CGSizeMake(-2, 0);
shadowView.layer.shadowOpacity = 0.8;
shadowView.backgroundColor = [UIColor darkGrayColor];
shadowView.tag = 100;

shadowView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

[cell addSubview:shadowView];

}
else
{
NSLog(@"old cell");
}

return cell;
}

Move UITextField on top of UIKeyBoard

The simple way to move UITextfield on top of UIKeyBoard is to

1)Put your UIView inside UIScrollView

2)Register for keyboard notification

3)In Keyboard event find keyboard size and scroll up if UITextField present below the UIKeyboard


- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    //kbSize.height and kbSize.width vary in Orientation
  
        
        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;
        
        // If active text field is hidden by keyboard, scroll it so it's visible
        // Your application might not need or want this behavior.
        CGRect aRect = self.view.frame;
  
        aRect.size.height -= kbSize.height+(activeField.frame.size.height*2); // add textfield height when the UITextField slightly outside from keyboard view

        if (!CGRectContainsPoint(aRect, activeField.frame.origin) )
        {
            CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y- kbSize.height);
            [scrollView setContentOffset:scrollPoint animated:YES];
        }
        scrollView.contentSize = self.view.frame.size;
    
}


// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
    scrollView.contentOffset = CGPointZero;
}



Download the source code : Move-UITextField-Top-UIKeyBoard


Wednesday, 6 June 2012

Read Pdf in android

you can use intent.ACTION_VIEW and Uri to read a file.if u already have pdf reader installed then u can use Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Wednesday, 16 May 2012

Access specifier in iOS / Objective C / iPhone / iPad programming

                    Access specifier in iOS programming


  • protected (by default)
  • private
  • public
  • package
protected :-
        default access specifier in objective c is protected.

Monday, 9 January 2012

How to add and retrieve NSMutableArray value dynamically

NSMutableArray parent class is NSArray


 //Add values dynamically

 NSMutableArray* arr_country = [[NSMutableArray alloc]init];
 [arr_country addObject:@"INDIA"];
 [arr_country addObject:@"RUSSIA"];

 //retrieve array value

id maybeNSString = [arr_country objectAtIndex:(NSUInteger)0]; //return value of the zero th position

//get array count
NSInteger arr_count  = arr_country.count;