CLLocationManager 位置定位

时间:2023-03-08 22:31:48

第一步,新建一个singleView的空白工程,如果新建,这里不做赘述了。

第二步:因为地图开发相关的framework:MapKit.frameworkCoreLocation.framework 至于如何添加,一般的ios相关博客都是有介绍。

   主界面的控制器 ViewController.h 文件中,我们啥也不做,.m文件中,我们需声明一个 CLLocationManager* locationManager的属性,我们让其实现CLLocationManagerDelegate的协议,并覆写其更新位置的方法,如下

1 #import "ViewController.h"

2 #import <CoreLocation/CoreLocation.h>

3 @interface ViewController ()<CLLocationManagerDelegate>{

4

5 }

6

7 @property (nonatomic,retain)CLLocationManager* locationManager;

8

9 @end

10

11      @implementation ViewController

12

13      -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

14

15      {

16          if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

17              NSLog(@"nibName:  %@   bundle: %@",nibBundleOrNil,nibBundleOrNil);

18              _locationManager = [[CLLocationManager alloc] init];

19

20          }

21

22          return  self;

23      }

24

25      - (void)dealloc

26      {

27          self.locationManager = nil;

28          [super dealloc];

}

29      - (void)viewDidLoad

30      {

31          [super viewDidLoad];

32           Do any additional setup after loading the view, typically from a nib.

33          delegate

34          self.locationManager.delegate = self;

35          The desired location accuracy.

36          self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

37          Specifies the minimum update distance in meters.

38

39          self.locationManager.distanceFilter = kCLDistanceFilterNone;

40

41          self.locationManager.purpose = @"To provide functionality based on user's current location.";

42

43          [self.locationManager startUpdatingLocation];

44      }

45

46      - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

47          NSLog(@"didChangeAuthorizationStatus---%u",status);

48      }

49

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

51          NSLog(@"didChangeAuthorizationStatus----%@",error);

52      }

53

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

55          UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"update" message:[NSString stringWithFormat:@"didUpdateToLocation:  newLocation: %@  old:%@",newLocation,oldLocation] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil nil];

56          [av show];

57          [av release];

}