Tuesday, 28 April 2015

Google Map WIth Path

Google Map WIth Path


Google Map Example :


Hi Friends !!!  Here I am Trying My Best To explain how Use  Google Map In IOS. So,I think its may be very helpful to you, Because here I am Trying so simple & easy  language and method so that everyone can understand it very quickly.
Here Google map Example using the API ....

Note :- 


Adding the "-ObjC" Linker Flag


  1. Select the project file from the project navigator on the far left side of the window.
  2. Select the target for where you want to add the linker flag.
  3. Select the "Build Settings" tab
  4. Choose "All" to show all Build Settings.
  5. Scroll down to the "Linking" section, and double-click to the right of where it says "Other Linking Flags".
  6. A box will appear, Click on the "+" button to add a new linker flag.
  7. Type "-ObjC" (no quotes) and press enter.


1) First Of all Include This File:


* import Google Map SDK Which Include
- Google Maps.Bundle 
- Google Maps.Framework


2) Import Following Framework :

- SystemConfiguration.framework
- QuartzCore.framework
- OpenGLEZ.framework
- libz.dylib
- libicucore.dylib
- libc++.dylib
- ImageIO.framework
- GLKit.framework
- CoreText.framework
- CoreLocation.framework
- CoreData.framework
- AVFoundation.framework
- CoreGraphics.framework
- UIkit.framework
- GoogleMaps.framework
- Foundation.framework

3) Import Google Map Framework in
    Appdelegate :


#import <GoogleMaps/GoogleMaps.h>


and also Declare a Key in didFinishLaunchingWithOptions Method : 

[GMSServices provideAPIKey:@"AIzaSyB8b2r8hg8AbxR6ONlLLYP-UDZfYdOh1a8"];



4) Write Coding in Different View Controller

    Which is Given Below :


* First View Controller (For Data Parse and Show In Table) :

FirstViewController.h :


#import <UIKit/UIKit.h>
#import "ViewController.h"

@interface FirstViewController : UIViewController
{
    ViewController *viewobj;
}

@property(strong,nonatomic)IBOutlet UITableView *tblobj;
@property(strong,nonatomic)NSMutableArray *arrobj;

@end


FirstViewController.m :


#import "FirstViewController.h"
#import "Container.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize arrobj,tblobj;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    
arrobj = [[NSMutableArray alloc] init];
    
    [self getmymethod];
    
    
    
}

-(void)getmymethod
{
    NSHTTPURLResponse *responce = nil;
    
    NSString *urlstring = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=23.0300,72.5800&radius=5000&types=atm&keyword=&key=AIzaSyB8b2r8hg8AbxR6ONlLLYP-UDZfYdOh1a8"];
    
    NSURL *urldata = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:urldata];
    
    NSData *mydata = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:&responce error:nil];
    
    NSMutableDictionary *maindic = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:nil];
    
    NSMutableArray *arrresult = [maindic objectForKey:@"results"];
    
    for (int i=0; i < arrresult.count; i++)
    {
        Container *data = [[Container alloc] init];
        
        NSMutableDictionary *subdic = [arrresult objectAtIndex:i];
        
        NSMutableDictionary *dicgeometry = [subdic objectForKey:@"geometry"];
        
        NSMutableDictionary *diclocation = [dicgeometry objectForKey:@"location"];
        
        NSString *strlat = [diclocation objectForKey:@"lat"];
        
        data.stringlate = strlat;
        
        
        NSString *strlong = [diclocation objectForKey:@"lng"];
        
        
        data.stringlong = strlong;
        
        NSString *strname = [subdic objectForKey:@"name"];
        
        data.stringname = strname;
        
        NSString *stradd = [subdic objectForKey:@"vicinity"];
        
        data.stringadd = stradd;
        
        
        [arrobj addObject:data];
        
    }
    
    [tblobj reloadData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arrobj.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Container *data1 = [arrobj objectAtIndex:indexPath.row];
    
    UITableViewCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
    }
    
    cell.textLabel.text = data1.stringname;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Container *mydata = [arrobj objectAtIndex:indexPath.row];
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    viewobj = [story instantiateViewControllerWithIdentifier:@"ViewController"];
    
    viewobj.strlat = mydata.stringlate;
    viewobj.strlong = mydata.stringlong;
    viewobj.strname = mydata.stringname;
    viewobj.stradd = mydata.stringadd;
    
    
    [self.navigationController pushViewController:viewobj animated:YES];
}

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

@end



* Second View Controller (For GooleMap And Show Path) :

ViewController.h :



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

@interface ViewController : UIViewController<CLLocationManagerDelegate>


{
    CLLocationManager *locationmanager;

    CLLocationDegrees lat_dest1;
    CLLocationDegrees lng_dest1;
    
    CLLocationDegrees Curr_lat;
    CLLocationDegrees Curr_lng;
}

@property (nonatomic,strong)CLLocationManager *locationmanager;


@property(strong,nonatomic)NSString *strlat;
@property(strong,nonatomic)NSString *strlong;
@property(strong,nonatomic)NSString *strname;
@property(strong,nonatomic)NSString *stradd;


@end


ViewController.m :

#import "ViewController.h"
#import <GoogleMaps/GoogleMaps.h>

@interface ViewController ()

@end

@implementation ViewController
@synthesize strlat,strlong,strname,stradd;
@synthesize locationmanager;


GMSMapView *mapView_;


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    
    NSLog(@"%@",strlat);
    NSLog(@"%@",strlong);
    NSLog(@"%@",strname);
    NSLog(@"%@",stradd);
    
    
    locationmanager = [[CLLocationManager alloc] init];
    locationmanager.delegate = self;
    locationmanager.desiredAccuracy=kCLLocationAccuracyBest;
    locationmanager.distanceFilter=kCLDistanceFilterNone;

    
// Create a GMSCameraPosition that tells the map to display the
    // coordinate at zoom level 6.
    
    double a = [strlat doubleValue];
    double b = [strlong doubleValue];
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:a
                                                            longitude:b
                                                                 zoom:15];
    
    
    
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView_.myLocationEnabled = YES;
    self.view = mapView_;
    
    
    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(a, b);
    marker.title = [NSString stringWithFormat:@"%@" ,strname];
    marker.snippet = [NSString stringWithFormat:@"%@" ,stradd];
    marker.map = mapView_;
    
    GMSMarker *currentmarker = [[GMSMarker alloc] init];
    currentmarker.position = CLLocationCoordinate2DMake(locationmanager.location.coordinate.latitude, locationmanager.location.coordinate.longitude);

    currentmarker.title = @"current mark";
    currentmarker.snippet = @"You are Here";
    currentmarker.map = mapView_;

     self.mapView.settings.myLocationButton = YES;


    mapView.mapType = kGMSTypeNormal;
    
    mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;


}

-(void)viewWillAppear:(BOOL)animated
{
    /*
    
    GMSMutablePath *path = [GMSMutablePath path];
    
    [path addCoordinate:CLLocationCoordinate2DMake([strlat floatValue], [strlong floatValue])];
    [path addCoordinate:CLLocationCoordinate2DMake(locationmanager.location.coordinate.latitude, locationmanager.location.coordinate.longitude)];
    
    GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
    polyline.path=path;
    polyline.strokeColor = [UIColor blueColor];
    polyline.strokeWidth = 3.f;
    polyline.geodesic = YES;
    
    
    polyline.map = mapView_;
    
    */
    
    [self myway];
    
}

-(void)myway
{
    
    CLLocationDegrees lat_dest=[strlat floatValue];
    CLLocationDegrees lng_dest=[strlong floatValue];
    lat_dest1=lat_dest;
    lng_dest1=lng_dest;
    
    NSHTTPURLResponse *responce = nil;
    
    NSString *urlstring = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true",locationmanager.location.coordinate.latitude,locationmanager.location.coordinate.longitude,lat_dest1,lng_dest1];
    
    
    NSURL *urldata = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:urldata];
    
    NSData *mydata = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:&responce error:nil];
    
    NSMutableDictionary *maindic = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:nil];
    
    NSArray *dict_routes=[maindic objectForKey:@"routes"];
    
    NSString *strStartLat;
    NSString *strStartLng;
    NSString *strEndLat;
    NSString *strEndLng;
    NSString *strText_Distance;
    NSString *strText_Time;
    
    float time=0,distance=0;
    
    
    for (int i=0; i<[dict_routes count]; i++)
    {
        NSDictionary *dict_steps=[dict_routes objectAtIndex:i];
        
        NSArray *dict_legs=[dict_steps objectForKey:@"legs"];
        
        
        for (int i=0; i<[dict_legs count]; i++)
        {
            NSDictionary *dict_steps=[dict_legs objectAtIndex:i];
            
            NSDictionary *dict_distance=[dict_steps objectForKey:@"distance"];
            
            NSDictionary *dict_duration=[dict_steps objectForKey:@"duration"];
            
            strText_Distance=[dict_distance objectForKey:@"text"];
            strText_Time=[dict_duration objectForKey:@"text"];
            
        }
        NSString *k = @"k";
        
        NSRange rang =[strText_Distance rangeOfString:k options:NSCaseInsensitiveSearch];
        
        if (rang.length == [k length])
        {
            distance=distance+[strText_Distance floatValue];
        }
        else
        {
            float temp=[strText_Distance floatValue];
            distance=distance+(temp/1000.0);
        }
        
        time=time+[strText_Time floatValue];
        
        for (int i=0; i<[dict_legs count]; i++)
        {
            
            
            GMSMutablePath *path = [GMSMutablePath path];
            [path addLatitude:locationmanager.location.coordinate.latitude longitude:locationmanager.location.coordinate.longitude];
            
            
            NSDictionary *dict_steps=[dict_legs objectAtIndex:i];
            NSArray *Arr_steps=[dict_steps objectForKey:@"steps"];
            for (int i=0; i<[Arr_steps count]; i++)
                
            {
                
                NSDictionary *dictFirst=[Arr_steps objectAtIndex:i];
                
                
                
                //                NSDictionary *dict_distance=[dictFirst objectForKey:@"distance"];
                //                NSDictionary *dict_duration=[dictFirst objectForKey:@"duration"];
                
                //                strText_Distance=[dict_distance objectForKey:@"text"];
                //                strText_Time=[dict_duration objectForKey:@"text"];
                
                NSDictionary *start_location=[dictFirst objectForKey:@"start_location"];
                NSDictionary *end_location=[dictFirst objectForKey:@"end_location"];
                
                
                strStartLat=[start_location objectForKey:@"lat"];
                strStartLng=[start_location objectForKey:@"lng"];
                strEndLat=[end_location objectForKey:@"lat"];
                strEndLng=[end_location objectForKey:@"lng"];
                
                
                
                [path addLatitude:[[start_location objectForKey:@"lat"] floatValue] longitude:[[start_location objectForKey:@"lng"] floatValue]];
                
                [path addLatitude:[[end_location objectForKey:@"lat"] floatValue] longitude:[[end_location objectForKey:@"lng"] floatValue]];
                
            }
            
            [path addLatitude:lat_dest1 longitude:lng_dest1];
            
            GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
            polyline.path=path;
            polyline.strokeColor = [UIColor orangeColor];
            polyline.strokeWidth = 3.f;
            polyline.geodesic = YES;
            polyline.map = mapView_;
            
            
        }
        
    }
    
    
    NSLog(@"%@",[NSString stringWithFormat: @"Distance=%.2f Km \nTime=%.2f",distance,time]);
    
       //    float km=0;
    //    if (distance>=1000) {
    //        km=distance/1000;
    //        lbl_distance.text=[NSString stringWithFormat: @"Distance=%2.f Km",km];
    //
    //    }
    //    else{
    //lbl_distance.text=[NSString stringWithFormat: @"Distance=%2.f Meter",distance];
    // }
    
    
}



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

@end



* NSObject Class (As a Container Of Data) :

Container.h :



#import "Container.h"

@implementation Container
@synthesize stringadd,stringlate,stringlong,stringname;

@end


Container.m :



#import <Foundation/Foundation.h>

@interface Container : NSObject

@property(strong,nonatomic)NSString *stringname;

@property(strong,nonatomic)NSString *stringlate;

@property(strong,nonatomic)NSString *stringlong;

@property(strong,nonatomic)NSString *stringadd;

@end


Tuesday, 21 April 2015

XML Parsar ( NSXml Parsar )

XML Parsar ( NSXml Parsar )



Xml Example :

Hi Friends !!!  Here I am Trying My Best To explain how Use  Xml  In IOS. So,I think its may be very helpful to you, Because here I am Trying so simple & easy  language and method so that everyone can understand it very quickly.
Here xml Example using the NSXml parser..

1) First Of Put Table View & Custom cell in  Storyboard :





3) write This Coding in View Controller

    Which is Given Below :


ViewController.h:


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSXMLParserDelegate>
{
     NSMutableData *conWebData;
     NSXMLParser*xmlParser;
     NSMutableDictionary *xmlDicts;
    NSString *currentElement;
    
    NSArray *arrobj;
    NSArray *arrname;
}

@property(strong, nonatomic) IBOutlet UITableView *tblobj;



@end


ViewController.h:


#import "ViewController.h"
#import "myCell.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize  tblobj;


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    arrobj = [[NSArray alloc] init];
    arrname = [[NSArray alloc] init];

    
// Do any additional setup after loading the view, typically from a nib.
    [self xmlParse];
    
}


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

-(void)xmlParse
{
    NSString *strRequest = [NSString stringWithFormat:@"http://ec2-54-169-64-237.ap-southeast-1.compute.amazonaws.com/v2/player/player_230558.xml"];
    
    NSURL *sRequestURL = [NSURL URLWithString:strRequest];
    
    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:sRequestURL];
    
    
    [myRequest setHTTPMethod:@"Get"];
    
    [myRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
    
    if(theConnection)
    {
         conWebData = [NSMutableData data];
    }
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
          [conWebData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
      [conWebData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
      NSLog(@"ERROR with theConenction");
      UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error Connection" message:@"Error With  Conenction" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    [alert show];
    
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
 
    
    NSString *theXml = [[NSString alloc] initWithBytes:[conWebData mutableBytes] length:[conWebData length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result :%@",theXml);
    
    NSLog(@"%@",conWebData);
    
    xmlParser = [[NSXMLParser alloc] initWithData:conWebData];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
    // [SVProgressHUD dismiss];
}


-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*) namespaceURI qualifiedName:(NSString*)qName attributes:(NSDictionary*)attributeDict
{
    
    if([elementName isEqualToString:@"pro"])
    {
        xmlDicts=[[NSMutableDictionary alloc]init];
    }

          // Here Condition in App Where Data is In Inner Block like      
          //      <yweather:location city="Chanzac" region="" country="France"/>



        //    if([elementName isEqualToString:@"yweather:location"])
       //    {
       //        NSString *strcity = [attributeDict objectForKey:@"city"];
       //        
       //        NSString *strcountry = [attributeDict objectForKey:@"country"];
       //        
      //        NSLog(@"%@",strcity);
      //        NSLog(@"%@",strcountry);
      //    }
         

    
}


-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string
{
   
    currentElement=@"";
    NSLog(@"%@",string);
    currentElement=[NSString stringWithString:string];
}

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName
{
    if([elementName isEqualToString:@"pro"])
    {
        NSLog(@"%@",xmlDicts);
        
        arrobj = [xmlDicts allValues];

        arrname = [xmlDicts allKeys];

        NSLog(@"%@",arrobj);
        
        [tblobj reloadData];

    }
    else if([elementName isEqualToString:@"pId"])
    {
        [xmlDicts setObject:currentElement forKey:@"playerid"];
    }
    else if([elementName isEqualToString:@"nm"])
    {
        [xmlDicts setObject:currentElement forKey:@"playername"];
    }
    else if([elementName isEqualToString:@"dob"])
    {
        [xmlDicts setObject:currentElement forKey:@"dateofbirth"];
    }
    else if([elementName isEqualToString:@"tm"])
    {
        [xmlDicts setObject:currentElement forKey:@"team"];
    }
    else if([elementName isEqualToString:@"pSkl"])
    {
        [xmlDicts setObject:currentElement forKey:@"pSkl"];
    }
    else if([elementName isEqualToString:@"batStl"])
    {
        [xmlDicts setObject:currentElement forKey:@"batStl"];
    }
    else if([elementName isEqualToString:@"bowStl"])
    {
        [xmlDicts setObject:currentElement forKey:@"bowStl"];
    }
    else if([elementName isEqualToString:@"bowStl"])
    {
        [xmlDicts setObject:currentElement forKey:@"bowStl"];
    }
    else if([elementName isEqualToString:@"btStrRt"])
    {
        [xmlDicts setObject:currentElement forKey:@"btStrRt"];
    }
    else if([elementName isEqualToString:@"mtchs"])
    {
        [xmlDicts setObject:currentElement forKey:@"mtchs"];
    }
    else if([elementName isEqualToString:@"fifts"])
    {
        [xmlDicts setObject:currentElement forKey:@"fifts"];
    }
    else if([elementName isEqualToString:@"hunds"])
    {
        [xmlDicts setObject:currentElement forKey:@"hunds"];
    }
    else if([elementName isEqualToString:@"rns"])
    {
        [xmlDicts setObject:currentElement forKey:@"rns"];
    }
    else if([elementName isEqualToString:@"btAvg"])
    {
        [xmlDicts setObject:currentElement forKey:@"btAvg"];
    }
    else if([elementName isEqualToString:@"highScr"])
    {
        [xmlDicts setObject:currentElement forKey:@"highScr"];
    }
    else if([elementName isEqualToString:@"bwAvg"])
    {
        [xmlDicts setObject:currentElement forKey:@"bwAvg"];
    }
    else if([elementName isEqualToString:@"bstBowling"])
    {
        [xmlDicts setObject:currentElement forKey:@"bstBowling"];
    }
    else if([elementName isEqualToString:@"fiveWkHauls"])
    {
        [xmlDicts setObject:currentElement forKey:@"fiveWkHauls"];
    }
    else if([elementName isEqualToString:@"wkts"])
    {
        [xmlDicts setObject:currentElement forKey:@"wkts"];
    }
    else if([elementName isEqualToString:@"fourWkHauls"])
    {
        [xmlDicts setObject:currentElement forKey:@"fourWkHauls"];
    }
    else if([elementName isEqualToString:@"ecoRat"])
    {
        [xmlDicts setObject:currentElement forKey:@"ecoRat"];
    }
    else if([elementName isEqualToString:@"bwStrRt"])
    {
        [xmlDicts setObject:currentElement forKey:@"bwStrRt"];
    }
    else if([elementName isEqualToString:@"sts"])
    {
        [xmlDicts setObject:currentElement forKey:@"sts"];
    }
    else if([elementName isEqualToString:@"cts"])
    {
        [xmlDicts setObject:currentElement forKey:@"cts"];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arrobj.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    myCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.txtname.text = [arrname objectAtIndex:indexPath.row];
    
    cell.txtvalue.text = [arrobj objectAtIndex:indexPath.row];
    
    return cell;
    
}


@end


Custom Cell (mycell) :

myCell.h :


#import <UIKit/UIKit.h>

@interface myCell : UITableViewCell

@property(strong,nonatomic) IBOutlet UILabel *txtname;
@property(strong,nonatomic) IBOutlet UILabel *txtvalue;

@end


myCell.m :

#import "myCell.h"

@implementation myCell
@synthesize txtname,txtvalue;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Wednesday, 4 March 2015

Local & Post Notification

Local & Post Notification



1) First Set Your Storyboard Like This :




2) Write Coding Which Is Given Below :


*ToDoListViewController (Set Notification) :

ToDoListViewController.h :



#import <UIKit/UIKit.h>

@interface ToDoListViewController : UITableViewController

@end



ToDoListViewController.m :


#import "ToDoListViewController.h"

@interface ToDoListViewController ()
- (void)reloadTable;

@end

@implementation ToDoListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadTable)
                                                 name:@"reloadData"
                                               object:nil];
}

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

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Get list of local notifications
    NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
    UILocalNotification *localNotification = [localNotifications objectAtIndex:indexPath.row];
    
    // Display notification info
    [cell.textLabel setText:localNotification.alertBody];
    [cell.detailTextLabel setText:[localNotification.fireDate description]];
    
    return cell;
}

- (void)reloadTable
{
    [self.tableView reloadData];
}




*AddToDoViewController (Show In tableView & Fire) :

AddToDoViewController.h :


#import <UIKit/UIKit.h>

@interface AddToDoViewController : UIViewController <UITextFieldDelegate>
- (IBAction)cancel:(id)sender;
- (IBAction)save:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *itemText;
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

@end



AddToDoViewController.m :

#import "AddToDoViewController.h"

@interface AddToDoViewController ()

@end

@implementation AddToDoViewController

- (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.
    
    self.itemText.delegate = self;
}

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

- (IBAction)cancel:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)save:(id)sender
{
    [self.itemText resignFirstResponder];
    
    // Get the current date
    NSDate *pickerDate = [self.datePicker date];
    
    // Schedule the notification
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = pickerDate;
    localNotification.alertBody = self.itemText.text;
    localNotification.alertAction = @"Show me the item";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    
    // Request to reload table view data
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];

    // Dismiss the view controller
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.itemText resignFirstResponder];
    return NO;
}
@end