2

I have a two view controllers (DatePickerViewController and RouteHistoryViewController). I also have the server response in DatePickerViewController. How can I pass that response to the RouteHitoryViewController. The RouteHistoryViewController has a map view.

Here is the code DatePicker.m :

#import "DatePickerViewController.h"
#import "MapAnnotation.h"

@interface DatePickerViewController ()


@end

@implementation DatePickerViewController
{
    //#define URL @"http://140e3087.ngrok.com"
#define URL3 @"http://784effb4.ngrok.com/bustracking/json/student/route_history"
    NSString *formatedDate;
    NSString *lat;
    NSString *longi;
    NSString *server_created_date;


}
@synthesize appDelagate,datePicker;

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", appDelegate);

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    formatedDate = [dateFormatter stringFromDate:self.datePicker.date];


    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)sendPicker:(id)sender;
{
    [self sendDataToServer : @"GET"];

   // NSLog(@"%@", formatedDate);

    //self.selectedDate.text =formatedDate;
}

-(void) sendDataToServer : (NSString *) method{


    NSString *beaconiD = @"EC112729B51B";
    NSString *trackerID = @"e61078a67e4233ad";//appDelagate.tracker_id;
    NSString *date = formatedDate;


    NSMutableURLRequest *request = nil;
    NSString *getURL = [NSString stringWithFormat:@"%@?beacon_id=%@&tracker_id=%@&date=%@", URL3, beaconiD, trackerID, date];
    getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url =  [NSURL URLWithString: getURL];
    request = [NSMutableURLRequest requestWithURL:url];

    NSLog(@"link: %@", getURL);

    [request setHTTPMethod:@"GET"];
    [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSLog(@"connection: %@", connection);

    if( connection )
    {
        mutData = [NSMutableData new];
    }
    else
    {
        NSLog (@"NO_CONNECTION");
        return;
    }
}

#pragma mark NSURLConnection delegates

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

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

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    NSLog (@"NO_CONNECTION");

    return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

//        NSString *jsonresultString =[jsonresultDict objectForKey:@"result"];
//        NSLog(@"%@", jsonresultString);
//        //serverResponse.text = jsonresultString;

        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:mutData options:kNilOptions error:&error];
        NSArray *fetchedArr = [json objectForKey:@"result"];


        for (NSDictionary *user in fetchedArr)
        {


            lat = [user objectForKey:@"latitude"];
            longi = [user objectForKey:@"longitude"];
            server_created_date = [user objectForKey:@"server_created_date"];

            NSLog(@"Item date&time : %@", server_created_date);
            NSLog(@"Item longitude : %@", longi);
            NSLog(@"Item latitude : %@", lat);
        }



} 

Here is the code RouteHistory.m:

#import "RouteHistoryViewController.h"
#import "MapAnnotation.h"

@interface RouteHistoryViewController ()

@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@end

@implementation RouteHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.mapView.delegate = self;

    //[self.mapView removeAnnotations:self.mapView.annotations];

    MapAnnotation *mapPoint = [[MapAnnotation alloc] init];
    mapPoint.coordinate = CLLocationCoordinate2DMake([self.appDelagate.latitude doubleValue], [self.appDelagate.longitude doubleValue]);
    mapPoint.title = self.appDelagate.name;
    mapPoint.time = self.appDelagate.server_created_date;
    mapPoint.mapimage = self.appDelagate.image;

    // Add it to the map view
    [self.mapView addAnnotation:mapPoint];

    // Zoom to a region around the pin
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);

    [self.mapView setRegion:region];


    //testing
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"MapUpdate"
                                               object:nil];


    // Do any additional setup after loading the view.
}
#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKPinAnnotationView *view = nil;
    static NSString *reuseIdentifier = @"MapAnnotation";

    // Return a MKPinAnnotationView with a simple accessory button

    view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
    if(!view)
    {
        view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        view.canShowCallout = YES;
        view.animatesDrop = YES;
    }

    return view;
}

datepicker to route history using prepareforsegue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ([[segue identifier]isEqualToString:@"b"])
    {
        RouteHistoryViewController *rh = segue.destinationViewController;


        NSLog(@"%@", rh);

    }

}
  • Can you show the code you go from datepicker to RouteHistory? – vien vu Dec 16 '15 at 03:53
  • Do Datepicker is a tableview? And when you tap on tableviewcell you will go RouteHistory? – vien vu Dec 16 '15 at 04:05
  • No sir, date picker view has separate button to click –  Dec 16 '15 at 05:10
  • Currently I can't clarify your flow. When will you go to routehistory? And what is data you want pass? all user data you get from server? I need this to help you resolve your problem. – vien vu Dec 16 '15 at 06:36
  • In DatePickerVIewController i have a server response (longitude,latitude,server_created_date) , i need to pass that response to the RouteHistoryViewController .. my RouteHistoryViewController has a map view –  Dec 16 '15 at 08:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98073/discussion-between-vien-vu-and-arndroid). – vien vu Dec 16 '15 at 08:17

1 Answers1

1

In first view controller inside connectionDidFinishLoading after this line

    NSArray *fetchedArr = [json objectForKey:@"result"];

add the following two lines

 _responseFromServer = fetchedArr; 
[self performSegueWithIdentifier:@"segueToRouteHistory" sender:self];

and then add this method in your first View Controller

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

 if ([[segue identifier] isEqualToString:@"segueToRouteHistory"])
 {


     RouteHistoryViewController *routeHistoryController = [segue segueToRouteHistory];

     [routeHistoryController setFetchedArray:_responseFromServer];

  }
}

In your First View Controller .h file add this

@property NSArray *responseFromServer;

Now We have assigned the Response array received from server to a object in your destination view controller.

Don't forget to add

@property NSArray *fetchedArray; 

inside your Second ViewController's .h file

Now you can access this array in second view controller. PS: Do not forget to give segue from storyboard from first view controller to second view controller and name the Segue Identifier as "segueToRouteHistory"