Я заполняю карту mapkit с данными из веб-сервиса JSON
. Каждая строка данных содержит набор коордов и добавляется к карте. Каждая строка также имеет URL-адрес. Проблема с моим кодом заключается в том, что в кнопке аксессуара выноска аннотации для каждой карты используется один и тот же URL (всегда последняя строка данных из массива). Ссылка - это последняя ссылка из словаря. В выводе NSLOG
ниже четвертой строки используется ссылка, используемая для каждой выноски. Разумеется, каждая выноска должна иметь свой собственный URL. dealAnnotation.title = [currentDeal objectForKey:@"vendor"];
отображает правильное имя поставщика для каждого объекта карты. Это только URL-адрес, который всегда отображает последний URL-адрес из словаря.Заселение карты данными JSON
Вот лог:
2013-02-27 11:17:35.077 link populated from map is http://www.http://www.****link1
2013-02-27 11:17:35.078 link populated from map is http://www.http://www.****link5
2013-02-27 11:17:35.079 link populated from map is http://www.http://www.****link3
2013-02-27 11:17:35.079 link populated from map is http://www.http://www.****link4
Вот мой код:
MKAnnotation с правым методом кнопки выноски pushToSafari
-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if ([annotation isMemberOfClass:[MKUserLocation class]]) return nil;
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
// annView.pinColor = MKPinAnnotationColorGreen;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
action:@selector(pushToSafari)
forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;
// annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
//add custom yd pin
annView.image = [UIImage imageNamed:@"icon-pin-2.png"];
return annView;
}
код, чтобы заполнить карту с данными. Это линия link = [currentDeal objectForKey:@"link"];
, что настройки последнего URL из JSON для каждой кнопки выноски
#pragma mark - Populate Map
- (void)populateMap:(MKMapView*)map withDeals:(NSArray*) deals
{
NSLog(@"DEALS");
for (NSDictionary *currentDeal in deals) {
CLLocationCoordinate2D ctrpoint;
ctrpoint.latitude = [[[currentDeal objectForKey:@"coords"] objectForKey:@"lat"] doubleValue];
ctrpoint.longitude =[[[currentDeal objectForKey:@"coords"] objectForKey:@"lng"] doubleValue];
MKPointAnnotation *dealAnnotation = [[MKPointAnnotation alloc] init];
dealAnnotation.coordinate = ctrpoint;
dealAnnotation.title = [currentDeal objectForKey:@"vendor"];
link = [currentDeal objectForKey:@"link"];
NSLog(@"link populated from map is %@",link);
NSDictionary *currDict = @{
@"EUR": @"€",
@"GBP": @"₤",
@"USD": @"$",
@"BRL": @"R$"
};
NSString *currName = [currentDeal objectForKey:@"currency"];
NSString *currency = [currDict objectForKey:currName];
dealAnnotation.subtitle = [NSString stringWithFormat:@"%@%i",currency,[[currentDeal objectForKey:@"price"] integerValue ]];
NSLog(@"current deal currency sym is %@",[currentDeal objectForKey:@"id"]);
[map setDelegate:self];
[map addAnnotation:dealAnnotation];
}
}
viewDidAppear: метод с кодом JSON:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"MAP VIEW APPEARED");
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSLog(@"%f %f",coordinate.latitude,coordinate.longitude);
if ((double) coordinate.latitude == 0 && (double) coordinate.longitude == 0){
CustomAlertView *alert = [[CustomAlertView alloc]initWithTitle:@"No GPS Connection" message:@"GPS data is currently unavailable. Please ensure that Location Services are turned on in Settings." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
return;
}
CLLocationDegrees currentLongitude=coordinate.longitude;
CLLocationDegrees currentLatitude=coordinate.latitude;
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(currentLatitude, currentLongitude);
[mapView setCenterCoordinate:center];
NSString *query = [NSString stringWithFormat:@"http://www.****.com/coords=45.4640,9.1916&country=%@&maxdistance=3000&api.ofilter=track:iphone",APP_ID,lang];
NSString *locationJsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:locationJsonString error:nil];
NSString *currentCity = [[[results objectForKey:@"results"] objectAtIndex:0] objectForKey:@"key"];
NSLog(@"Current city is : %@",currentCity);
NSString *dealSearch = [NSString stringWithFormat:@"http://****coords=45.4640,9.1916&maxdistance=20&api.ofilter=track:iphone",APP_ID,currentCity];
NSString *dealsInCurrentLocationJsonString = [NSString stringWithContentsOfURL:[NSURL URLWithString:dealSearch] encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding error:nil];
// SBJSON *parser2 = [[SBJSON alloc] init];
NSDictionary *dealResults = [parser objectWithString:dealsInCurrentLocationJsonString error: nil];
NSArray *listOfDeals = [dealResults objectForKey:@"results"];
[self populateMap:mapView withDeals:listOfDeals];
NSLog(@"dLongitude : %f", currentLongitude);
NSLog(@"dLatitude : %f", currentLatitude);
}
и метод правой кнопки выноски прикосновения :
-(IBAction)pushToSafari {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:link]];
NSLog(@"link touched from offers around me is %@",link);
}
спасибо за любую помощь
Почему вы называете это JSON? Вы имеете дело с массивами и словарями.Тот факт, что данные возникли как JSON, едва ли уместен. –
@HotLicks спасибо! Я внес изменения – hanumanDev
Важно не приносить нерелевантные детали при рассмотрении проблемы. Хорошо знать, что данные получены из JSON, потому что это говорит нам о том, что дерево словаря/массива будет «хорошо сформировано», но после того, как вы проанализировали JSON, нет ничего специфического для JSON в отношении полученных данных и думать об этом как JSON может вас просто смутить. –