[IOS]IOS8下地圖定位的使用方法

和ios7比較,稍微增加了些變動


1.Info.plist表裏面添加兩個變量

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription

首先這2個字段沒有特別的意思,可以理解爲使用定位時候的提示語


添加之後在h文件:

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "Corelocation/CLLocationManagerDelegate.h"
@interface MapViewController : UIViewController<CLLocationManagerDelegate>

@property (strong, nonatomic)    CLLocationManager* locationManager;

@property (weak, nonatomic) IBOutlet UITextField *longitudeText;

@property (weak, nonatomic) IBOutlet UITextField *latituduText;
- (IBAction)findme:(id)sender;

@end

m文件中:

- (void)viewDidLoad {
    [super viewDidLoad];
      _locationManager = [[CLLocationManager alloc]init];
    _locationManager.delegate = self;
    [_locationManager requestAlwaysAuthorization];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    
   
}

-(void)viewWillAppear:(BOOL)animated
{
        [super viewWillAppear:animated];
       [self.locationManager startUpdatingLocation];//定位是需要不斷的請求當前的位置,放在willappear最適合
}
-(void)viewWillDisappear:(BOOL)animated
{
        [super viewWillDisappear:animated];
       [self.locationManager stopUpdatingLocation];
}


另外相較於ios8之前的地圖定位,還要調用代理:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [_locationManager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}


調用完成後,其他方法和ios7一樣

  - (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {
    _latituduText.text = [NSString stringWithFormat:@"%3.5f",newLocation.coordinate.latitude];
    _longitudeText.text = [NSString stringWithFormat:@"%3.5f",newLocation.coordinate.longitude];
      [_locationManager stopUpdatingLocation];
    NSLog(@"location ok");
  
    
   
    
}
顯示所獲得的座標信息


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章