Friday 27 June 2014

Utility methods


Remove white space from string

 -(NSString*)trimString:(NSString *)theString  
 {  
      NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];  
      return theStringTrimmed;  
 }  


get cache directory path

 -(NSString *)applicationCacheDirectoryString  
 {  
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
   NSString *cacheDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;  
   return cacheDirectory;  
 }  

for email validation

 -(BOOL)isValidEmailAddress:(NSString *)email  
 {  
   BOOL stricterFilter = YES;   
   NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
   NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";  
   NSString *emailRegex = stricterFilter ? stricterFilterString:laxString;  
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];  
   return [emailTest evaluateWithObject:email];  
 }  

string to date conversion

 - (NSDate *)stringToDate:(NSString *)dateString withFormate:(NSString *)format  
 {  
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
   [dateFormatter setDateFormat:format];  
   NSDate *date = [dateFormatter dateFromString: dateString];  
   return date;  
 }  

date to string conversion

 -(NSString *)DateToString:(NSDate *)date withFormate:(NSString *)format  
 {  
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];  
   [formatter setDateFormat:format];//2013-07-15:10:00:00  
   NSString * strdate = [formatter stringFromDate:date];  
   return strdate;  
 }  

get the age from birthdate

 -(NSString *)getAge:(NSDate *)birthDate  
 {  
   NSDate *dateA=birthDate;  
   NSDate *dateB=[NSDate date];  
   NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
   NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit  
                         fromDate:dateA  
                          toDate:dateB  
                         options:0];  
   NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);  
   return [NSString stringWithFormat:@"%i",components.year];  
 }  

get Image of view with its all subviews

 -(UIImage *)captureView:(UIView *)view  
 {  
   CGSize imageSize = CGSizeZero;    
   imageSize=CGSizeMake(view.bounds.size.width, view.bounds.size.height);  
   UIGraphicsBeginImageContext(imageSize);  
   CGContextRef context = UIGraphicsGetCurrentContext();  
   [view.layer renderInContext:context];  
   UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();  
   UIGraphicsEndImageContext();  
   return screenShot;  
 }