Monday 24 December 2012

How to remove the null or space from string? , use these two methods..




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

-(NSString *) removeNull:(NSString *) string {    
    
NSRange range = [string rangeOfString:@"null"];
    //NSLog(@"in removeNull : %d  >>>> %@",range.length, string);
if (range.length > 0 || string == nil) {
string = @"";
}
string = [self trimString:string];
return string;
}

And call it like bellow...

        NSString *str = yourStringValue;
        str = [self removeNull:str];

Change the Appearance and BackGroundImage of cancel button of UISearchBar


  This bellow code for change the cancel button of UISearchBar
    
    for (UIView *possibleButton in searchBar.subviews)
    {
        if ([possibleButton isKindOfClass:[UIButton class]])
        {
            UIButton *cancelButton = (UIButton*)possibleButton;
            cancelButton.enabled = YES;
            [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];            
            [cancelButton setBackgroundImage:[UIImage imageNamed:@"mainbg1.png"] forState:UIControlStateNormal];
            [cancelButton setBackgroundImage:[UIImage imageNamed:@"mainbg.png"] forState:UIControlStateHighlighted];
            break;
        }
    }
     

Set Italic and Bold Font to UILable and anything else...



You have to actually ask for the bold, italic version of a font. For example:
UIFont *myFont = [UIFont fontWithName:@"Helvetica-BoldOblique" size:[UIFont systemFontSize]];
To get a list of everything available on the iPhone, put this little snippet in yourapplicationDidFinishLaunching: delegate method and look at the log output:
for (NSString *family in [UIFont familyNames]) {
    NSLog(@"%@", [UIFont fontNamesForFamilyName:family]);
}
Note: Some font names say "oblique" - this is the same as italic.
I can't see a built-in way of doing underlines - you may have to draw the line yourself.

Wednesday 19 December 2012

UserDefault with NSMutableArray ..


    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 Data in this UserDefaults Use Bellow Code...
    
    [appDelegate.yourArray addObject:yourDataString];///set your value or anything which you want to store here...
    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.yourArray];
    [appDelegate.userDefaults setObject:data forKey:@"yourArray"];
    [appDelegate.userDefaults synchronize];

And when you want to retrive data just retrive like bellow..

 i hope this help you...

Tuesday 11 December 2012

Append string with file extention


NSString *filename = @"DSC004.jpg";//suppose file name this or also file.some.jpg then it also work in the condition
NSString *ext = [filename pathExtension];
NSString *basename = [filename stringByDeletingPathExtension];
NSString *updated = [basename stringByAppendingString:@"-Add"];
NSString *finalName = [updated stringByAppendingPathExtension:ext];

Wednesday 5 December 2012

Custom Button



UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
[playButton setTitle:@"Play" forState:UIControlStateNormal];
playButton.backgroundColor = [UIColor clearColor];
[playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];

UIImage *buttonImageNormal = [UIImage imageNamed:@"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];

UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];

[playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];

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