gpt4 book ai didi

iphone - 将注释的标题设置为当前地址

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:15:38 25 4
gpt4 key购买 nike

我想获取当前位置的地址并将其设置为注释的标题。但它没有用。我认为这是因为 block ,但我不知道如何解决它。任何帮助将不胜感激。最相关的代码如下:

WhereAmIAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface WhereAmIAnnotation : NSObject <MKAnnotation>
{
CLLocation *myLocation;
NSString *addr;
}
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, copy) NSString *addr;

@end

WhereAmIAnnotation.m

#import "WhereAmIAnnotation.h"

@implementation WhereAmIAnnotation
@synthesize myLocation, addr;

- (CLLocationCoordinate2D)coordinate;
{
return self.myLocation.coordinate;
}

- (NSString *)title
{
return self.addr;
}
@end

MapViewController.m

- (IBAction)gotoCurrentLocation{
self.mapView.showsUserLocation = YES;//a bar button linked with this action
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocation *currentLocation = userLocation.location;

MKCoordinateRegion newRegion;
newRegion.center = currentLocation.coordinate;
newRegion.span.latitudeDelta = 0.02;
newRegion.span.longitudeDelta = 0.02;
[self.mapView setRegion:newRegion animated:YES];

WhereAmIAnnotation *whereAmIAnnotation = [[WhereAmIAnnotation alloc] init];
whereAmIAnnotation.myLocation = currentLocation;
whereAmIAnnotation.addr = [self addrAtLocation:currentLocation];

[self.mapView addAnnotation:whereAmIAnnotation];

self.mapView.showsUserLocation = NO;
}

- (NSString *)addrAtLocation:(CLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
self.addr = [NSString stringWithFormat:@"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
return self.addr;
}

我应该实现这个方法

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id )annotation{}

抱歉这个愚蠢的问题!

最佳答案

您在异步 block 中修改地址时返回地址。您应该将返回移到 block 内,或者创建一个协议(protocol)来处理将此信息传递回调用者。

将 block 更改为:

- (void)addrAtLocation:(CLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
whereAmIAnnotation.addr = [NSString stringWithFormat:@"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
}

然后让whereAmIAnnotation成为一个成员变量。您了解为什么这可以解决您的问题吗?

关于iphone - 将注释的标题设置为当前地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com