Saturday, 25 April 2015

Experience at @Altimetrik 24 Hackathon on April 25 2015, Chennai

We +karthik prabhu  +Surendran S  +Tamil Arasan reached  +Altimetrik on April 24 7pm, organizers welcome with coffee , snacks and provided T-Shirts to all participants.....then started the event with all team introductions .. presented their presentation about the hackathon and motivated all teams to think like a entrepreneur to provide a prototype of the application. They given only one rule to the participants is  "There  is no rule" they made everyone to feel more comfortable with their environment  and we felt very more comfortable and happy.
 Given 5 real-world problem ideas to develop a prototype also given chance to develop our own idea prototype...
Had fun ....participants danced and sang a song ... +Surendran S sang minnale song..this fun activities made more cool and relaxed us to feel normal without nervous in a hackathon.
Had good dinner....
 All technical mentors, organizers interacted friendly and motivated us to create a innovative solution for the given problem. we selected smart digital visitor management problem and proposed our ideas to them , they encouraged us ...we planned to develop two iOS mobile app and one web app.We started the application with full of positive energy .... the whole night we coded...mentors and organizer cheer up and motivated the whole night without sleep...
Morning provided the freshup kits and good breakfast...
code...code....
Had good lunch....
Code code code .....completed...we prepared the presentation....and our prototype app is ready to demo...
Organizers make us to cool by giving presentation tips and appreciating...this helps us to remove our nervous and we were cool to given the presentation...
Our presentation and demo was successful.
Finally we got the winner title and price worth 30000 INR from +Altimetrik  president Mr.Ravindran   ......

This was a awesome experience in my career and looking for their next hackathon to hack


Winner price - flipkart coupon RS. 30000








Tuesday, 19 November 2013

iOS7 navigationbar Color properties

How to change iOS7 navigationbar color

self.navigationController.navigationBar.barTintColor = [UIColor blackColor]; self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.translucent = NO; 

Monday, 21 January 2013

Gzip in Objective C

Reduce client side download time 

Gzip is a compression technique better than zip . The main advantage of gzip is to upload/download data from server to client quickly. All enterprise application uses XML or JSON and the size of the XML or JSON is very big and client side will take more time to download/upload data from server, to reduce the download/upload time GZipped data is needed.
   GZip compression will reduce download and upload time from server to client and client to server respectively.
Gzip will compress XML /JSON/ HTML data upto 60% ,so its very lighter on wire to download from client side.
To improve the performance of application, can send the gziped sqlite file from server to client, then its easy to download and use the sqlite directly.

GZip in iOS :-
https://github.com/nicklockwood/GZIP


Reference :-
http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/

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;


Thursday, 10 November 2011

UINavigationBar and UINavigationItem background image

UINavigationBarItem Background Image


navigationController.parentViewController action:@selector(yourmethod:)];
             self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"leftbar.png"];

UINavigationBar Background Image

 [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header.png"] forBarMetrics:UIBarMetricsDefault];



iOS Application starts from main method

iOS application starts from main method


int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}



int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
// If nil is specified for principalClassName, the value for NSPrincipalClass from the Info.plist is used. If there is no NSPrincipalClass key specified, the UIApplication class is used. The delegate class will be instantiated using init.



Handle Orientation in iPhone/iPad


  
By default iOS5 and earlier supports only portrait mode orientation, if we want to enable all orientation we have to implement shouldAutorotateToInterfaceOrientation method in UIViewController.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES; //YES for supporting all orientation. NO- disable orientation
}

iOS have four orientations are 
   UIInterfaceOrientationPortrait
   UIInterfaceOrientationPortraitUpsideDown
   UIInterfaceOrientationLandscapeLeft    
   UIInterfaceOrientationLandscapeRight
if dont want any one orientation, then check the orientation and return NO

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if(UIInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    return NO; //disable UIInterfaceOrientationLandscapeLeft orientation
else
   return YES;
}

Find device orientation changes :-

//implement this method to find the device orientation changes - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { } If your application doesn't call didRotateFromInterfaceOrientation method then you have to add your controller as child view controller in then rootview controller. - (void)viewDidLoad { [super viewDidLoad]; [self addChildViewController:(UIViewController*) self.yourChildController]; }

Changing UIView when Orientation change :-

Here i created two UIView and assigned when orientation changed. I created two dashboard UIView for portrait and landscape , get the IBOutlet from XIB 
Views.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight ) { self.view = self.LandscapeView; } else { self.view = self.portraitView; } return YES; }
Download the source code for better understanding : https://github.com/karthikprabhuA/iPhoneOrientationHandling



Launch iPhone/iPad email composer in your application


MFMailComposeViewController  class is used to editing and email, its present in MessageUI.framework.

canSendMail method is used to find whether the user has set up the device for sending email .

Here launched email composer in my application, presenting as a modal popover.

if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.navigationBar.tintColor = [UIColor redColor]; // your navigationbar color
mail.mailComposeDelegate = self;
[mail setSubject:@"Check out my iPhone/iPad app"];
[mail setMessageBody:@"<html><body>Check out <a href='http://karthik-prabhu.blogspot.in/'>iVerde</a></body></html>" isHTML:YES];
        //mail.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
       // [self setModalPresentationStyle:UIViewAnimationOptionTransitionFlipFromTop];
            [self presentViewController:mail animated:YES completion:NULL ]; //presentModalViewController deprecated from iOS5 and above 
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"App name Message" message:@"Please setup at least One email account." delegate:self cancelButtonTitle:nil      otherButtonTitles: @"OK", nil];
[alert show];
[alert release];
}





Wednesday, 2 November 2011

How to get iPhone iPad System Properties

UIDevice Class is used to get the phone name, model, localizedModel, systemname, system version,orientation,battery level etc.

  [[UIDevice currentDevicename]
  [[UIDevice currentDevice] model]
  [[UIDevice currentDevicelocalizedModel]
  [[UIDevice currentDevicesystemName]
  [[UIDevice currentDevicesystemVersion]
  [[UIDevice currentDeviceorientation]
  [[UIDevice currentDevicebatteryLevel]


The main advantage is to check the battery level ;

float btlevel = [[UIDevice currentDevice] batteryLevel]; // range is from 0.0 to 1.0 UIDeviceBatteryState btstate = [UIDevice currentDevice] batteryStatus];


iOS(iPhone and iPad) Application Development for Beginner




  • First you need to learn objective C basics.
  • Should know about the iOS Framework.
  • Should know how the iOS controller works like UIViewController,UITableviewcontroller, UINavigationControler,UITabBarcontroller etc. 
  • Do some homework with all the controls with xib and programatically then you will get a clear idea.
  • If you want to become a master dont skip the basics.
  • My advise is to start with stanford tutorial (pdf and video) for iOS5 (http://www.stanford.edu/class/cs193p/cgi-bin/drupal/downloads-2011-fall and http://itunes.apple.com/us/itunes-u/ipad-iphone-application-development/id473757255).


Here I attached Stanford iOS basics tutorial


Stanford iOS development basics tutorial