Wednesday, October 29, 2014

UIAlertView function overloading

AlertView.h file

#import <Foundation/Foundation.h>

@interface AlertView : NSObject

+ (void)showAlert:(NSString*)message;
+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate;
+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag;

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons;

+ (void)showDiscardAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons;


@end

================================
AlertView.m file

#import "AlertView.h"
#define title @"PrognoCIS"

@implementation AlertView

+(void) showAlert: (NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title 
                    message:message delegate:nil  cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

+(void) showAlert: (NSString*)message WithDelegate:(id)delegate
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title   message:message
           delegate:delegate cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegate
            cancelButtonTitle:@"OK" otherButtonTitles: nil];
    
    [alert setTag:tag];
    [alert show];
}

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message
            delegate:delegate cancelButtonTitle:@"Cancel" otherButtonTitles: buttons, nil];
    
    [alertView setTag:tag];
    [alertView show];
}

+ (void)showDiscardAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title 
    message:message delegate:delegate cancelButtonTitle:@"Discard" otherButtonTitles: buttons, nil];
    
    [alertView setTag:tag];
    [alertView show];
}

@end

================================
Usage in any file :

[AlertView showAlert:@"Discard the changes?" WithDelegate:self andTag:3000 andButtons:@"Discard"];

Adjust cell height dynamically in UITableView

#define GET_BOLD_FONT_WITH_SIZE(__SIZE) ([UIFont fontWithName:FONT_BOLD size:__SIZE])

//Method declaration
-(CGSize)calculateCellHeight:(NSString*)text;

//Usage
cellHeight=[self calculateCellHeight:info.textValue];

///////////////////////////////////////////////////
// Method : calculateCellHeight
// Params : text
// Description : To adjust cell height dynamicaly
//////////////////////////////////////////////////

-(CGSize)calculateCellHeight:(NSString*)text{
    
    CGSize height;
    height = [text sizeWithFont:GET_BOLD_FONT_WITH_SIZE(14)
              constrainedToSize:CGSizeMake(300.0, 1000.0)
                  lineBreakMode:UILineBreakModeWordWrap];

    return height;

}

Restrict user from selecting future date in UIDatePickerView

Below function disables the future date in UIDatePickerView 

-(void)setMaximumDateInDatePicker {       

    [dateTimePicker setMinuteInterval:1];   
    
    NSDate* now = [NSDate date] ;
    NSCalendar* calendar = [NSCalendar currentCalendar] ;

    NSDateComponents* nowWithoutSecondsComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:now] ;

    int currentHour=nowWithoutSecondsComponents.hour;
    int currentMinute=nowWithoutSecondsComponents.minute;
    int currentSecond=nowWithoutSecondsComponents.second;
  
    NSDate *maxDate = [[NSDate alloc] initWithTimeIntervalSinceNow:((24-currentHour)*60*60)-((currentMinute*60)+currentSecond+10)];

    dateTimePicker.maximumDate = maxDate ;
    NSLog(@"maxDate : %@ ",maxDate );

}

Tuesday, October 28, 2014

Toggle animation of view (up/down) on button click

In the below code snippet SearchBar toggles up and down with animation effect

[self animateView:DOWN];

////////////////////////////////////////////////////////
// Method : animateView
// Params : direction
// Return : animate the searchview appearance
////////////////////////////////////////////////////////

- (void)animateView:(NSString *)direction {
    
    [self.view bringSubviewToFront:patientSearchbar];
    
    if ([direction isEqualToString:DOWN]) {
        
        CGRect initialFrame = CGRectMake(0, 0 - searchView.frame.size.height  
        + 44, searchView.frame.size.width, searchView.frame.size.height);
        searchView.frame = initialFrame;
        
        searchView.layer.borderColor = VIOLET_BORDER_COLOR;
        searchView.layer.masksToBounds = NO;
        searchView.layer.shadowColor = [[UIColor blackColor] CGColor];
        searchView.layer.shadowOpacity = 1.0;
        searchView.layer.shadowRadius = 10.0;
        searchView.layer.shadowOffset = CGSizeMake(0, 3);
        
        [UIView animateWithDuration:0.5 delay:0.0 
        options:UIViewAnimationOptionCurveEaseOut animations:^{  
            
            CGRect viewRect =  CGRectMake(initialFrame.origin.x
        initialFrame.origin.y + initialFrame.size.height
        initialFrame.size.width, initialFrame.size.height);
           
            searchView.frame = viewRect;
            
        } completion:^(BOOL finished) {
             // Perform completion task here
        }];
        
    } else if ([direction isEqualToString:UP]){
        
        [UIView animateWithDuration:0.5 delay:0.0 
         options:UIViewAnimationOptionCurveEaseOut animations:^{  
       
              CGRect originalFrame = CGRectMake(0, 0
         searchView.frame.size.height + 44, searchView.frame.size.width
         searchView.frame.size.height);
        
         searchView.frame = originalFrame;
            
        } completion:^(BOOL finished) {

            [searchView removeFromSuperview];
        }];
    }

}

Alternative method to check network connectivity using Reachability

Import Reachability file and create an object of Reachability


[self checkReachability];

-(void)checkReachability {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(reachabilityChanged:)
                name:kReachabilityChangedNotification object:nil];
    
    reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
    [reachability startNotifier];
}

- (void)reachabilityChanged:(NSNotification* )notification {
    
    Reachability* curReach = [notification object];

    if ([curReach currentReachabilityStatus] == NotReachable{
        NSLog(@"Server not reachable....");
        [self hideOverlay];       
    }
    else {
        NSLog(@"Server reachable ....");
        
    }

}



Create custom navigation bar back button

//**************************************************************************
//Method    : createLeftNavigationButton
//Params    : create the left navigation back button with the image
//Return    :
//**************************************************************************

#define IMAGE(imageName)    (UIImage *)[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName         ofType:IMAGE_TYPE_PNG]]

- (void)createLeftNavigationButton {
    
    //customize right bar button item
    UIView *backButtonView = [[UIView alloc] initWithFrame:NAVIGATION_BAR_BUTTON_RECT];

    [backButtonView setBackgroundColor:[UIColor clearColor]];
    
    UIButton *backButton = [[UIButton alloc] init];
    backButton.frame     = backButtonView.frame;

    [backButton addTarget:self action:@selector(backButtonClick:) 
         forControlEvents:UIControlEventTouchUpInside];

    [backButton setImage:IMAGE(@"backButton") forState:UIControlStateNormal];    
    [backButtonView addSubview:backButton];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]  
                                  initWithCustomView:backButtonView];    

}

Convert hexString to UIColor


//Usage
titleLabel.textColor = [UIColor colorFromHexString:@"#929292"];


//Method definition
- (UIColor *)colorFromHexString:(NSString *)hexString {

    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if([cleanString length] == 3) {

        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@"
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];

    }

    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }

    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;
    float alpha = ((baseValue >> 0) & 0xFF)/255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

}

Crop an image w.r.t UIImageView without reducing quality of image

//Crop an image without reducing quality of image
imageView.image=[self imageByScalingAndCroppingForSize:CGSizeMake(100, 100)]; 


//crop Image function
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = imageView.image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.1;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.1;
            }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
         
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

Monday, October 27, 2014

Push to new ViewController as per coding convention

-(IBAction)myButtonClick:(id)sender {

 BOOL animated = (sender) ? YES : NO;

 myViewController *objMyViewController = [[myViewController alloc
  initWithNibName:@"myViewController" bundle:nil];
    
 [self.navigationController pushViewController: objMyViewController 
  animated:animated];

 objMyViewController = nil;

}

Multiple inheritance in Objective-c

Objective-C doesn't support multiple inheritance, and you don't need it. Use composition:

@interface ClassA : NSObject {
  ...
}
-(void)methodA;

@end

@interface ClassB : NSObject {
  ...
}
-(void)methodB;

@end

@interface MyClass : NSObject {
    ClassA *a;
    ClassB *b;
}

-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;

-(void)methodA;
-(void)methodB;

@end


Password validation as per coding convention

//Declaration
-(BOOL) isPasswordValid:(NSString *)pwd; 

//Usage
int length=[passwordString length];        

if( length<8 || length >10 || (![self isPasswordValid:passwordString])) {
            
     NSString *alertMsg=@"Password length should be between 8 to 10 characters.Password must have at least 1 alphabet and 1 numeral(0-9)";
     
     [AlertView showAlert:alertMsg WithDelegate:self andTag:555];
     textField.text=@"";            
 }


//Method 
-(BOOL) isPasswordValid:(NSString *)pwd{
    
    NSRange rang;
    isValid=YES;
    rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
    if (!rang.length ){
        isValid=NO;// no letter        
    }    

    rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];

    if (!rang.length) {
     isValid=NO// no numb
    }

    return isValid;

}

Create a drop-down menu on button click - using UITableView

Create a UITableView with two rows. Now, on click of UIButton this tableView will appear like drop-down list and will disappear again on click (toggle case). Below function helps in creating an animation effect on UITableView.

////////////////////////////////////////////////////////
// Method : animateTableViewDown
// Params : nil
// Description : To animate clinic selection tableview down
////////////////////////////////////////////////////////
-(void)animateTableViewDown {
    
    float tableHeight = ([clinicList count]*CELL_HEIGHT)>141?141:([clinicList count]*CELL_HEIGHT);

    [UIView animateWithDuration:.5 delay:0.0 options:UIViewAnimationOptionTransitionCurlDown animations:^{

        clinicListTableView.frame = CGRectMake(self.clinicSelectionButton.frame.origin.x, self.clinicSelectionButton.frame.origin.y+self.clinicSelectionButton.frame.size.height, self.clinicSelectionButton.frame.size.width, tableHeight);

        clinicListTableView.hidden = NO;
    } completion:^(BOOL finished) {
        
    }];
}

////////////////////////////////////////////////////////
// Method : animateTableViewUp
// Params : nil
// Description : To animate clinic selection tableview up
////////////////////////////////////////////////////////
-(void)animateTableViewUp {

    [UIView animateWithDuration:1 delay:0.0 options:UIViewAnimationOptionTransitionCurlUp animations:^{

        clinicListTableView.frame = CGRectMake(self.clinicSelectionButton.frame.origin.x, self.clinicSelectionButton.frame.origin.y+self.clinicSelectionButton.frame.size.height, self.clinicSelectionButton.frame.size.width,0);

         clinicListTableView.hidden =YES;
    } completion:^(BOOL finished) {
        
    }];
    

}

Determine type of LastViewController on NavigationController stack

id lastController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count -1];
      
if([lastController isKindOfClass:[LoginViewController class]]) {
    //LastController is of type LoginVC
    //Perform some activity here  

}

Tuesday, October 14, 2014

Establish socket connection in Objective-C

//************************************************************************
// ClassName     : Communicator.h
// Created On    : 10/13/12.
// Created By    : Jayprakash Dubey
// Purpose       : Socket connection
//************************************************************************

#import <Foundation/Foundation.h>

#define REQUEST_DETAILS @"search^10|5|2|1^diab mel^abcdefrgh\r\n\r\n"

@interface Communicator : NSObject <NSStreamDelegate> {
@public
NSString *host;
int port;
    
    NSInputStream *inputStream;
    NSOutputStream *outputStream;       
}

- (void)setup;
- (void)open;
- (void)close;
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event;

@property (strong) NSInputStream *inputStream;
@property (strong) NSOutputStream *outputStream;

@end


=================================================


//************************************************************************
// ClassName     : Communicator.m
// Created On    : 10/13/12.
// Created By    : Jayprakash Dubey
// Purpose       : Socket connection
//************************************************************************

#import "Communicator.h"

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;

@implementation Communicator

@synthesize inputStream,outputStream;

//////////////////////////////////////////////////////////////////
// Method : setup
// Params :nil
// Description : Establishes a connection for socket
//////////////////////////////////////////////////////////////////

#pragma mark - Connection handlers

- (void)setup {
NSURL *url = [NSURL URLWithString:host];
NSLog(@"Setting up connection to %@ : %i", [url absoluteString], port);
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)CFBridgingRetain([url host]), port, &readStream, &writeStream);
if(!CFWriteStreamOpen(writeStream)) {
NSLog(@"Error, writeStream not open");
return;
}
    
[self open];
NSLog(@"Status of outputStream: %i", [outputStream streamStatus]);
return;
}

- (void)open {
NSLog(@"Opening streams.");
    inputStream = (NSInputStream *)CFBridgingRelease(readStream);
    outputStream = (NSOutputStream *)CFBridgingRelease(writeStream);
    
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}

- (void)close {
NSLog(@"Closing streams.");
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
[outputStream setDelegate:nil];
inputStream = nil;
outputStream = nil;
}

//////////////////////////////////////////////////////////////////
// Method : handleEvent
// Params :event
// Description : Handles events of NSStream
//////////////////////////////////////////////////////////////////

#pragma mark - NSStreamEvent delegates

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
NSLog(@"Stream triggered.");
    NSMutableString *strServerResponse = [[NSMutableString alloc] init];
    
switch(event) {
            
case NSStreamEventHasSpaceAvailable: {
if(stream == outputStream) {
NSLog(@"outputStream is ready.");
                
                NSString *response  = @"search^10|5|2|1^diab mel^abdefghjik\r\n\r\n";
                NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
                
                [outputStream write:[data bytes] maxLength:[data length]];
                [outputStream close];
            }
break;
}
case NSStreamEventHasBytesAvailable: {
         
            NSLog(@"NSStreamEventHasBytesAvailable");
            
            if (stream == inputStream) {
                NSLog(@"inputStream is ready.");
                uint8_t buffer[1024];
                int len;
                
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {
                        
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                        
                        if (nil != output) {
                            
                            NSLog(@"server said: %@", output);
                            [strServerResponse appendString:output];
                        }
                    }
                }
            }
            
break;
}
        case NSStreamEventErrorOccurred: {
            NSLog(@"Can not connect to the host!");
            
            break;
        }
case NSStreamEventEndEncountered: {
NSLog(@"Event end occured");
break;
}
default: {
NSLog(@"Stream is sending an Event: %i", event);
break;
}
}      
}

@end


=================================

Invoke socket connection :

Communicator *c = [[Communicator alloc] init];

c->host = @"http://your URL here";
c->port = port number;
[c setup];
[c open];