// LocationManager.m
//
// Created by Daniel on 15/12/22.
// Copyright © 2015年 Daniel. All rights reserved.
//
import "LocationManager.h"
import <CoreLocation/CoreLocation.h>
@interface LocationManager ()<CLLocationManagerDelegate>
@property (strong, nonatomic)CLLocationManager *manager;
@property (copy, nonatomic)LocationBlock block;
@end
static LocationManager *single = nil;
@implementation LocationManager
- (instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (!single) {
single = [super allocWithZone:zone];
return single;
}
return single;
}
}
-
(instancetype)sharedLocationManager:(LocationBlock)block {
if (!single) {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
single = [LocationManager new];
single.manager = [[CLLocationManager alloc] init];
single.manager.delegate = single;
single.manager.desiredAccuracy = kCLLocationAccuracyBest;
single.manager.distanceFilter = 100.0f;
[single.manager requestAlwaysAuthorization];
[single.manager requestWhenInUseAuthorization];
});
}if ([CLLocationManager locationServicesEnabled]) {
single.block = block;
[single.manager startUpdatingLocation];
} else {
UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"请开启定位功能" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
[aler show];
}
return single;
}
pragma mark -- CLLocationManagerDelegate
-
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLGeocoder *coder = [[CLGeocoder alloc] init];
[coder reverseGeocodeLocation:locations[0] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error && [placemarks count] > 0) {
NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
_block(dict);
} else {
NSLog(@"ERROR: %@", error);
}
}];
} (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"error = %@", error);
}
@end
//另 需要再info.plist添加:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription