iOS dynamically override subtitle method in id<MKAnnotation> subclass - iphone

I'm in a situation where in the
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
method, I need to dynamically change the implementation of the subtitle method for the annotation object. The reason I need to do this is because I'm doing some computations based on latitudes and longitudes that are changing frequently (which I wish to display as the subtitle) ...so when I first create the id object, it doesn't make sense to do that computation at that time.
How would I dynamically override the subtitle method for my custom id object? Can someone point me in the direction of doing that? Or are there any other approaches I could take?
EDIT:
To be a bit more clear... I want to add the annotation custom object to the map BEFORE figuring out what the title and subtitle should be for that annotation object. I want to wait until the user touches on the annotation on the map..and when it shows the popup, that's where I want to calculate what to show as the subtitle. That's why I thought of dynamically overriding the subtitle method of the custom id object.
Thanks!

If you need to dynamically change the implementation of a method at run time, that might call for an application of strategy pattern.
With C blocks, we can do it in a flexible and quick way. Have your custom annotation delegate its implementation of subtitle to the return value of a block property. Then, in your map view's delegate, define blocks that calculate the subtitle based on your requirements, and assign them to the annotation's property.
Sketch of a custom annotation implementation that delegates its subtitle implementation:
typedef NSString* (^AnnotationImplementationSubtitleBlock)();
#interface AnnotationImplementation : NSObject <MKAnnotation>
#property (nonatomic, copy) AnnotationImplementationSubtitleBlock *subtitleBlock;
#end
#implementation AnnotationImplementation
- (NSString *)subtitle
{
return self.subtitleBlock();
}
// Rest of MKAnnotation methods
#end
Also a sketch of the implementation of the map view delegate method where the blocks are created and assigned:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
AnnotationImplementation *customAnnotation = (AnnotationImplementation *)annotation;
if (/* some condition causing you to do it one way */) {
customAnnotation.subtitleBlock = ^{
//calculate the subtitle some way
return calculatedSubtitle;
}
}
else if (/* some condition causing you to do it another way */) {
customAnnotation.subtitleBlock = ^{
//calculate the subtitle the other way
return calculatedSubtitle;
}
}
... rest of method
}

Related

mapView:viewForAnnotation: not called when delegate set in code

I have a custom class for my MKAnnotations, I want to override the default mapView:viewForAnnotatation method so that I can add extra information in the callout. When I set my delegate in code (as per the code below) the annotations are dropped on the map and are selectable but my mapView:viewForAnnoation is never called.
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
NSLog(#"viewForAnnotation: called");
MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:#"mapPin"];
if(!aView){
aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"mapPin"];
}
aView.annotation = annotation;
return aView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.mapView.delegate = self;
}
I know the delegate is being set as I can override the method -(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view and I see an NSLog when I select an annotation.
When I change from setting the delegate in code to setting it in the Storyboard the method is called (NSLog(#"viewForAnnotation: called"); statements appear) but the annotations don't appear on the map and sometimes this error appears:
<Error>: ImageIO: CGImageReadSessionGetCachedImageBlockData *** CGImageReadSessionGetCachedImageBlockData: bad readSession [0x8618480]
This seems like two separate issues:
Regarding the setting delegate in code v storyboard, it's hard to reconcile your various observations (delegate method didSelectAnnotationView is getting called in both scenarios, but viewForAnnotation is not). The only difference between setting it in code v in the storyboard is the timing of when the delegate is getting set. You're not showing us the process of adding the annotations, so it's hard to diagnose on the basis of what you've described. If none of your delegate methods were getting called, I'd suspect the mapView IBOutlet, but if some are working and others aren't, I can only suspect a timing issue.
Regarding the setting of the MKAnnotationView, the default implementation does nothing. You either need to write your own subclass of MKAnnotationView, set its image if you're using your own image, or, much easier, just use MKPinAnnotationView. But just creating a MKAnnotationView won't do anything. You really want:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:#"mapPin"];
if(aView){
aView.annotation = annotation;
} else {
aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"mapPin"];
}
aView.canShowCallout = NO;
return aView;
}
(Note, I'm not only creating a MKPinAnnotationView, but I'm also making sure that it's not a MKUserLocation, in case you ever choose to show user location on the map. I'm also going to explicitly set the canShowCallout, as that's presumably the reason you're writing this method at all.)
Bottom line, if you want to show a simple pin annotation view, use MKPinAnnotationView. Using MKAnnotationView alone will result in no annotations from appearing.
In case someone else is searching for a reason why mapView:viewForAnnotatation is not being called when the delegate is set in code, there is a bug in iOS 6 - http://openradar.appspot.com/12346693
I came across the same issue and I wanted to share my solution:
I also override
(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation
But I realised that these Annotations work similar to TableView and iOS will reuse the annotations like the cells in TVC (table view controller)
Since I was only using one Identifier mapView dequeueReusableAnnotationViewWithIdentifier:#"mapPin" it would not need to call ViewForAnnotation again if it had enough 'annotation' in memory.
So my solution was to create multiple Identifier the first time the map load based on my conditions.
This solved my problem.
i just dropped to this question accidentally when i was searching for the same problem.
I solved my problem, in my case im resizing the mapview.
I added delegate after i resize the mapview. it works now perfectly.!

IPhone - Removing the 'currentLocation' blue dot from an MKMapView

I'm trying to replace the blue 'currentLocation' dot with a custom annotation. That code is working well (I am just implementing viewForAnnotation and cycling through that, replacing the annotation ofClass MKUserLocation with a custom image).
However, once I replace the annotation, the user's current location stops updating. All related functions (like didUpdateUserLocation) thus stop being called. This causes a lot of problems. I tried implementing the various code blocks at MKUserLocation Custom View not moving! but I couldn't get it to work. After extensive Googling and stackoverflow searching, I've come up with nothing.
Does anyone have a solution to this problem?
Here is the code for the viewForAnnotation method:
_userDot is an instance variable within MapScreen.m (the place where all of this code is). It's alloced in the viewDidLoad and is of type MKAnnotationView. Basically I couldn't just get rid of the annotation, so I wanted to set it to an invisible image instead (currently 1x1 for debugging).
- (MKAnnotationView *)mapView:(MKMapView *)newMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]) {
//Initialize a new MKAnnotationView using the current userLocation annotation
//Then make it invisible (because we are cheap like that)
//TODO: Make it actually invisible (right now it is 1x1 for debugging)
if (_userDot)
{
_userDot.annotation = annotation;
_userDot.image = [UIImage imageNamed:#"mister_taco"];
_userDot.frame = CGRectMake(1, 1, 1, 1);
return _userDot;
}
else
return nil;
}
else {*/
return nil;
//}
}
Thanks,
Brian

Problem with selected annotations

:)
I have a really strange problem when trying to retrieve the properties of a selected annotation. Here is the short description of my problem:
I pass the first object of the selected annotations array to a new array as it's the only one I need (acc. to Apple doc, passing the selectedAnnotations array to a new array only selects the first object. But I did tried to pull the object directly from the selectedAnnotations array at index path 0 and it's the same problem).
Then I transform the object into a Custom annotation object (as this is what the object should be).
Afterwards I try to access the properties of my custom annotation temp object. Here is when everything breaks loose. NSLog of the object only shows memory address. Text property is null. So basically I can't access it.
I would appreciate any help on what am I doing wrong or what approach should I use.
Thank you kindly!
Here is the code:
-(void) mapView:(MKMapView *)aMapView didSelectAnnotationView:(MKAnnotationView *)view
{
if ([view isUserInteractionEnabled])
// NSLog(#"Tapped!!!");
{
NSArray* selectedAnnotation=mapView.selectedAnnotations;
CustomAnnotations *selectedAnn=[selectedAnnotation objectAtIndex:0];
NSLog(#"selected annotation text is %#", selectedAnn.text);
My custom annotation class has a coordinate and a text property and it's being placed on map with this code:
CustomAnnotations* commentAnnotation = [[[CustomAnnotations alloc] initWithLocation:mapView.userLocation.location.coordinate andTitle:#"comment" andText:text]autorelease];
[mapView addAnnotation:commentAnnotation];
Furthermore, the view for annotation has the following coding:
-(MKAnnotationView *) mapView:(MKMapView *) aMapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKAnnotationView *customAnnotation = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:#"pin"];
if(!customAnnotation)
{
customAnnotation = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"pin"]autorelease];
}
customAnnotation.centerOffset=CGPointMake(10, -30);
if ([annotation title]==#"comment")
{
customAnnotation.userInteractionEnabled=YES;
customAnnotation.image=[UIImage imageNamed:#"NewCommentsPin.png"];
}
return customAnnotation;
}
Any help would be much appreciated!
I figured out the problem: My custom annotation class was releasing the text in dealloc.
I still have a long way to go until I understand when to release and when not to but one step at a time!:)
Here is your release cheat sheet.
When you create an object, and it has any of the words new, alloc,
copy or retain in the constructor then you own it and you have
to release it if you do not need the reference any more.

Customize the MKAnnotationView callout

I want to create a custom MKAnnotationView callout as shown in this image. I have tested several solutions but they only allow customization of the left/right images and title/subtitle. Can anybody please give me some source code or tutorial link for it?
Currently I am clueless. Please help.
I understand you want a pin with a custom callout.
We can't create a custom callout, but we can create an annotation with a completely customized view. So the trick is to add a second annotation when the first is selected, and make the 2nd annotation view look like a callout bubble.
This is the solution posted by users djibouti33 and jacob-jennings in the answer: MKAnnotationView - Lock custom annotation view to pin on location updates, which in turn is based in a blog post from Asynchrony Solutions. For explanation purposes, here is some UML from a forked project:
This is a big hack, but also the cleanest way I've seen to implement custom annotations.
Start with a NSObject "Content" class which has a coordinate, the class of the callout view to use (in the UML is AnnotationView, but you can create more and set them here), and a dictionary of random values with the title, photo url, etc. Use this class to initialize a MKAnnotation "Annotation" object.
#import <MapKit/MapKit.h>
#interface Content : NSObject
#property (nonatomic,assign) CLLocationCoordinate2D coordinate;
// ...
#interface Annotation : NSObject <MKAnnotation, AnnotationProtocol>
-(id) initWithContent:(Content*)content;
// ...
The Annotation implements AnnotationProtocol to announce it wants to handle the creation of its own MKAnnotationView. That is, your MKMapViewDelegate should have code like this:
- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id<MKAnnotation>)annotation
{
// if this is a custom annotation, delegate the implementation of the view
if ([annotation conformsToProtocol:#protocol(AnnotationProtocol)]) {
return [((NSObject<AnnotationProtocol>*)annotation) annotationViewInMap:mapView];
} else {
// else, return a standard annotation view
// ...
}
}
The view returned will be of type AnnotationView, which implements AnnotationViewProtocol to announce that it wants to handle selection/deselection. Therefore, in your map view controller, the methods mapView:didSelectAnnotationView: and mapView:didDeselectAnnotationView: should delegate in a similar way to what we saw before.
When the annotation is selected, a second annotation (CalloutAnnotation) is added, which follows the same behaviour, but this time the view returned (CalloutView) is initialized from a XIB, and contains Core Graphics code (in BaseCalloutView) to animate and replicate a callout.
The initializer of the CalloutView class:
- (id)initWithAnnotation:(CalloutAnnotation*)annotation
{
NSString *identifier = NSStringFromClass([self class]);
self = [super initWithAnnotation:annotation reuseIdentifier:identifier];
if (self!=nil){
[[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
// prevent the tap and double tap from reaching views underneath
UITapGestureRecognizer *tapGestureRecognizer = ...
}
return self;
}
To be able to push another view controller from the callout view I used notifications.
The SO answer I linked at the top contains two complete projects implementing this code (class names may differ). I have another project using the UML above at https://github.com/j4n0/callout.
I added custom UIButton in MKAnnotationView. And on click of that button I have shown popOver with rootViewController with the view similar as you have shown above.
I know this question is from 2011 but for people who still find it in a search:
In iOS 9 you have MKAnnotationView.detailCalloutAccessoryView which entirely replaces the standard callout.

Change MKMapType in MKMapView and keep custom pinImage for annotations

I have set a custom pinImage for my annotations and when I change the type toMKMapTypeHybrid it reverts the pinImage setting to the standard pins.
I'm setting the mapType in my viewWillAppear method of the map view controller. I'm setting my pinImage for the annotations like so (shortened for clarity):
- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id ) annotation {
MKPinAnnotationView *customAnnotationView=[[[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:#"markerAnnotationView"] autorelease];
UIImage *pinImage = [UIImage imageNamed:#"/pin-image"];
[customAnnotationView setImage:pinImage];
return customAnnotationView;
}
Is there any way to use setImage and set the mapType via code?
The solution to this problem was to use an MKAnnotationView instead of the MKPinAnnotationView. I had previously been using the MKPinAnnotationView for good reason but later added a custom image to the pin without changing the instantiating class to MKAnnotationView.
Now, I think it is probably buggy framework behavior. If you're going to let an MKPinAnnotationView accept a setImage call then make sure that it handles it correctly when you change mapTypes. If you only want them to do pins then don't do anything with the call. Ah well.