подключитесь к серверу, затем нанесите координаты на mkmapview

моя проблема довольно проста, но я не могу понять это.

Я пытаюсь добавить кнопку обновления в свое представление карты, которая будет возвращаться на сервер и получать новые местоположения, если были какие-либо обновления. Мой код ниже уже может сделать первый вызов на сервер с помощью метода viewdidload и может нанести на карту все местоположения на сервере. Сейчас мне нужна кнопка, которая будет выполнять один и тот же вызов при каждом нажатии. Я использую один класс для всего своего кода, поэтому, пожалуйста, ваше самое простое решение, которое легко сольется с кодом, будет очень признательно.

Я также очень новичок в программировании ios, поэтому любые советы о том, как привести в порядок мой код, также будут оценены.

Это мой контроллер представления, который содержит весь мой код.

//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

person fa_devlpr    schedule 05.11.2014    source источник


Ответы (1)


Вы можете найти мое решение с комментарием.

Удалите свои старые данные при обновлении или при получении ответа.

- (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];
}
person ben_    schedule 05.11.2014