Friday, July 25, 2014

Check device OS version

Alertnative 1 :
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
           
if ([[vComp objectAtIndex:0] intValue] >= 7) {

      // OS 7 code here
}

Alertnative 2 :
NSString *reqSysVer = @"7.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    

if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {

     // OS 7 code here
}

Custom ActivityIndicator

//Display an Activity Indicator
-(void) displayActivityIndicator {

    // Set position for activityIndicator
    [self setActivityIndicatorPosition];
    
    [waitView setImage:[UIImage imageNamed:@"WaitScreen.png"]];
    
    activityIndicator= [[UIActivityIndicatorView alloc]
                        initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhiteLarge];
    
    [activityIndicator setFrame:CGRectMake(86,30,30,30)];
    [activityIndicator startAnimating];
    
    [waitView addSubview: activityIndicator];
    
    [self.view] addSubview:waitView];
    
    [activityIndicator startAnimating];
    
    //Ignore interaction for background activities
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];

}


#pragma mark -
#pragma mark setActivityIndicatorPosition
-(void) setActivityIndicatorPosition {
       
    CGRect screenSize = [[UIScreen mainScreen] bounds];      
    
     if( ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) {
        
        [waitView setFrame:CGRectMake(x,y,203,73)];
    }
    
    if(([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft ) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight)) {
                
         [waitView setFrame:CGRectMake(x1,y1,203,73)];
    }    
}


//Hide Activity Indicator
-(void) hideActivityIndicator {
    
    //Hide waitView
    [waitView setImage:[UIImage imageNamed:nil]];
    [activityIndicator stopAnimating];
    
    if ([[UIApplication sharedApplication] isIgnoringInteractionEvents]) {
        
        // Start interaction with application
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }
       
}
 


NSUserDefault usage

 //Set NSUserDefault
NSString *somePersistantValue = @"null";
    
[[NSUserDefaults standardUserDefaults] setObject:somePersistantValue forKey:@"keyName"];

[[NSUserDefaults standardUserDefaults] synchronize];

 //Get NSUserDefault
NSString *fetchPersistantValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"keyName"]; 

Set notification for Orientation

//Set Notification on Orientation change
[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification  object:nil];


//  Handle orientation change
- (void)orientationChanged:(NSNotification *)notification {

    ...
}

Using camera / gallery of device

 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
//camera selection
if(buttonIndex == 0){
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.delegate = self;
                
[self presentViewController:imagePicker animated:YES completion:nil];                
}
else {
                
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:NSLocalizedString(@"DeviceItem", @"") delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                
[alert show];
}

}       
else if(buttonIndex == 1) {   //gallery selection
            
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
   imagePicker.delegate=self;
   [self presentViewController:imagePicker animated:YES completion:nil];
}

Execute code in background

// Fetch legend details task in background
                 dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                 dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                     
                     // Perform task here

                 });

Check device orientation

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

 if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight)) {
     //Landscape mode
}
 else if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
     //Portrait mode
}

Animate UItableView while reloading table content

 //Reload tableView with animation
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationRight];  

Options :

UITableViewRowAnimationFade, UITableViewRowAnimationRight, UITableViewRowAnimationLeft, UITableViewRowAnimationTop, UITableViewRowAnimationBottom, UITableViewRowAnimationNone, UITableViewRowAnimationMiddle

Fetch gzip format response

@try {
        NSURL *url = [NSURL URLWithString:strURL];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:180.0];
        
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        //Set GZIP format
        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        
        //Set Authorization request
        if([basicAuthRequired caseInsensitiveCompare:@"Yes"] ==  NSOrderedSame) {
            
            NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
            NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
            NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
            
            [request setValue:authValue forHTTPHeaderField:@"Authorization"];
        }
        
        NSURLResponse *response = NULL;
        NSError *requestError = NULL;
        
        //NSURLConnection will automatically decode gzipped response
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
                                                                 error:&requestError];
        
        NSError *errorSuccess=nil;
        
        NSMutableDictionary  *dictionary = [[NSMutableDictionary alloc]
                                            initWithDictionary:[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&errorSuccess]];
        
        if (errorSuccess) { //Handle error if dictionary failed to generate
            [self showSecureServiceAlert];
        }
        
        return dictionary;
    }
    @catch (NSException *exception) {
        // Handle exception
        NSLog(@"Exception in fetchURLContent function");

    }

Create function with multiple parameters

 //Create function with multiple parameter
 [self createNewFileStructure : url : uniqueID : authentication : dictionary];

#pragma mark - createNewFileStructure
-(void) createNewFileStructure : (NSString *) url : (int) uniqueID  : (NSString *) authentication : (NSMutableDictionary *) dictionary {

    // Function body. Use parameters here

}

Waiting label strip on top position of device with animation

 //Show an Wait indicator
 [self showHelpLabel];


#pragma mark -
#pragma mark showHelpLabel
-(void)showHelpLabel {  // Show instructions
    
    infoLabel = [[UILabel alloc] init];
    infoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"PleaseWait", @"")];
    
    //Check OS version and set image for Toolbar button
    reqSysVer = @"7.0";
    currSysVer = [[UIDevice currentDevice] systemVersion];
    
    //Check OS version and set image for Toolbar button
    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {        
        [infoLabel setFrame:CGRectMake(0, 60,self.mapView.frame.size.width ,50)];
    }
    else {
        [infoLabel setFrame:CGRectMake(0, 0,self.mapView.frame.size.width ,50)];
    }
    
    infoLabel.numberOfLines =2;
    
    [infoLabel setBackgroundColor:[UIColor blackColor]];
    infoLabel.textAlignment = UITextAlignmentCenter;
    [infoLabel setTextColor:[UIColor whiteColor]];
    infoLabel.autoresizesSubviews = TRUE;
    infoLabel.autoresizingMask=UIViewAutoresizingFlexibleWidth;
    [self.mapView  addSubview:infoLabel];
    
    [UIView beginAnimations:@"fade" context:NULL];
[UIView setAnimationDuration:2];
[UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(reverseAnimation)];
infoLabel.alpha = 0.0;
infoLabel.alpha = 1.0;
    
[UIView commitAnimations];
}


#pragma mark -
#pragma mark reverseAnimation
-(void)reverseAnimation {
    
    [UIView beginAnimations:@"fade" context:NULL];
[UIView setAnimationDuration:2];
[UIView setAnimationDelegate:self];
    
    [UIView setAnimationDidStopSelector:@selector(removeLabel)];
    
infoLabel.alpha = 1.0;
infoLabel.alpha = 0.0;
    
[UIView commitAnimations];
}



#pragma mark -
#pragma mark HelpLabel
-(void)removeLabel { // Remove instructions
    
    [infoLabel removeFromSuperview];
}


Thursday, July 24, 2014

Restrict user from entering certain number of characters in UITextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // Restrict user in entering 25 characters in UITextField
          
    if (textField.tag==111) {
        
        const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
        int isBackSpace = strcmp(_char, "\b");
        
        if (isBackSpace == -8) {
            NSLog(@"isBackSpace");
            return YES; // is backspace
        }
        else if (textField.text.length <= 25 && range.length == 0) {
            return YES;
        }
    }
           
    return NO;

}

Change color of button in UIActionSheet


- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
    
    if ([[[UIDevice currentDevice] systemVersion] intValue]>=7) { // Change color of button in actionsheet for iOS 7
        
        if (actionSheet==actionSheetCustom) {
                      
          [[actionSheet layer] setBackgroundColor:[UIColor whiteColor].CGColor];
        
          for (UIView *subview in actionSheet.subviews) {
              if ([subview isKindOfClass:[UIButton class]]) {
                 UIButton *button = (UIButton *)subview;
                
                [button setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Background.png"]]];
              }
          }
            
        }
    }


}

Check disk space capacity

 //Invoke freeDiskspace function
 [self freeDiskspace];


//Check for Disk Space capacity
- (void)freeDiskspace {
    
    totalSpace = 0;
    totalFreeSpace = 0;
    
    __autoreleasing NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject]
                                                                            error: &error];
        
    if (dictionary) {
        
        fileSystemSizeInBytes = 0;
        freeFileSystemSizeInBytes = 0;
        
        fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];

        // freeFileSystemSizeInBytes = [NSNumber numberWithInt:1293408];
        
        NSLog(@"fileSystemSizeInBytes : %@  freeFileSystemSizeInBytes : %@ ",fileSystemSizeInBytes,freeFileSystemSizeInBytes);
        
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
                      
        NSLog(@"Memory Capacity of %llu MB with %llu MB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
        
    } else {
        
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], (int)[error code]);
    }

}

Delete an UIAlertView window (if exists)

//Code to delete an Alert Window
for (UIWindow *window in [UIApplication sharedApplication].windows) {
                        
     NSArray *subviews = window.subviews;
                       
     if ([subviews count] > 0) {
                         
          for (int k=0; k<[subviews count]; k++) {
                                
             BOOL alert = [[subviews objectAtIndex:k] isKindOfClass:[UIAlertView class]];
                                
             if (alert) {
                 NSLog(@"alert exists");
                                  
                 // Delete an Alert                                    
               [(UIAlertView *)[subviews objectAtIndex:k] dismissWithClickedButtonIndex:[(UIAlertView *)[subviews objectAtIndex:k] cancelButtonIndex] animated:NO];
                                    
                break;
             }
                                
          }
      }

 }

Email ID Validation

//Regex for Validating EmailID
-(BOOL) validateEmailIDfromString : (NSString *) s {
    
NSString * emailregexString = @"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,3})\\b" ;     
    
NSPredicate *regexText = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailregexString] ;
return ([regexText evaluateWithObject:s]);

}


if(![self validateEmailIDfromString:txtLogin]) {  
   // Invalid email ID 
}

Animate ScrollView on editing UITextField

//Declare in implementation file

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

//static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;


#pragma - UITextField Delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    //Perform Animation during Keyboard show and Hide
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    
    if (heightFraction < 0.0) {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0) {
        heightFraction = 1.0;
    }
    
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

Reverse content of Array


/ Reverse the content of Array so as to display recent
// value on top of stack

-(NSArray *) reverseArray : (NSArray *) myArray {
    
    return [[myArray reverseObjectEnumerator] allObjects];

}

Simple way to detect empty field

// Detect empty fields
-(BOOL) detectEmptyTextFields {
    
    UITextField *temp = (UITextField *)[self.Control1 viewWithTag:12];
    
    //Remove whitespaces if any in string
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
    NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
    
    NSLog(@"Value of the text field is %@",trimmedString);
    
    if (([trimmedString isEqualToString:@""])) {
        return YES;
    }
    
    NSLog(@"temp.text : %@",temp.text);
    
    if ([temp.text isEqualToString:@""] || temp.text==nil) {
        return YES;
    }
    
    return NO;

}

Compute height on control (eg.UILabel) based on text

//Compute height for label based on text
CGSize labelStringSize = [self labelStringSize:lblInput.text]; 

cell.lblInput.frame = CGRectMake(x, y, 160,labelStringSize.height);


-(CGSize)labelStringSize : (NSString *) strInput { // Detemine height based on text
    
    UILabel *tempLabel = [[UILabel alloc] init];
    tempLabel.lineBreakMode = UILineBreakModeWordWrap;
    
    tempLabel.text = [NSString stringWithFormat:@"%@",strInput];

    CGSize labelStringSize = [tempLabel.text sizeWithFont:tempLabel.font constrainedToSize:CGSizeMake(143, 9999) lineBreakMode:tempLabel.lineBreakMode];
    
    return labelStringSize;
}