Sunday 25 November 2012

Date and time difference from two dates...

        NSString *strDatehere = @"22/11/2012 11:12:00 PM"; // set any date with any formate
        NSDateFormatter *heredateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    assert(enUSPOSIXLocale != nil);
    
       [heredateFormatter setLocale:enUSPOSIXLocale];

       [heredateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        [heredateFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
        
        NSDate *datehere = [heredateFormatter dateFromString: strDatehere];
        
        NSTimeInterval timeDifference = [[NSDate date] timeIntervalSinceDate:datehere];
        
        double minutes = timeDifference / 60;
        
        double hours = minutes / 60;
        
        double seconds = timeDifference;
        
        double days = minutes / 1440;
        
        
        
        NSLog(@"%.0f, %.0f, %.0f, %.0f", days, hours, minutes, seconds);

Friday 23 November 2012

Set UILabel with adjust content text..

CGSize sizeToMakeLabel = [label.text sizeWithFont:label.font]; 
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, 
sizeToMakeLabel.width, sizeToMakeLabel.height); 

use bellow method for adjust the height of UILable..


-(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];

[text release];
[withFont release];

return suggestedSize.height;
}

and use it like bellow..

    UILabel *lblAddress = [[UILabel alloc]init];
    [lblAddress setFrame:CGRectMake(110, 31, 200, 50)];        
    lblAddress.text = @"your Text ";
    lblAddress.lineBreakMode = UILineBreakModeWordWrap;
    lblAddress.numberOfLines = 0;
    lblAddress.font = [UIFont fontWithName:@"Helvetica" size:12];

    lblAddress.frame = CGRectMake(lblAddress.frame.origin.x, lblAddress.frame.origin.y
                             200,[self calculateHeightOfTextFromWidth:lblAddress.text :lblAddress.font :200 :UILineBreakModeWordWrap] ); 

    lblAddress.textColor = [UIColor darkGrayColor];

    [self.view addSubview:lblAddress];

Thursday 22 November 2012

set the UISearchBar BackGroundColor and back image...





for (UIView *subview in searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"SkyBackground.jpeg"]];
            [searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            break;
        }
    }

//And for change the background of TextField of searchBar see bellow code..


UITextField *searchField;
    NSUInteger numViews = [searchBar.subviews count];
    for(int i = 0; i < numViews; i++) {
        if([[searchBar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
            searchField = [searchBar.subviews objectAtIndex:i];
        }
    }
    if(!(searchField == nil)) {
        searchField.textColor = [UIColor whiteColor];
        [searchField setBackground: [UIImage imageNamed:@"searchbox.png"]];
        [searchField setBorderStyle:UITextBorderStyleNone];
    }

For change the icon of searchbaricon


UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]];
searchIcon.frame = CGRectMake(10, 10, 24, 24);
[searchBar addSubview:searchIcon];
[searchIcon release];



and for set color 

[searchBar setTintColor:[UIColor colorWithRed:.81 green:.14 blue:.19 alpha:1]];//set alpha with your requirement

See My Answer for UISearchBar http://stackoverflow.com/questions/13817330/how-to-change-inside-background-color-of-uisearchbar-component-on-ios/13817915#13817915

Wednesday 21 November 2012

ASIHTTPRequest Tutorial..


Using ASIHTTPRequest in an iOS project

1) Add the files

Copy the files you need to your project folder, and add them to your Xcode project. An overview of the ASIHTTPRequest source files appears here.
If you aren't sure which files you need, it's best to copy all the following files:
  • ASIHTTPRequestConfig.h
  • ASIHTTPRequestDelegate.h
  • ASIProgressDelegate.h
  • ASICacheDelegate.h
  • ASIHTTPRequest.h
  • ASIHTTPRequest.m
  • ASIDataCompressor.h
  • ASIDataCompressor.m
  • ASIDataDecompressor.h
  • ASIDataDecompressor.m
  • ASIFormDataRequest.h
  • ASIInputStream.h
  • ASIInputStream.m
  • ASIFormDataRequest.m
  • ASINetworkQueue.h
  • ASINetworkQueue.m
  • ASIDownloadCache.h
  • ASIDownloadCache.m
iPhone projects must also include:
  • ASIAuthenticationDialog.h
  • ASIAuthenticationDialog.m
  • Reachability.h (in the External/Reachability folder)
  • Reachability.m (in the External/Reachability folder)

2) Link with CFNetwork, SystemConfiguration, MobileCoreServices, CoreGraphics and zlib

Open the settings for your target by clicking on the blue bar at the very top of the Xcode sidebar:


Open the Build Phases tab, expand the box labeled Link Binary With Libraries then click the plus button.


Choose CFNetwork.framework from the list, and click Add:


Repeat the last two steps to add the following: SystemConfiguration.frameworkMobileCoreServices.framework,CoreGraphics.framework and libz.dylib.

CountDown Timer in iPhone SDK


This code is used to create a countdown timer in iPhone app.

1. Code for .h file.

@interface UIMyContoller : UIViewController {

    NSTimer *timer;
    IBOutlet UILabel *myCounterLabel;
}

@property (nonatomic, retain) UILabel *myCounterLabel;
-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;

@end

2. Code for .m file.

@implementation UIMyController
@synthesize myCounterLabel;

int hours, minutes, seconds;
int secondsLeft;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    secondsLeft = 16925;
    [self countdownTimer];
}

- (void)updateCounter:(NSTimer *)theTimer {
    if(secondsLeft > 0 ){
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    }
    else{
        secondsLeft = 16925;
    }
}

-(void)countdownTimer{
    
    secondsLeft = hours = minutes = seconds = 0;
    if([timer isValid])
    {
        [timer release];
    }
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}

Animation with Push Left and Right


CATransition *animation = [CATransition animation];
    [animation setDuration:0.5];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromLeft];
    [animation setTimingFunction:[CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    self.view.center = CGPointMake(410, 205);


    [[self.view layer] addAnimation:animation forKey:@"SwitchToNoti"];

Friday 16 November 2012

Substring with string location.


see something like this srting to get string www.google.com then this is code for get string from fullstring

- (NSString *)extractString:(NSString *)fullString toLookFor:(NSString *)lookFor skipForwardX:(NSInteger)skipForward toStopBefore:(NSString *)stopBefore 
{
          NSRange firstRange = [fullString rangeOfString:lookFor]; 
          NSRange secondRange = [[fullString substringFromIndex:firstRange.location + skipForward] rangeOfString:stopBefore];
          NSRange finalRange = NSMakeRange(firstRange.location + skipForward, secondRange.location);
         return [fullString substringWithRange:finalRange];
}

use this method like bellow..

 NSString *strTemp = [self extractString:@"abcdefwww.google.comabcdef" toLookFor:@"www" skipForwardX:0 toStopBefore:@"ab"];
    NSLog(@"\n\n Substring ==>> %@",strTemp);


Thursday 15 November 2012

JSON Parsing


This "startloadingdata" method is use for external knowledge only.. here this method start operation with "loadJsonData" Method..

-(void)startloadingdata
{
      appdelegate.activityView.hidden=FALSE;
      NSOperationQueue *queue = [[NSOperationQueue alloc]init];
      NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self             selector:@selector(loadJsonData) object:nil];
      [queue addOperation:operation];
      [operation release];
      [queue release];

}

-(void)loadJsonData{
     NSURL *jsonURL = [NSURL URLWithString:yourURL];
     NSLog(@"url :%@",jsonURL);
     NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    if(jsonData == nil){
       NSLog(@"Data NIL.....");
    }
    else{
       SBJSON  *json = [[SBJSON alloc] init];
      NSError *error = nil;
      dict = [json objectWithString:jsonData error:&error];
      [json release];
   }
   [jsonData release];
    if ([dict isKindOfClass:[NSMutableDictionary class]]) {
        Result =[dict objectForKey:@"any_dict_key"];
        [Result retain];
        NSLog(@"Respoonse : %@",Result);
        
        [self performSelectorOnMainThread:@selector(loadDataDone) withObject:nil waitUntilDone:YES];
        
    }
    else{
        appdelegate.activityView.hidden = TRUE;;
    }
}

here Result is object of NSMutableArray

-(void)loadDataDone{
     if([Result count]>0)
    {
            listOfItems=[[NSMutableArray alloc]init];
           for(int j=0;j<[latersArray count];j++){
           NSMutableArray *tempArray = [[NSMutableArray alloc] init];
           for(int i=0;i<[Result count];i++){
           NSDictionary *dict = [Result objectAtIndex:i];
            if([[[dict objectForKey:@"dap_title"] substringToIndex:1] isEqualToString:[latersArray objectAtIndex:j]]){
                  [tempArray addObject:dict];
           }
     }
     [listOfItems addObject:tempArray];
     [tempArray release];
tempArray=nil;
}
        
//NSLog(@"listofitem %@",listOfItems);
[tblview reloadData];
}
else{
}
self.view.userInteractionEnabled=TRUE;
self.navigationItem.hidesBackButton=FALSE;
appdelegate.activityView.hidden=TRUE;
}

Thursday 8 November 2012

Comparison Between two Dates....


+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
     return NO;

    if ([date compare:endDate] == NSOrderedDescending) 
     return NO;

    return YES;
}

How to set Tabbar with ViewController..


set tabbarcontroller with viewcontroller like this in `AppDelegate.m` file in `didFinishLaunchingWithOptions:` method for example..

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
           UIViewController *viewController1 = [[[yourViewController1 alloc] initWithNibName:@"yourViewController1" bundle:nil] autorelease];
            UINavigationController *navviewController1=[[UINavigationController alloc]initWithRootViewController:viewController1];

           
            UIViewController *viewController2 = [[[yourViewController2 alloc] initWithNibName:@"yourViewController2" bundle:nil] autorelease];
            UINavigationController *navviewController2=[[UINavigationController alloc]initWithRootViewController:viewController2];

           
            UIViewController *viewController3 = [[[yourViewController3 alloc] initWithNibName:@"yourViewController3" bundle:nil] autorelease];
            UINavigationController *navviewController3=[[UINavigationController alloc]initWithRootViewController:viewController3];

           
            UIViewController *viewController4 = [[[yourViewController4 alloc] initWithNibName:@"yourViewController4" bundle:nil] autorelease];
            UINavigationController *navviewController4=[[UINavigationController alloc]initWithRootViewController:viewController4];

           
            UIViewController *viewController5 = [[[yourViewController5 alloc] initWithNibName:@"yourViewController5" bundle:nil] autorelease];
            UINavigationController *navviewController5=[[UINavigationController alloc]initWithRootViewController:viewController5];

           
            self.tabBarController = [[[UITabBarController alloc] init] autorelease];
            self.tabBarController.viewControllers = [NSArray arrayWithObjects:navviewController1, navviewController2,navviewController3,navviewController4,navviewController5, nil];
        [self.window makeKeyAndVisible];
        return YES;
    }

Wednesday 7 November 2012

NSUserDefault with insert,update,delete facility.


In AppDelegate.h file just declare variable...
NSUserDefaults  *userDefaults;
NSMutableArray *yourArray;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
    userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:@"yourArray"];    if (dataRepresentingtblArrayForSearch != nil) {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
        if (oldSavedArray != nil)
            yourArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];        else
            yourArray = [[NSMutableArray alloc] init];    } else {
        yourArray = [[NSMutableArray alloc] init];    }
    [yourArray retain];
after that when you want to insert,update or delete Data from this UserDefaults Use Bellow Code...
for Delete record from array
[appDelegate. yourArray removeObjectAtIndex:Index];/// give the integer value instead of Index
and this is for add record in array..
[appDelegate. yourArray addObject:AnyValue];///add value or here
after in final save this modification in array just archive like bellow..
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate. yourArray];[appDelegate.userDefaults setObject:data forKey:@"yourArray"];[appDelegate.userDefaults synchronize];
i hope this is helpful to you..