Search code examples
iosuibuttonmkmapviewnsurlconnectionibaction

connect to server then plot coordinates on mkmapview


my problem is rather simple but I can not seem to figure it out.

I am trying to add a refresh button to my mapview that will go back to the server and retrieve new locations if there have been any updates. My code below can already make the first call to the server with viewdidload method and can plot all the locations on the server to the map. What I need now is for a button that will make this same call whenever pressed, I am using one class for all my code so please your simplest solution that will easily merge with the code will be very much appreciated.

I am also very new to ios programming so any advice on how to tidy up my code will be also appreciated.

This is my view controller that contains all my code.

//ViewController.m

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;

locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {

    [self.mapView setShowsUserLocation:YES];

} else {
    [locationManager requestWhenInUseAuthorization];
}

NSURL *jsonFileUrl = [NSURL URLWithString:@"http://sample.name/service.php"];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}

#pragma mark NSURLConnectionDataProtocol Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_downloadedData = [[NSMutableData alloc] init];
}

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

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

NSMutableArray *_locations = [[NSMutableArray alloc] init];

NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];

CLLocationCoordinate2D coordinate;

for (int i = 0; i < jsonArray.count; i++)
{
    NSDictionary *jsonElement = jsonArray[i];

    MKPointAnnotation* marker = [[MKPointAnnotation alloc] init];

    marker.title = jsonElement[@"Name"];
    marker.subtitle = jsonElement[@"Address"];
    coordinate.latitude = [jsonElement [@"Latitude"] doubleValue];
    coordinate.longitude = [jsonElement [@"Longitude"] doubleValue];

    marker.coordinate = coordinate;
    [_locations addObject:marker];
}

[self.mapView addAnnotations:_locations];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id     <MKAnnotation>)annotation
{
static NSString *identifier;
{
    if (annotation == mapView.userLocation) return nil;

    MKAnnotationView *annotationView;
    if (annotationView == nil) {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        annotationView.enabled = YES;
        annotationView.canShowCallout = YES;
        annotationView.image = [UIImage imageNamed:@"blue_pin.png"];
    } else {
        annotationView.annotation = annotation;
    }
    return annotationView;
}

return nil;
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
    [self.mapView setShowsUserLocation:YES];
}
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationCoordinate2D myLocation = [userLocation coordinate];
MKCoordinateRegion zoomRegion = MKCoordinateRegionMakeWithDistance(myLocation, 10000, 10000);
[self.mapView setRegion:zoomRegion animated:YES];
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)InterfaceOrientation
{
return (InterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

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

- (IBAction)Refresh:(id)sender {
}
@end

Solution

  • You can find my solution with comment.

    Remove your old data when you refresh or when you got the response.

    - (IBAction)action_goToManageDevice:(id)sender
    {
       [self reloadData];
    }
    
    - (void)reloadData
    {
         // Remove old annotation
         [self.mapView removeAnnotations:self.mapView.annotations];
    
         // reload your data
         NSURL *jsonFileUrl = [NSURL URLWithString:@"http://sample.name/service.php"];
         NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
         [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    }