系统定位功能
导入定位功能框架CoreLocation.framework
代理对象.h文件
#import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> /** * 获取用户最新的位置 */ typedef void(^GetlatesPlaceMark)(NSString* placeDetailName); @interface NSObjectMapViewDelegate : NSObject<CLLocationManagerDelegate> /** * 获取用户最新的位置 */ -(void)setGetlatesPlaceMark:(GetlatesPlaceMark)getlatesPlaceMark0; /** * 开始定位 */ -(void)configureLocationManager; /** * 单例 */ +(NSObjectMapViewDelegate *)defaultMapviewDelegate; @end
代理对象.m文件
// // NSObjectMapViewDelegate.m // attendance // // Created by dgc on 15/7/9. // Copyright © 2015年 dgc. All rights reserved. // #import "NSObjectMapViewDelegate.h" @implementation NSObjectMapViewDelegate { CLLocationManager* locationManager; GetlatesPlaceMark getlatesPlaceMark; } /** * 开始定位 */ -(void)configureLocationManager { locationManager=[CLLocationManager new]; if(![CLLocationManager locationServicesEnabled]) { NSLog(@"定位服务不可用"); // [locationManager requestWhenInUseAuthorization]; [locationManager requestAlwaysAuthorization]; } else { NSLog(@"定位服务可用"); locationManager.delegate=self; //The desired location accuracy. locationManager.desiredAccuracy=kCLLocationAccuracyBest; //Specifies the minimum update distance in meters. locationManager.distanceFilter=100.0; //开始定位 [locationManager startUpdatingLocation]; } } /** * 获取用户位置 * * @param manager * @param locations */ -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // NSLog(@"%s\n%@",__func__,locations); if (locations.count>0) { CLLocation* latesLocation=[locations lastObject]; [self wgcTOcgjAndLocation:latesLocation]; } } /**
*
*中国地区会涉及到GPS转火星坐标才可以正常进行地理编码
(GPS纠偏使用的是网站提供的免费接口:http://api.zdoz.net/interfaces.aspx接口使用的方式是按照演示地址发送一个动态的URL,而不是发送参数,然后解析数据就可以了。)
* WGC转CGJ
*
* @param location WGC */ -(void)wgcTOcgjAndLocation:(CLLocation*)location { // NSLog(@"%s\n%@",__FUNCTION__,location); NSURLSession* wgcToGcj=[NSURLSession sharedSession]; NSString* wgcToGcjAPI=[NSString stringWithFormat:@"http://api.zdoz.net/transgps.aspx?lat=%lf&lng=%lf",location.coordinate.latitude,location.coordinate.longitude ]; NSURLSessionDataTask *locationTask=[wgcToGcj dataTaskWithURL:[NSURL URLWithString:wgcToGcjAPI] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // NSLog(@"response.URL:%@",response.URL); if (error) { NSLog(@"error2\n%@",error.localizedDescription); NSLog(@"error3\n%@",error.localizedFailureReason); } if (data) { NSError* errorMars; NSDictionary* marsLocation=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&errorMars]; if (errorMars) { NSLog(@"errorMars\n%@",errorMars.localizedDescription); NSLog(@"errorMars\n%@",errorMars.localizedFailureReason); } [self getPlaceMark:marsLocation]; } } ]; [locationTask resume]; } /** * 根据火星坐标获取地理编码 * * @param lat * @param lng */ -(void)getPlaceMark:(NSDictionary*)location { // NSLog(@"%s",__FUNCTION__); NSNumber* lat=location[@"Lat"]; NSNumber* lng=location[@"Lng"]; CLGeocoder* geocoder=[[CLGeocoder alloc]init]; CLLocation* textLocation=[[CLLocation alloc] initWithLatitude:lat.doubleValue longitude:lng.doubleValue]; [geocoder reverseGeocodeLocation:textLocation completionHandler:^(NSArray *placemarks, NSError *error) { if (error) { NSLog(@"error0\n%@",error.localizedDescription); NSLog(@"error1\n%@",error.localizedFailureReason); } if (placemarks.count>0) { CLPlacemark* latesPlaceMark=(CLPlacemark*)[placemarks lastObject]; // NSLog(@"latesPlaceMark.addressDictionary:%@",(latesPlaceMark.addressDictionary[@"FormattedAddressLines"])[0]); if (getlatesPlaceMark) { getlatesPlaceMark((NSString*)(latesPlaceMark.addressDictionary[@"FormattedAddressLines"])[0]); } } }]; } /** * 传出地址数据 * * @param getlatesPlaceMark0 传入的Block */ -(void)setGetlatesPlaceMark:(GetlatesPlaceMark)getlatesPlaceMark0 { if (getlatesPlaceMark0) { getlatesPlaceMark=nil; getlatesPlaceMark=[getlatesPlaceMark0 copy]; } } /** * 单例 * * @return */ +(NSObjectMapViewDelegate *)defaultMapviewDelegate { //socket只会实例化一次 static NSObjectMapViewDelegate* mapView=nil; //保证线程安全,defaultMapviewDelegate只执行一次 static dispatch_once_t once; dispatch_once(&once, ^ { mapView=[[NSObjectMapViewDelegate alloc] init]; }); return mapView; }
/**
* 定位失败
*
* @param manager
* @param error
*/
-(void)locationManager:(nonnull CLLocationManager *)manager
didFailWithError:(nonnull NSError *)error
{
NSLog(@"%s",__func__);
NSLog(@"[error localizedDescription]:%@",[error localizedDescription]);
NSLog(@"[error localizedFailureReason]:%@",[error localizedFailureReason]);
}
@end
定位失败会调用触发代理
通常也会提示如下信息The operation couldn’t be completed. (kCLErrorDomain error 2.)
那么这个clerror.h文件在哪里?
该文件是属于定位框架下的对定位失败对描述,所以其位置是这样的
#import <CoreLocation/CLError.h>
内容如下
/* * CLError.h * CoreLocation * * Copyright (c) 2008-2010 Apple Inc. All rights reserved. * */ #import <Foundation/Foundation.h> #import <CoreLocation/CLAvailability.h> NS_ASSUME_NONNULL_BEGIN /* * CLError * * Discussion: * Error returned as code to NSError from CoreLocation. */ typedef NS_ENUM(NSInteger, CLError) { kCLErrorLocationUnknown = 0, // location is currently unknown, but CL will keep trying kCLErrorDenied, // Access to location or ranging has been denied by the user kCLErrorNetwork, // general, network-related error kCLErrorHeadingFailure, // heading could not be determined kCLErrorRegionMonitoringDenied, // Location region monitoring has been denied by the user kCLErrorRegionMonitoringFailure, // A registered region cannot be monitored kCLErrorRegionMonitoringSetupDelayed, // CL could not immediately initialize region monitoring kCLErrorRegionMonitoringResponseDelayed, // While events for this fence will be delivered, delivery will not occur immediately kCLErrorGeocodeFoundNoResult, // A geocode request yielded no result kCLErrorGeocodeFoundPartialResult, // A geocode request yielded a partial result kCLErrorGeocodeCanceled, // A geocode request was cancelled kCLErrorDeferredFailed, // Deferred mode failed kCLErrorDeferredNotUpdatingLocation, // Deferred mode failed because location updates disabled or paused kCLErrorDeferredAccuracyTooLow, // Deferred mode not supported for the requested accuracy kCLErrorDeferredDistanceFiltered, // Deferred mode does not support distance filters kCLErrorDeferredCanceled, // Deferred mode request canceled a previous request kCLErrorRangingUnavailable, // Ranging cannot be performed kCLErrorRangingFailure, // General ranging failure }; /* * kCLErrorUserInfoAlternateRegionKey * * Discussion: * When an error with code kCLErrorRegionMonitoringResponseDelayed is received, this key may be populated * in the userInfo dictionary. The value is a CLRegion that the location service can more effectively monitor. */ extern NSString *const kCLErrorUserInfoAlternateRegionKey NS_AVAILABLE(10_7, 5_0) __WATCHOS_PROHIBITED; NS_ASSUME_NONNULL_END
确实不好找啊。