Tuesday 29 October 2013

Image as a left calloutaccessoryView


In native map annotation if you want to show custom image  in annotation and  discloser button as rightCalloutaccessoryView then you can do this by applying this code:


- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
  static NSString *AnnotationViewID = @"annotationViewID";
        
        MKAnnotationView *annotationView = (MKAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        
        if (annotationView == nil)
        {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] ;
        }
      annotationView.image = [UIImage imageNamed:@"marker.png"];
       UIImageView *_image_view = [[UIImageView alloc] initWithFrame:CGRectMake (0,0,31,31)];
       [_image_view setImage:[UIImage imageNamed:@"marker_similar.png"]];
       annotationView.leftCalloutAccessoryView = _image_view;
       annotationView.rightCalloutAccessoryView = [UIButton         buttonWithType:UIButtonTypeDetailDisclosure];
}




Custom Navigation and tabbar Controller to orientation support

in ios 6 and ios 5 orientation methods are changed so that you might have to face some problems.I here provide the steps how to come out from that if you gave compatibilty from ios 5 to ios 7

->First in .plist give this value for the   key UISupportedInterfaceOrientations

<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>

</array>

-> In  appDelegate apply this method:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    return UIInterfaceOrientationMaskAll;
}

->If you are using tabbar controller you have to make custom class for that.

CustomTabbarControllerViewController.h

@interface CustomTabbarControllerViewController : UITabBarController

@end

CustomTabbarControllerViewController.m

#import "CustomTabbarControllerViewController.h"

@interface CustomTabbarControllerViewController ()

@end

@implementation CustomTabbarControllerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotate
{
    return [self.selectedViewController shouldAutorotate];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return [self.selectedViewController shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}

- (NSUInteger)supportedInterfaceOrientations
{
    return [self.selectedViewController supportedInterfaceOrientations];
}
@end

the tabbar only support that orientation which is passed by its selected view controller

->If you are using navigation controller then make category of it

#import <UIKit/UIKit.h>

@interface UINavigationController (CustomUINaviagationController)
-(BOOL)shouldAutorotate;
-(NSUInteger)supportedInterfaceOrientations;

@end

#import "UINavigationController+CustomUINaviagationController.h"

@implementation UINavigationController (autorotation)

- (BOOL)shouldAutorotate {
    
    return [self.topViewController shouldAutorotate];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return [self.topViewController shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}
-(BOOL)disablesAutomaticKeyboardDismissal{
    return NO;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self.topViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
- (NSUInteger)supportedInterfaceOrientations
{
    return [self.topViewController supportedInterfaceOrientations];
}
@end

In specific view controller apply this three methods

eg. in specific PropertyListViewController if you want to support portrait mode Only.

- (NSUInteger) supportedInterfaceOrientations
{
    //Because your app is only landscape, your view controller for the view in your
    // popover needs to support only landscape
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate
{
    return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);

Monday 28 October 2013

Decode Polylines got from google map directions api and draw Polylines.

In my one of location update application i have to display shortest path between multiple flierz[Property Locations].For that I used google direction api and calculate points between them using decoding them using formula If you have to do the same thing in your application you can use this formula.


eg.

http://maps.googleapis.com/maps/api/directions/json?origin=23.030064,72.546242&destination=23.030130,72.546310&sensor=true&mode=driving

you can run this link in browser and you can get structure like this

 -routes
-legs
     -steps
      
you will get steps array so you have to apply for loop and decode polylines.

-(void)calculateRoute{

    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
    NSMutableData *data = [NSMutableData dataWithContentsOfURL:apiUrl];
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0       error:nil];
    NSString *apiResponse=@"";
    NSArray *arrSteps = [[[[[responseDict objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"steps"];
    
        for (int l=0;l<arrSteps.count; l++) {
            @autoreleasepool {
            apiResponse = [[[arrSteps objectAtIndex:l] objectForKey:@"polyline"] objectForKey:@"points"]; 
            [totalRoutes addObject:[self decodePolyLine:[apiResponse mutableCopy]] ];
         }

}

you can grab decodePolyLine from here and then added totalRoutes and then can draw polylines between them.

-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
    
    [encoded replaceOccurrencesOfString:@"\\" withString:@"\/"
options:NSLiteralSearch
  range:NSMakeRange(0, [encoded length])];
    
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
  range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init] ;
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
        
        
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5] ;
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5] ;
        // printf("[%f,", [latitude doubleValue]);
        // printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
[array addObject:loc];
        
        
}
    Count = Count +[array count];
return array;
}

To draw polylines between these points you have to make array of CLLocationCoordinate2D like this:
-(void)updateRouteView{
 @autoreleasepool {

    pointArr = malloc(sizeof(CLLocationCoordinate2D) * Count);
    
    NSUInteger k=0;
    
    for(int j=0;j<totalRoutes.count;j++)
    {
                    
                for(int i = 0; i < [[totalRoutes objectAtIndex:j] count]; i++) {
                point = MKMapPointForCoordinate([[[totalRoutes objectAtIndex:j] objectAtIndex:i] coordinate]);
                pointArr[k] = point;
                k++;

        }
    }
    routeLine = [MKPolyline polylineWithPoints:pointArr count:k];
    [mapView addOverlay:routeLine];
    }
}
then apply this method to draw polyline red color.
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *pv = [[MKPolylineView alloc] initWithPolyline:(MKPolyline*)overlay] ;
    pv.strokeColor = [UIColor redColor];
    return pv;
}

Friday 25 October 2013

Custom UITextField

In our ios application normally text field text comes just after text field edge.But if you want to give space after text field and then display text you have to give.If you want to give 5 pixel gap from x position and 7 pixel from the y poistion of text field edge ,you can get this way:


.h file

#import <UIKit/UIKit.h>

@interface UITextFieldCustom : UITextField


@end


.m file

#import "UITextFieldCustom.h"

@implementation UITextFieldCustom

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset( bounds , 5 , 7 );
}

// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset( bounds , 5 , 7 );
}


@end

whenever you put textfield in xib  give its UITextFieldCustom 

Thursday 24 October 2013

get Curernt address using CLGeocoder

So many applications use corelocation services to get location update and get curent location .So we here use CLGeocoder to get current city ,administritive area,country etc,for that you have to create CLLocation object by self ,or use got from the location update method find the code here.


 CLLocation *location  = [[CLLocation alloc] initWithLatitude:
23.03005981 longitude:
72.54624939];


 CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark;
        if(!error){
            placemark = [placemarks objectAtIndex:0];
            [ApplicationPreferences setCurrentLocation:placemark.locality];
            [ApplicationPreferences setCurrentAddress:[NSString stringWithFormat:@"%@%@%@",placemark.locality,@",",placemark.administrativeArea]];
            if(self.nowLoad==TRUE){
                [self createBackgroundThread];
            }
        }
        else{
            if(DEBUG_MODE){
                NSLog(@"There was a reverse geocoding error\n%@",
                      placemark.locality);
            }
        }
        
        
        
    }];

Dynamic set height of label

There are so many occassions when we have to set height of the label according to text displayed in label or textview etc.

NSString *text  = @"A fairy tale is a type of short story that typically features folkloric fantasy characters, such as fairiesgoblinselvestrollsdwarvesgiants,mermaids, or gnomes, and usually magic or enchantments. Fairy tales may be distinguished from other folk narratives such as legends (which generally involve belief in the veracity of the events described) and explicitly moral tales, including beast fables."

CGSize textViewSize;

textViewSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:14.0]
                                   constrainedToSize:CGSizeMake(246, FLT_MAX)
                                       lineBreakMode:UILineBreakModeCharacterWrap];
 [geographics_lbl setFrame:CGRectMake(x, y, 246, roundf(textViewSize.height))];

Play Video from URL

In so many application we can see videos are playing from the Url,we here implement that functionality in our application.

Please first define IS_IPHONE_5 macro in .pch file so you can check it it is iphone 5 then set player size according to it.


#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
  • We have to add MediaPlayer framework and import 
    #import <MediaPlayer/MediaPlayer.h> in .h file
  • We have to define variable of activity indicator and mediaPlayer object first in .h file like
      MPMoviePlayerController *moviePlayer;
      UIActivityIndicatorView *aiv;

     first create playMovieButtonPressed to create activity indicator and movie player object and set frame according to iphone 5 and other and added as a subview of current view.we create notification which notifies us when movie player finished playing.

-(IBAction)playMovieButtonPressed:(id)sender{
    
    aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    aiv.center = self.view.center;
    [self.view addSubview:aiv];
    [aiv startAnimating];
    
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    NSURL *movieURL = [NSURL URLWithString:strVideo];
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    self.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    [self setWantsFullScreenLayout:YES];
    [self.moviePlayer.view setFrame:self.view.bounds];
    if( IS_IPHONE_5 )
    {
        [self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 568)];
    }
    else{
        [self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 480)];
    }
    [self.view addSubview:self.moviePlayer.view];
    
    
    //insert the video player below the aiv
    [self.view insertSubview:self.moviePlayer.view belowSubview:aiv];
    [self.moviePlayer play];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.moviePlayer];
}
#pragma Player methods
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    MPMoviePlayerController *player = [notification object];
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:player];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    if ([player
         respondsToSelector:@selector(setFullscreen:animated:)])
    {
        
    }
    NSDictionary *notiUserInfo = [notification userInfo];
    if (notiUserInfo != nil)
    {
        NSError *errorInfo = [notiUserInfo objectForKey:@"error"];
        if ([[errorInfo domain] isEqualToString:@"MediaPlayerErrorDomain"])
        {
        }
        else{
            [self dismissModalViewControllerAnimated:YES];
        }
    }
    else{
        [self dismissModalViewControllerAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
    [player.view removeFromSuperview];
    [player stop];
    player = nil;
    [aiv stopAnimating];
    [aiv removeFromSuperview];
}

here we set full screen mode of movieplayer,when done button pressed or  becuase of error movie player stops moviePlayBackDidFinish method called.

You can grab whole code here:

.h file

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface VideoPlayViewController : UIViewController
{
    MPMoviePlayerController *moviePlayer;
    UIActivityIndicatorView *aiv;
    NSString *strVideo;
}
@property (readwrite, retain) MPMoviePlayerController *moviePlayer;

-(IBAction)playMovieButtonPressed:(id)sender;
@end

.m file

#import "VideoPlayViewController.h"

@interface VideoPlayViewController ()

@end

@implementation VideoPlayViewController
@synthesize moviePlayer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(movieLoadStateDidChange:)
                                                 name:MPMoviePlayerLoadStateDidChangeNotification
                                               object:nil];
    strVideo = @"http://flierz.wwhnetwork.net/seller/upload/video/233_125_best-funny-video-ever_06112013194721_07192013183307.mp4";
    [self playMovieButtonPressed:nil];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)movieLoadStateDidChange:(id)sender{
    NSLog(@"STATE CHANGED");
    if(MPMovieLoadStatePlaythroughOK ) {
        NSLog(@"State is Playable OK");
        NSLog(@"Enough data has been buffered for playback to continue uninterrupted..");
        aiv.hidden = YES;
        [aiv stopAnimating];
    }
    
}
-(IBAction)playMovieButtonPressed:(id)sender{
    
    aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    aiv.center = self.view.center;
    [self.view addSubview:aiv];
    [aiv startAnimating];
    
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    NSURL *movieURL = [NSURL URLWithString:strVideo];
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    self.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    [self setWantsFullScreenLayout:YES];
    //MPMovieControlStyleFullscreen;
    [self.moviePlayer.view setFrame:self.view.bounds];
    if( IS_IPHONE_5 )
    {
        [self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 568)];
    }
    else{
        [self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 480)];
    }
    [self.view addSubview:self.moviePlayer.view];
    
    
    //insert the video player below the aiv
    [self.view insertSubview:self.moviePlayer.view belowSubview:aiv];
    [self.moviePlayer play];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.moviePlayer];
}
#pragma Player methods
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    MPMoviePlayerController *player = [notification object];
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:player];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    if ([player
         respondsToSelector:@selector(setFullscreen:animated:)])
    {
        
    }
    NSDictionary *notiUserInfo = [notification userInfo];
    if (notiUserInfo != nil)
    {
        NSError *errorInfo = [notiUserInfo objectForKey:@"error"];
        if ([[errorInfo domain] isEqualToString:@"MediaPlayerErrorDomain"])
        {
        }
        else{
            [self dismissModalViewControllerAnimated:YES];
        }
    }
    else{
        [self dismissModalViewControllerAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
    [player.view removeFromSuperview];
    [player stop];
    player = nil;
    [aiv stopAnimating];
    [aiv removeFromSuperview];
}
#pragma-mark orientation methods
- (NSUInteger) supportedInterfaceOrientations
{
//to support all orientation
    return UIInterfaceOrientationMaskAll;
}
- (BOOL)shouldAutorotate
{
    return YES;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return TRUE;
}
@end

Wednesday 23 October 2013

set zoom scale in MapView to fit annotations

In location based application we are displaying annotations in MapView but  to show all annotation on screen we have to fit the zoom scale according to no of annotation and their latitude and longitude,I here apply patch when there are two annotations to fit them proper.

To fit all annotations apply this code:

-(void)zoomToFitMapAnnotations:(MKMapView*)mapView
{
    if([self.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 self.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;
    if([self.annotations count]==2){
        region.span.latitudeDelta = 5.0; // Add a little extra space on the sides
            region.span.longitudeDelta =5.0;
    }
    else{
    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;
        }
                                  
    
    //fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 0.1; // Add a little extra space on the sides
    
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];

}


Search Near by places according to lattitude longitude


There are so many applications which use location data and display nearby coffee shops , bus stations ,parks, railway stations etc.

In this example we search near by church using latitude,longitude for that  we are using google api 

-You even need your application's api key.
-You can find more search string here:

Example string is here:


Here,
- radios is in meters
- location is combination of latitude and longitude
- sensor means whether the place request came from device or not.
- key is application specific ,you need to provide it yourself for your application.

you can copy whole code from here

-(void)ParseXML_of_Google_PlacesAPI
{
    NSMutableArray *arrMap = [[NSMutableArray alloc]init];
    BOOL isListDisplay = FALSE;
    NSString *strSearchWord;
    NSString *searchField;
    NSString *PlacesURL = @"AIzaSyAgOK0X0Pmwc2BlONmyiHzn5NiKPk_QJqg";
    NSString *lattitude = @"41.0335410";
    NSString *longitude = @"-74.0475390";
    int radious = 500;
    @autoreleasepool {
        
        searchField = @"church";
        strSearchWord =  [[[[[PlacesURL stringByAppendingString:[NSString stringWithFormat:@"location=%@,%@",lattitude,longitude]] stringByAppendingString:[NSString stringWithFormat:@"&radius=%d",radious]]stringByAppendingString:[NSString stringWithFormat:@"&types=%@",searchField ]] stringByAppendingString:[NSString stringWithFormat:@"&sensor=%@",@"false"]] stringByAppendingString:[NSString stringWithFormat:@"&key=%@",@"AIzaSyAgOK0X0Pmwc2BlONmyiHzn5NiKPk_QJqg"]];
        
        NSURL *googlePlacesURL = [NSURL URLWithString:[strSearchWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        NSURLRequest *theRequest = [NSURLRequest requestWithURL:googlePlacesURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
        
        NSURLResponse *resp = nil;
        
        NSError *err = nil;
        
        NSData *xmlData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
        
        if(xmlData!=nil){
            NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:xmlData options:0 error:nil];
            NSArray *arr = [responseDict objectForKey:@"results"];
            
            NSMutableDictionary *new = [[NSMutableDictionary alloc] init];
            // new =  [[arr objectAtIndex:l] mutableCopy];
            [new setObject:searchField forKey:@"type"];
            [new setObject:arr forKey:@"Value"];
            [arrMap addObject:[NSDictionary dictionaryWithDictionary:new]];
            //
            if([arr count]>0)
            {
                isListDisplay = TRUE;
            }
        }
        else{
        }
    }


}


strike out effect in UILABEL

we can apply strike out effect to label.
If we are tagetting ios 6.0 and above then we can apply this code

  NSString* cutText = @"Hi!!!Testing going on.";
    
  NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:cutText];
    
    // making text property to strike text- NSStrikethroughStyleAttributeName
 [titleString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];
    
    // using text on label

 [lbl_title  setAttributedText:titleString];

Add Event to iCalender ,check existing event and add alert for event

In our daily life we need to set alert to remember ourself for specific task.In ios application using eventStore we can create events and set alert to it.

     First we need to add EventKit Framework in application
  • Here in our application we need to  display event name listing if perticuler event not existing in iCalender then displayed enabled calender icon and if already exists then  disabled calender icon is displyed 
  • when user tap on calender button that event should be added in iCalender with alert
      First define this variable in .h file
      EKEventStore *eventStore;

     then in your viewDidLoad method check eventstore class is available or not.
   
       - (void)viewDidLoad
     {
        [super viewDidLoad];
        eventStore = [[EKEventStore alloc] init];
        if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
        {
            // the selector is available, so we must be on iOS 6 or newer
            [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,       NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error)
                    {
                   
                    }
                    else if (!granted)
                    {
                        // display access denied error message here
                    }
                    else
                    {
                        // access granted
                        // ***** do the important stuff here *****
                    }
                });
            }];
        }
        else
        {
        }
   
    }

on calender button click check if event already exists or not and then if not add in iCalender.

first check event in Calender use this code

    -(BOOL)checkifAppointmentExists:(NSDate *)startDate withEndDate:(NSDate *)endDate withTitle:(NSString*)str{
        BOOL addinAppointment = FALSE;
       
        NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate
                                 
                                                                     endDate:endDate
                                 
                                                                   calendars:nil];
       
       
       
        // Fetch all events that match the predicate
       
        NSArray *eventsArray = [eventStore eventsMatchingPredicate:predicate];
        if([eventsArray count]>0)
        {
            if([eventsArray objectAtIndex:0])
            {
                for (EKEvent *event in eventsArray) {
                    NSString *strId = [[NSString alloc] initWithFormat:@"%@", event.title];
                    if([strId isEqualToString:str])
                        addinAppointment = TRUE;
                }
               
            }
        }
        return addinAppointment;
    }

    -(void)addIniCalender{
         int  clickedTag = alertView.tag;
                    NSString *alarmDate = (NSString*)[[self.table_showing_array objectAtIndex:clickedTag] objectForKey:@"appointmentdate"];
                    NSString *startTime = (NSString*)[[self.table_showing_array objectAtIndex:clickedTag] objectForKey:@"starttime"];
                   
                    startTime =  [NSString stringWithFormat:@"%@ %@",alarmDate,startTime];
                   
                    NSString *endTime = (NSString*)[[self.table_showing_array objectAtIndex:clickedTag] objectForKey:@"endtime"];
                    NSString *title = (NSString*)[[self.table_showing_array objectAtIndex:clickedTag] objectForKey:@"address"];
                   
                    endTime = [NSString stringWithFormat:@"%@ %@ ",alarmDate,endTime];
                   
                    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
                    event.title     = title;
                   
                   
                    NSDateFormatter *df= [[NSDateFormatter alloc] init];
                    [df setDateFormat:@"MM/dd/yyyy HH:mm"];
                   
                    NSDate *FireDate = [df dateFromString:startTime];
                   
                    NSDate *EndDate = [df dateFromString:endTime];
                   
                   
                    if([self checkifAppointmentExists:FireDate withEndDate:EndDate withTitle:title]== TRUE)
                    {
                       
                    }
                    else{
                        event.startDate = FireDate;
                        event.endDate   = EndDate;
                        event.allDay = YES;
                       
                        [event setCalendar:[eventStore defaultCalendarForNewEvents]];
                        NSArray *arrAlarm = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:FireDate]];
                        event.alarms= arrAlarm;
                       
                        NSError *err;
                        if ([eventStore saveEvent:event span:EKSpanThisEvent error:&err]) {
                            if(DEBUG_MODE){NSLog(@"Event Send");}
                        }else {
                            if(DEBUG_MODE){ NSLog(@"%@",[err localizedDescription]);}
                        }
                        UITableViewCell *cell=[tbl_showing_Details cellForRowAtIndexPath:[NSIndexPath indexPathForRow:clickedTag inSection:0]];
                        UIButton *btnSync = (UIButton*)[cell viewWithTag:TAG_SHOWINGCALBUTTON];
                        // [AppStatus showAlert:MESSAGE_TITLE message:MESSAGE_SYNC_SUCCESS delegate:self cancelButtonTitle:MESSAGE_OK];
                        [btnSync setImage:[UIImage imageNamed:@"calendfer_icon_selected.png"] forState:UIControlStateNormal];
                        [btnSync setEnabled:FALSE];
                       
                       
                    }
    }