//系统自带定位
[[MPLocationManager shareInstance] startSystemLocationWithRes:^(CLLocation *loction, NSError *error) {
if (!error) {
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:loction completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks.count>0) {
CLPlacemark *placemark=[placemarks objectAtIndex:0];
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
//有差异才改变
if(![BBUserDefault.LocationCity isEqualToString:city])
{
BBUserDefault.LocationCity=city;
}
NSLog(@"当前城市:[%@]",city);
}
}];
}
BBUserDefault.latiude=[NSString stringWithFormat:@"%f",loction.coordinate.latitude];
BBUserDefault.longitude=[NSString stringWithFormat:@"%f",loction.coordinate.longitude];
NSLog(@"定位信息:[%f,%f]",loction.coordinate.latitude,loction.coordinate.longitude);
}];
MPLocationManager.h类的代码如下:
#import <Foundation/Foundation.h>
typedef void(^KSystemLocationBlock)(CLLocation *loction, NSError *error);
@interface MPLocationManager : NSObject
+ (id)shareInstance;
/**
* 启动系统定位
*
* @param systemLocationBlock 系统定位成功或失败回调成功
*/
- (void)startSystemLocationWithRes:(KSystemLocationBlock)systemLocationBlock;
@end
#import "MPLocationManager.h"
@interface MPLocationManager()<CLLocationManagerDelegate>
@property (nonatomic, readwrite, strong) CLLocationManager *locationManager;
@property (nonatomic, readwrite, copy) KSystemLocationBlock kSystemLocationBlock;
@end
@implementation MPLocationManager
+ (id)shareInstance{
static id helper = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
helper = [[MPLocationManager alloc] init];
});
return helper;
}
#pragma mark - 苹果
/**
* 苹果系统自带地图定位
*/
- (void)startSystemLocationWithRes:(KSystemLocationBlock)systemLocationBlock{
self.kSystemLocationBlock = systemLocationBlock;
if(!self.locationManager){
self.locationManager =[[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
// self.locationManager.distanceFilter=10;
if ([UIDevice currentDevice].systemVersion.floatValue >=8) {
[self.locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要)
}
}
self.locationManager.delegate=self;
[self.locationManager startUpdatingLocation];//开启定位
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currLocation=[locations lastObject];
self.locationManager.delegate = nil;
[self.locationManager stopUpdatingLocation];
self.kSystemLocationBlock(currLocation, nil);
}
/**
*定位失败,回调此方法
*/
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
if ([error code]==kCLErrorDenied) {
NSLog(@"访问被拒绝");
}
if ([error code]==kCLErrorLocationUnknown) {
NSLog(@"无法获取位置信息");
}
self.locationManager.delegate = nil;
[self.locationManager stopUpdatingLocation];
self.kSystemLocationBlock(nil, error);
}
@end