iOS - 动态添加时不显示基本MKAnnotation

时间:2013-11-22 13:11:54

标签: ios annotations mapkit

我正在创建一个简单的地图应用程序 - 我在pubnub频道上发送和接收位置和文本。当聊天消息进来时,我想使用一个简单的MKAnnotation来绘制聊天(我知道这是一个可怕的用户体验,我不在乎)。

当我的app委托在pubnub通道上收到消息时,它会调用主视图控制器中的方法在地图上绘制文本消息。该方法应使用最新用户位置作为引脚坐标。

我不知道为什么,但我无法在我的方法中显示注释。我尝试在方法中构建注释并显示它。我也尝试过制作一个自定义注释类,并在我的方法中调用它。当我使用相同的注释代码但在我的viewDidLoad中对其进行硬编码时,它就会很好地显示出来。任何见解都将是最受欢迎的。

我的应用代表:

#import "MyLocationAppDelegate.h"
#import "MyLocationViewController.h"

@implementation MyLocationAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    [PubNub setDelegate: self];

    return YES;
}

- (void)pubnubClient:(PubNub *)client didReceiveMessage:(PNMessage *)message
{
    NSString* text = message.message; 

    //Call drawChat method of MyLocationViewController

    MyLocationViewController *MyLocViewController = [[MyLocationViewController alloc] init];
    [MyLocViewController drawChat:text];

   }

我的视图控制器:

#import "MyLocationViewController.h"
#import "MyLocationAppDelegate.h"
#import "MyLocationAnnotation.h"


CLLocation *userLocation;

@implementation MyLocationViewController {
     CLLocationManager *locationManager;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //Delegate map view

    self.mapView.delegate = self;

    [self SetUpChat];
    [self configurePubNub];

    //Instantiate location manager
    if (nil == locationManager) {
        locationManager = [[CLLocationManager alloc] init];
    }

    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];

    NSLog(@"Application: viewDidLoad");

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    userLocation = [locations lastObject];

}

- (void)drawChat:(NSString *)message
{
    //Create new annotation object

    CLLocationCoordinate2D location;
    location.latitude = userLocation.coordinate.latitude;
    location.longitude = userLocation.coordinate.longitude;

    MyLocationAnnotation *chat = [[MyLocationAnnotation alloc] initWithLocation:location andTitle:message];

    [self.mapView addAnnotation:chat];

}

和MyLocationAnnotation.m

#import "MyLocationAnnotation.h"

@implementation MyLocationAnnotation

- (id)initWithLocation:(CLLocationCoordinate2D)coord andTitle:(NSString *)ttl {
    self = [super init];
    if (self) {
        _coordinate = coord;
        _title = ttl;
    }
    return self;
}

@end

1 个答案:

答案 0 :(得分:1)

感谢Anna指出我做错了什么我能解决这个问题:

而不是在app委托中重新声明我的主视图控制器,而是改为:

MyLocationViewController *mainController = (MyLocationViewController *) self.window.rootViewController; 
[mainController drawChat:text]; 

然后我可以使用来自app delegate的数据调用该方法。

相关问题