1杜漠、在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription (value 就是你要顯示的提示用戶獲取gps)
(2)NSLocationWhenInUseUsageDescription?(value 就是你要顯示的提示用戶獲取gps)
2.引入CoreLocation.framework
#import < CoreLocation/CoreLocation.h >
讓APPcontroller 繼承接口 CLLocationManagerDelegate?
AppController :NSObject <?UIAccelerometerDelegate,UIAlertViewDelegate,UITextFieldDelegate,UIApplicationDelegate,WXApiDelegate,CLLocationManagerDelegate >
3.添加全局變量?
@property(nonatomic,strong)CLLocationManager*locationManager;
4.在didFinishLaunchingWithOptions方法中調(diào)用initGPS, 然后就可以在回調(diào)中獲取到信息了(獲取失敗則會(huì)調(diào)用失敗回調(diào));
值得注意的是 在iOS8 以后必須加上:
[locationmanager requestWhenInUseAuthorization];(在使用時(shí)獲取gps)
或者[locationmanager requestAlwaysAuthorization];(無(wú)論是否在使用都獲取gps)
- (void) initGps{
locationmanager= [[CLLocationManageralloc]init];
//設(shè)置精度
/*
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers
*/
//設(shè)置定位的精度
[locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];
//實(shí)現(xiàn)協(xié)議
locationmanager.delegate=self;
[locationmanager requestWhenInUseAuthorization];
NSLog(@"開(kāi)始定位");
//開(kāi)始定位
[locationmanager startUpdatingLocation];
}
//獲取定位成功回調(diào)
- (void)locationManager:(CLLocationManager*)manager
didUpdateToLocation:(CLLocation*)newLocation
fromLocation:(CLLocation*)oldLocation
{
NSLog(@"hello");
//打印出精度和緯度
CLLocationCoordinate2Dcoordinate = newLocation.coordinate;
NSLog(@"輸出當(dāng)前的精度和緯度");
NSLog(@"精度:%f 緯度:%f",coordinate.latitude,coordinate.longitude);
//停止定位
//[locationmanager stopUpdatingLocation];
//計(jì)算兩個(gè)位置的距離
floatdistance = [newLocationdistanceFromLocation:oldLocation];
NSLog(@" 距離 %f",distance);
}
//獲取gps失敗回調(diào)
- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error
{
NSLog(@"獲取GPS失斉握痢锈至!");
if([errorcode] ==kCLErrorDenied)
{
//訪問(wèn)被拒絕
}
if([errorcode] ==kCLErrorLocationUnknown) {
//無(wú)法獲取位置信息
}
}
//停止獲取GPS
- (void)stopUpdateGPS
{
[locationmanagerstopUpdatingLocation];
}