Wednesday, 4 December 2013

Display all Annotation pin on MapView

- (void)zoomToFitMapAnnotations:(MKMapView *)mapView {
    if ([mapView.annotations count] == 0) return;
    
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(id<MKAnnotation> annotation in mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    
    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
    
    // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
    
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}



Thursday, 21 November 2013

See How to Find Latitude and Longitude from location name.


/// Required Framework
     1. CoreLocation and 2. MapKit.

Import this two file where you use bellow method

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h> 

/// This bellow code work in < 5.0

  CLGeocoder* gc = [[CLGeocoder alloc] init];
    [gc geocodeAddressString:@"Set Your Location Name" completionHandler:^(NSArray *placemarks, NSError *error)
    {
        if ([placemarks count]>0)
        {
            // get the first one
            CLPlacemark* mark = (CLPlacemark*)[placemarks objectAtIndex:0];
            double lat = mark.location.coordinate.latitude;
            double lng = mark.location.coordinate.longitude;
            CLLocationCoordinate2D objCo;
            objCo.latitude = lat;
            objCo.longitude = lng;
            
            MKCoordinateRegion region;
            region.center = objCo;
            region.span.latitudeDelta = 0.03;
            region.span.longitudeDelta = 0.03;
            
            [objMapView setRegion:region animated:YES];// set region on your mapView
            MyAnnotation *ann = [[MyAnnotation alloc] init];// i just create this Annonation object for get and set location detail
            ann.title = strLocation;
            ann.subtitle = strDetailDesc;
            ann.anntag=11111;
            ann.coordinate = objCo;
            [objMapView addAnnotation:ann];
//            MKCoordinateRegion viewregion = MKCoordinateRegionMakeWithDistance(objCo, 0.03  , 0.03);
//            [self.objMapView setRegion:viewregion animated:YES];
        }

    }];


/// This is working in any ios

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;
}

=> In this above method if your location not found then you get lat-long 0.0000

you can use above method it like bellow...

CLLocationCoordinate2D objLocaton =[appDelegate geoCodeUsingAddress:@"ahmedabad"];

NSLog(@"Location:%f && %f",objLocaton.latitude, objLocaton.longitude);


How to convert NSMutableDictionary to JSONString...

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
///Add records or any value and convert it like bellow...

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                               options:0
                                                                 error:nil];
            
if (!jsonData) {
      NSLog(@"Error");
} else {
                
      NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData  bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
      NSLog(@"\n\n JSON String ==>> %@",JSONString);
 }

Tuesday, 13 August 2013

Go to particular parent class from subclass

you can find that particular UIViewController from its navigationController's viewControllers array like bellow...

    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[YourViewController class]]) {
            //Do not forget to import that YourViewController.h
            
            [self.navigationController popToViewController:controller
                                                  animated:YES];
            break;
        }

    }

Wednesday, 29 May 2013

Watch or counter with NSTimer

take object of NSTimer and also int variable  in .h file like bellow..

    NSTimer *timer;
    int hours, minutes, seconds;
    int secondsLeft;

and just use it with bellow method

- (void)updateCounter:(NSTimer *)theTimer {
    secondsLeft++;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    //lblTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    NSLog(@"\n%02d:%02d:%02d",hours,minutes,seconds);

}

-(void)countdownTimer{
    
    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];
}

See My Answer also converstion-of-seconds-in-minutes

Thursday, 18 April 2013

Convert some Special character to the Unicode/UTF 8 character and also Unicode to NSString....


    NSString *string = @"Hello & How % Are You?";
string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
    NSLog(@"\n\n ===>> Before ==>> %@",string);
    
    NSString *string2 = string;
string2 = [string2 stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
string2 = [string2 stringByReplacingOccurrencesOfString:@"%26" withString:@"&"];
string2 = [string2 stringByReplacingOccurrencesOfString:@"%25" withString:@"%"];    
    NSLog(@"\n\n ===>> After ==>> %@",string2);

Here you get out put is:

===>> Before ==>> Hello%20%25%20How%20Are%20You?
====>> After ==>> Hello % How Are You?

See My answer from this link.. http://stackoverflow.com/questions/16081390/how-to-get-from-web-service-in-iphone/16081968#16081968

And also list of Unicode/UTF 8 Character Table.. http://www.utf8-chartable.de/

Wednesday, 13 March 2013

Just Change your date from current format to another ...



I create this method for convert some string date format to convert in another format...

Call bellow method with its 3 parameters..


1. stringDate : Pass your date which in string type.
2. dateFormat : set format which is use in your passed string date. For ex if your string date is "14-03-2013 11:22 am" then set format @"dd-MM-yyyy hh:mm a".
3. getwithFormat : Set format which you want like if you want date "14/03/2013" then just set format @"dd/MM/yyyy".

How to call this see bellow example with method..

NSString *strSDate = [self changeDateFormat:@"14-03-2013 11:22 am" dateFormat:@"dd-MM-yyyy hh:mm a" getwithFormat:@"dd/MM/yyyy"];

Output is : 14/03/2013


-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{
    
    
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:dateFormat];
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:getwithFormat];
    
    NSString *convertedString = [dateFormatter stringFromDate:date];
    NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}


Also Get Date in NSDate from NSString with my bellow custom Method...

-(NSDate *)convertStringToDate:(NSString *) date dateFormat:(NSString*)dateFormat{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *nowDate = [[[NSDate alloc] init] autorelease];
    [formatter setDateFormat:dateFormat];// set format here which format in string date
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;

}

and use it like bellow...

NSDate *startDate = [self convertStringToDate:@"2013-05-27 19:00" dateFormate:@"yyyy-MM-dd HH:mm"];
NSDate *endDate = [self convertStringToDate:@"2013-05-27 20:00" dateFormate:@"yyyy-MM-dd HH:mm"];

Sunday, 17 February 2013

not get iPhone simulator option on xcode? see this bellow answer

Some time you not seen the iPhone simulator option on xcode and just see the "Mac 64-bit" option.

so for get iPhone simulator option on xcode just change base SDK in project -> Build Setting and just set  "latest ios sdk" option instead of other.

Also see this bellow link with some other answers :

xcode-ios-project-only-shows-my-mac-64-bit-but-not-simulator-or-device

Friday, 1 February 2013

How To change day like calendar's next prev button..


#pragma mark view calnder Next Prev

-(IBAction)btnRigth_Clicked:(id)sender{
    NSLog(@"\n Right Button Clicked");
    [self NextDate:lblTitleDate.text];
}

-(IBAction)btnLeft_Clicked:(id)sender{
    NSLog(@"\n Left Button Clicked");
    [self PrevDate:lblTitleDate.text];
}

-(void)NextDate:(NSString *)strDate{
    
    NSDate *selectedDate = [[NSDate alloc]init];
    selectedDate = [self convertStringToDate:strDate];
    
    // start by retrieving day, weekday, month and year components for yourDate
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:selectedDate];
    NSInteger theDay = [todayComponents day];
    NSInteger theMonth = [todayComponents month];
    NSInteger theYear = [todayComponents year];
    
    // now build a NSDate object for yourDate using these components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:theDay]; 
    [components setMonth:theMonth]; 
    [components setYear:theYear];
    NSDate *thisDate = [gregorian dateFromComponents:components];
    [components release];
    
    // now build a NSDate object for the next day
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:1];
    NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:thisDate options:0];
    [offsetComponents release];
    [gregorian release];
    lblTitleDate.text = [self convertDateToString:nextDate];
}

-(void)PrevDate:(NSString *)strDate{
    
    NSDate *selectedDate = [[NSDate alloc]init];
    selectedDate = [self convertStringToDate:strDate];
    // start by retrieving day, weekday, month and year components for yourDate
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:selectedDate];
    NSInteger theDay = [todayComponents day];
    NSInteger theMonth = [todayComponents month];
    NSInteger theYear = [todayComponents year];
    
    // now build a NSDate object for yourDate using these components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:theDay]; 
    [components setMonth:theMonth]; 
    [components setYear:theYear];
    NSDate *thisDate = [gregorian dateFromComponents:components];
    [components release];
    
    // now build a NSDate object for the next day
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:-1];
    NSDate *prevDate = [gregorian dateByAddingComponents:offsetComponents toDate:thisDate options:0];
    [offsetComponents release];
    [gregorian release];
    lblTitleDate.text = [self convertDateToString:prevDate];
}

-(NSDate *)convertStringToDate:(NSString *) date {
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
    NSDate *nowDate = [[[NSDate alloc] init] autorelease];
    [formatter setDateFormat:@"EEEE, dd MMM yyyy"];// set format here which format in string date
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;
}

-(NSString *)convertDateToString:(NSDate *) date {
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
    NSString *nowDate = [[[NSString alloc] init] autorelease];
    [formatter setDateFormat:@"EEEE, dd MMM yyyy"];// set format here which format in string date
    
    nowDate = [formatter stringFromDate:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;
}

Saturday, 12 January 2013

Set Dyanamic Color or change the color of UIImage..

-(UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color{

    
    // load the image
//    NSString *name = @"badge.png";
    UIImage *img = [UIImage imageNamed:name];
    
    // begin a new image context, to draw our colored image onto
    UIGraphicsBeginImageContext(img.size);
    
    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // set the fill color
    [color setFill];
    
    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    // set the blend mode to color burn, and the original image
    CGContextSetBlendMode(context, kCGBlendModeColorBurn);
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
    CGContextDrawImage(context, rect, img.CGImage);
    
    // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
    CGContextClipToMask(context, rect, img.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);
    
    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //return the color-burned image
    return coloredImg;
}

use this like bellow...

    yourImageView.image = [self imageNamed:@"yourImageName" withColor:[UIColor orangeColor]];


See this link also...
and other link

Tuesday, 8 January 2013

Validation for Number with character limit

- (BOOL)NumberValidation:(NSString *)string  {
    NSUInteger newLength = [string length];
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return (([string isEqualToString:filtered])&&(newLength <= 3));
}

in your button action event just use this like bellow...

-(IBAction)ButtonPress{
    
    if ([self NumberValidation:yourString]) {
        NSLog(@"Macth here");
    }
    else {
        NSLog(@"Not Match here");
    }
}

http://stackoverflow.com/questions/9477563/how-to-enter-numbers-only-in-uitextfield-and-limit-maximum-length

Thursday, 3 January 2013

presentViewController:animated:completion: is available on iOS5 and above only, hence you get that crash.

 presentViewController:animated:completion: is available on iOS5 and above only, hence you get that crash.


Change the last part to:


if ([MFMailComposeViewController canSendMail]) 
        {
            UIImage *tempImageSave=[self captureView];
            //                imgBackBoard.image = [self captureView];
            //                [imgBackBoard.image retain];
            MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
            NSString *mailBody = @"New Image Of Retreat Caravans Posted By Paras";
            
            NSData *imageData = UIImagePNGRepresentation(tempImageSave);
            [mailComposeViewController addAttachmentData:imageData mimeType:@"image/png" fileName:@"Testing"];
            [mailComposeViewController setMessageBody:mailBody isHTML:NO];
            mailComposeViewController.mailComposeDelegate = self;
            if ([self respondsToSelector:@selector(presentViewController:animated:completion:)])
            {   //yes->so do it!
                [self presentViewController:mailComposeViewController animated:YES completion:NULL];
            }
            else
            {   //nope->we seem to be running on something prior to iOS5, do it the old way!
                [self presentModalViewController:mailComposeViewController animated:YES];
            }
//            [self presentViewController:mailComposeViewController animated:YES completion:nil];
        } 
        else 
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"e-Mail Sending Alert"
                                                            message:@"You can't send a mail"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }

Also dissmis like above..
For EX..


if([self respondsToSelector:@selector(dismissViewControllerAnimated:completion:)])
        [self dismissViewControllerAnimated:YES completion:nil];
    else
        [self dismissModalViewControllerAnimated:YES];



This will first check if the new way of presenting a viewController is supported. For making sure that this works fine in the future, as presentModalViewController: is marked as being deprecated, we only use that option if the new way is not available.

Tuesday, 1 January 2013

Get Device Model or Device Type and platform...

just use this bellow method and you will got the Device platform or Device Type

- (NSString *) platformString{
    // Gets a string with the device model
    size_t size;  
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);  
    char *machine = malloc(size);  
    sysctlbyname("hw.machine", machine, &size, NULL, 0);  
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];  
    free(machine); 
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";    
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch (1 Gen)";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch (2 Gen)";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch (3 Gen)";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch (4 Gen)";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    return platform;
}