Wednesday, October 1, 2014

Function for Password validation


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=@"";
            
 }


-(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;
}

Function to validate TextField and String

+ (BOOL) validateTextField: (UITextField*)textField
{
    if(!textField){
        return NO;
    }
    
    textField.text = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ([textField.text isEqualToString:@""]) {
        return NO;
    }
    return YES;
}


+ (BOOL) validateString: (NSString*)string
{
    if(!string)
    {
        return NO;
    }
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if([string  isEqualToString:@""] || [string isEqual:[NSNull null]] || string == nil || [string  length]==0)
    {
        return NO;
    }
    return YES;

}

Tuesday, September 30, 2014

Better way to check empty string

//Check if we have any search terms in the search dictionary.
    if( (searchBar.text==(id) [NSNull null] || [searchBar.text length]==0 || searchBar.text isEqual:@""))
    {
         [AlertView showAlert:@"Please enter a search string"];

    }

Monday, September 29, 2014

Check device for iPhone 5

#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

if(IS_IPHONE_5{

   // It's iPhone 5
}

Calculate Height of Text from Width of an UILabel

UILabel *type;
type.frame=[self calculateHeightOfTextFromWidth:type withText:type.text];

-(CGRect) calculateHeightOfTextFromWidth:(UILabel*)detailLabel withText:(NSString*)text
{
    
    CGRect currentFrame = detailLabel.frame;
    CGSize max = CGSizeMake(detailLabel.frame.size.width, 500);
    CGSize expected = [text sizeWithFont:detailLabel.font constrainedToSize:max lineBreakMode:detailLabel.lineBreakMode]; 
    currentFrame.size.height = expected.height;
    return currentFrame;
}

Load an Image from existing location and from URL

AsynchImage.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface AsynchImage : UIView{
    
    NSURLConnection* connection;
    NSMutableData* data;
    UIImageView* imageView;
}

-(void)loadImageFromURL:(NSURL*)url;
-(void)loadExistingImage:(UIImage *)image;

@end

AsynchImage.m


#import "AsynchImage.h"

#define ACTIVITY_FRAME CGRectMake(30, 35, 10, 10)
#define ACTIVITYINDICATOR_TAG 999
#define BORDER_COLOR [[UIColor colorWithRed:FLOAT_COLOR_VALUE(200) green:FLOAT_COLOR_VALUE(210) blue:FLOAT_COLOR_VALUE(232) alpha:1.0] CGColor];


@implementation AsynchImage

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)loadExistingImage:(UIImage *)image {
    
    if ([[self subviews] count]>0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];
    }
    
    UIImageView* _imageView = [[UIImageView alloc] init];
    _imageView.frame = CGRectMake(2, 2, self.frame.size.width-4, self.frame.size.height-4); 
    _imageView.image = image; 
    _imageView.layer.borderWidth= 2.5f;
    _imageView.layer.borderColor=BORDER_COLOR
    _imageView.contentMode = UIViewContentModeScaleToFill;
    _imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    [self addSubview:_imageView];
    _imageView =nil;
    [_imageView setNeedsLayout];

    [self setNeedsLayout];
}

- (void)loadImageFromURL:(NSURL *)url{
    
    self.layer.borderColor = BORDER_COLOR
    self.layer.borderWidth = 2.5f;
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc
                                                  initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame=ACTIVITY_FRAME;
    activityIndicator.center=CGPointMake(self.frame.size.width/2, self.frame.size.height/2);

    activityIndicator.tag = ACTIVITYINDICATOR_TAG;
    [self addSubview:activityIndicator];
    [activityIndicator startAnimating];
      
    if (data!=nil) { data = nil; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url                                       
cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:30.0];

    connection = [[NSURLConnection alloc]
                  initWithRequest:request delegate:self];
}

#pragma mark - delegates

- (void)connection:(NSURLConnection *)theConnection
    didReceiveData:(NSData *)incrementalData {
    if (data == nil) {
        data = [[NSMutableData alloc] initWithCapacity:2048];
    }

    [data appendData:incrementalData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
      
    connection=nil;
    
    if ([[self subviews] count]>0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];
    }
   
        imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(0, 0, self.frame.size.width-1, self.frame.size.height-1); 
        imageView.image = [UIImage imageWithData:data];
        //To crop Image
        imageView.image=[self imageByScalingAndCroppingForSize:CGSizeMake(100, 100)];      
  
        int resolution=data.length;
        if(resolution>800) {
            
        }

        imageView.contentMode=UIViewContentModeScaleToFill;
        imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth
                                      UIViewAutoresizingFlexibleHeight);
        [self addSubview:imageView];
        [imageView setNeedsLayout];
        [self setNeedsLayout];   
        imageView = nil;
        // save the image to avoid multiple downloads
       data=nil;
    
       UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self 
                          viewWithTag:ACTIVITYINDICATOR_TAG];
       [activity removeFromSuperview];
}

- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error {
    connection=nil;
   
    UIImage *image = [UIImage imageNamed:@"userImage"];
    [self loadExistingImage:image];
    
    UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self viewWithTag:ACTIVITYINDICATOR_TAG];
    [activity removeFromSuperview];
}

//crop Image
- (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;
}


@end

Remove subviews (if already exists)

if ([[self subviews] count]>0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];

}