CLLocationManager与ARC一起使用?

时间:2014-11-15 22:53:27

标签: objective-c cllocationmanager cllocation

我试图做的就是获取用户的当前位置,并在我的应用程序的地图上显示,所以我正在使用CLLocationManager类,正如任何人都可以看到的那样:

ViewController.h

import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface MeuPrimeiroViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{

    IBOutlet MKMapView *mapView;
}

@property(nonatomic, retain) CLLocationManager *locationManager;


@end

ViewController.m

-(void)viewDidAppear:(BOOL)animated{

    //Lendo as coordenadas com o core location
    if ([CLLocationManager locationServicesEnabled]) {

        NSLog(@"CLLocationManager locationServicesEnabled == ON");

            self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;

            self.locationManager.distanceFilter = kCLDistanceFilterNone;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            [self.locationManager startUpdatingLocation];


    }else{

        NSLog(@"CLLocationManager locationServicesEnabled == OFF");
    }


}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    CLLocationDistance altitude = newLocation.altitude;
    CLLocationDegrees latitude = newLocation.coordinate.latitude;
    CLLocationDegrees longitude = newLocation.coordinate.longitude;

    NSLog(@"Altitude, Latitude, Longitude: %f, %f, %f",altitude,latitude,longitude);

    MKCoordinateRegion coordenada = {{0.0,0.0}, {0.0,0.0}};

    coordenada.center.latitude = latitude;
    coordenada.center.longitude = longitude;

    [mapView setRegion:coordenada animated:YES];

    //Calculando distancias

    CLLocationDistance distancia = [newLocation distanceFromLocation:oldLocation];
    NSLog(@"Distancia em metros : %f",distancia);

}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{

    NSLog(@"Error: %@",[error description]);

}

这段代码的问题是我的CLLocationManager类的方法没有被调用,我在互联网上做了一些与ARC相关的可能问题的研究,但没有一个工作,有什么建议吗?

2 个答案:

答案 0 :(得分:2)

iOS 8改变了两件让它无法正常工作的事情

  1. 在iOS 8上,您需要在致电requestWhenInUseAuthorization之前致电requestAlwaysAuthorizationstartUpdatingLocation
  2. 您必须提供与您在Info.plist中请求的授权类型相对应的位置使用说明(NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription)。您还应该继续为旧版iOS 8之前的密钥(NSLocationUsageDescription)提供值,作为旧版iOS的后备版。

答案 1 :(得分:1)

  

我试图做的就是获取用户的当前位置,并在我的应用程序的地图上显示

您不需要任何其他内容即可将用户的位置放在地图上。只需告诉地图即可跟踪用户的位置。在iOS 8中,您需要用户授权才能执行此操作,为此您需要一个位置管理器。但这两行代码就足够了(这是Swift,但我确定你可以翻译):

self.locman.requestWhenInUseAuthorization()
self.map.userTrackingMode = .Follow