(MKAnnotationView *)mapView:不在第一个视图上触发

时间:2012-12-19 15:47:14

标签: iphone ios

- (MKAnnotationView *)mapView:在第一次运行视图时没有触发。

我从JSON调用中加载了引脚。引脚加载所有信息,但调出(*见代码)并将它们变为紫色。(在 - (MKAnnotationView *)mapView2 :)中完成但是当我离开该选项卡然后返回它然后它被调用并且一切都很好。

为什么这不行?因为如果只检查一次,最终用户将不知道地图引脚具有电话呼叫功能。

进度流程:它会加载地图。加载针脚。通过呼出将引脚更改为紫色。然后缩放到引脚和当前位置。但是在第一次运行时,它不会通过调出来更改引脚。

我已将它缩小到 - (MKAnnotationView *)mapView:在第一次测试时没有触发,但是在一次测试中它确实触发但只在两个引脚的第二次调用,直到重新加载视图。

我愿意接受任何建议,以改善它与之相关的任何代码天气。我总是喜欢学习更好的方法去完成我所做的事情。所以你的批评是免费的。

.h文件

  

@class Reachability;

@interface LocationsViewController : UIViewController <MKMapViewDelegate,CLLocationManagerDelegate>
{
NSString *phone;

IBOutlet MKMapView *mapView;

CLLocationManager *locationManager;

NSURLConnection *theConnection;

Reachability* internetReachable;
Reachability* hostReachable;
}

@property(nonatomic, retain) IBOutlet MKMapView *mapView;
@property(nonatomic, retain)CLLocationManager *locationManager;
@property(nonatomic, retain) NSString *phone;

- (BOOL) connectedToNetwork;
- (void) mapPinsJSON;

@end

.m文件

@implementation LocationsViewController

@synthesize mapView;
@synthesize locationManager;
@synthesize phone;

MapAnnotation *ann1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = NSLocalizedString(@"Locations", @"Locations");
        self.tabBarItem.image = [UIImage imageNamed:@"locations"];
    }
    return self;
 }

- (void)dealloc
{
    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    MKCoordinateRegion region;
    region.center.latitude = newLocation.coordinate.latitude;
    region.center.longitude= newLocation.coordinate.longitude;
    region.span.longitudeDelta=0.2;
    region.span.latitudeDelta =0.2;
    [mapView setRegion:region animated:YES];
    [mapView setDelegate:self];
    NSTimer *myTimer;
    myTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDown) userInfo:nil repeats:NO];
    [self zoomMapViewToFitAnnotations:self.mapView animated:YES];   
}

-(void)countDown{
    [locationManager stopUpdatingLocation];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [locationManager stopUpdatingLocation];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [mapView removeAnnotations:mapView.annotations];
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    if([self connectedToNetwork] != YES)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"OH NO!" message:@"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else
    {
        [self performSelectorInBackground:@selector(mapPinsJSON) withObject:nil];
    }
}

- (void) mapPinsJSON{

    NSString *urlString = [NSString stringWithFormat:@"http://www.mywebsite.com/api/newlocations25/json.json"];

    NSURL *url = [NSURL URLWithString:urlString];

    NSData *data = [NSData dataWithContentsOfURL:url];

    NSError *error;

    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    for(id key in json) {
        id value = [json objectForKey:key];
        NSString *titlePin = [value valueForKey:@"address"];
        NSString *address = [value valueForKey:@"title"];
        NSString *latitude = [value valueForKey:@"latitude"];
        NSString *longitude = [value valueForKey:@"longitude"];

        NSArray* foo = [address componentsSeparatedByString: @":"];
        NSString* address2 = [foo objectAtIndex: 0];
        phone = [foo objectAtIndex: 1];

        double myLatitude = [latitude doubleValue];
        double myLongitude = [longitude doubleValue];

        MKCoordinateRegion location1;
        location1.center.latitude =myLatitude;
        location1.center.longitude= myLongitude;
        location1.span.longitudeDelta=0.1;
        location1.span.latitudeDelta =0.1;

        ann1 =[[[MapAnnotation alloc] init] autorelease];
        ann1.title=[NSString stringWithFormat:@"%@",titlePin];
        ann1.subtitle=[NSString stringWithFormat:@"%@",address2];
        ann1.phone=[NSString stringWithFormat:@"%@",phone];
        ann1.coordinate= location1.center;
        [mapView addAnnotation:ann1];
        [phone retain];     
    }
}

-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
    if (annotation == mapView2.userLocation) {
        return nil;
    }else{
        MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"current"];
        MyPin.pinColor = MKPinAnnotationColorPurple;

        UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
        [advertButton setImage:[UIImage imageNamed:@"mapphone"] forState:UIControlStateNormal];
        [advertButton addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        MyPin.rightCalloutAccessoryView = advertButton;

        MyPin.draggable = NO;
        MyPin.highlighted = YES;
        MyPin.animatesDrop=TRUE;
        MyPin.canShowCallout = YES;

        return MyPin;
    }
}

-(void)button:(id)sender {

    UIButton *button = (UIButton *)sender;

    MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;

    MapAnnotation *mapAnnotation = annotationView.annotation;

   UIDevice *device = [UIDevice currentDevice];
    if ([[device model] isEqualToString:@"iPhone"] ) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",mapAnnotation.phone]]];
    } else {
        UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:@"Your device doesn't support this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [Notpermitted show];
        [Notpermitted release];
    }   
}

- (BOOL) connectedToNetwork
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    BOOL internet;
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
    internet = NO;
    } else {
    internet = YES;
    }
    return internet;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}

#define MINIMUM_ZOOM_ARC 0.014 //approximately 1 miles (1 degree of arc ~= 69 miles)

#define ANNOTATION_REGION_PAD_FACTOR 1.15

#define MAX_DEGREES_ARC 360

- (void)zoomMapViewToFitAnnotations:(MKMapView *)mapView3 animated:(BOOL)animated
{

    NSArray *annotations = mapView.annotations;

    int count = [mapView.annotations count];

    if ( count == 0) { return; } //bail if no annotations

    //convert NSArray of id <MKAnnotation> into an MKCoordinateRegion that can be used to set the map size

    //can't use NSArray with MKMapPoint because MKMapPoint is not an id

    MKMapPoint points[count]; //C array of MKMapPoint struct

    for( int i=0; i<count; i++ ) //load points C array by converting coordinates to points  
    {
        CLLocationCoordinate2D coordinate = [(id <MKAnnotation>)[annotations objectAtIndex:i] coordinate];
        points[i] = MKMapPointForCoordinate(coordinate);    
    }

    //create MKMapRect from array of MKMapPoint

    MKMapRect mapRect = [[MKPolygon polygonWithPoints:points count:count] boundingMapRect];

    //convert MKCoordinateRegion from MKMapRect

    MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);

    //add padding so pins aren't scrunched on the edges

    region.span.latitudeDelta  *= ANNOTATION_REGION_PAD_FACTOR;

    region.span.longitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;

    //but padding can't be bigger than the world

    if( region.span.latitudeDelta > MAX_DEGREES_ARC ) { region.span.latitudeDelta  = MAX_DEGREES_ARC; }

    if( region.span.longitudeDelta > MAX_DEGREES_ARC ){ region.span.longitudeDelta = MAX_DEGREES_ARC; }

    //and don't zoom in stupid-close on small samples

    if( region.span.latitudeDelta  < MINIMUM_ZOOM_ARC ) { region.span.latitudeDelta  = MINIMUM_ZOOM_ARC; }

    if( region.span.longitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.longitudeDelta = MINIMUM_ZOOM_ARC; }

    //and if there is a sample of 1 we want the max zoom-in instead of max zoom-out

    if( count == 1 )   
    {    
        region.span.latitudeDelta = MINIMUM_ZOOM_ARC;
        region.span.longitudeDelta = MINIMUM_ZOOM_ARC;     
    }
    [mapView3 setRegion:region animated:animated];   
}

@end

1 个答案:

答案 0 :(得分:0)

我感到羞怯。这是我修复它的原因。

- (void)viewDidLoad
{
    [super viewDidLoad];

    mapView.delegate = self;
}