使用系統的CoreLocation定位

//
//  ViewController.m
//  LBS
//
//  Created by tonnyhuang on 15/8/28.
//  Copyright (c) 2015年 tonnyhuang. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

//首先,咱們須要在工程中導入CoreLocation系統框架。而後在咱們的控制器中引入頭文件。
//而後,聲明一個CLLocationManager對象做爲成員變量,用於定位獲取經緯度座標,並遵照協議CLLocationManager的協議。
@interface ViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
}

@end

@implementation ViewController



//實現其中的代理方法
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    //獲取經度
    NSLog(@"經度 == %lf", newLocation.coordinate.longitude);
    //獲取緯度
    NSLog(@"緯度 == %lf", newLocation.coordinate.latitude);
    //獲取當前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根據經緯度反向地理編碼出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        NSLog(@"%@", placemark.name);
        //獲取城市
        NSString *city = placemark.locality;
       
        //四大直轄市的城市信息沒法經過locality得到,只能經過獲取省份的方法來得到(若是city爲空,則可知爲直轄市
       
        if (!city) {
            city = placemark.administrativeArea;
        } else if (error == nil && [placemarks count] == 0){
            NSLog(@"no result were returned");
        } else if (error != nil) {
            NSLog(@"error = %@", error);
        }
        NSLog(@"city = %@", city);
    }];
    //系統會一直更新數據,直到選擇中止更新,由於咱們只須要得到一次經緯度便可,因此獲取以後就中止更新
}



//最後在viewDidLoad中初始化定位管理器。
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeLocationService];
}

- (void)initializeLocationService {
    //初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    //設置代理
    _locationManager.delegate = self;
    //設置定位精確度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //設置過濾器爲無
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //開始定位
    [_locationManager requestAlwaysAuthorization];
    //取得定位權限,有兩個方法,取決於你的定位使用狀況
    [_locationManager startUpdatingLocation];
}

//若是須要正常定位,相對iOS7而言,iOS8須要額外處理兩個地方。
//1. 工程的plist文件裏面添加兩個字段:NSLocationAlwaysUsageDescription,
//NSLocationWhenInUseUsageDescription,type類型均爲string,值能夠根據你的須要填寫(也能夠不填),填寫的內容會展現在APP提示用戶是否容許定位的alert內容裏面,具體效果能夠自行測試,這裏就不額外截圖。
 
這兒的位置不要錯誤  在上邊的info.plist中添加字段
 
 
//2. 調用定位方法以前須要額外調用一個函數,直接在上面iOS7初始化定位服務的方法裏面修改便可,具體以下:

// 開始定位
// 取得定位權限,有兩個方法,取決於你的定位使用狀況
// 一個是requestAlwaysAuthorization,一個是requestWhenInUseAuthorization
//[_locationManager requestAlwaysAuthorization];//這句話ios8以上版本使用。
//[_locationManager startUpdatingLocation];


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
相關文章
相關標籤/搜索