我正在制作一个简单的地图应用程序-我在公共频道上发送和接收位置和文本。当收到聊天消息时,我想用一个简单的MKAnnotation来绘制聊天(我知道这是一个可怕的用户体验行为,我不在乎)。
当我的应用程序代理在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
多亏了Anna指出我做错了什么,我才得以解决这个问题:
我没有在应用程序代理中重新清理我的主视图控制器,而是这样做了:
MyLocationViewController *mainController = (MyLocationViewController *) self.window.rootViewController;
[mainController drawChat:text];
然后,我就可以用应用程序委托中的数据很好地调用该方法了。