在 IOS 中使用 CLLocation 获取用户当前位置
Posted
技术标签:
【中文标题】在 IOS 中使用 CLLocation 获取用户当前位置【英文标题】:Get User Current location using CLLocation in IOS 【发布时间】:2015-12-03 08:08:05 【问题描述】:我想获取用户当前的位置和地址,我使用CLLocationManager
并添加了核心位置框架。但反应是什么。请分享您的 cmets。
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self; [locationManager startUpdatingLocation];
代表是
(void)locationManager:(CLLocationManager *)manager didFailWithError: (NSError *)error
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
CLLocation *currentLocation = locations.first;
[locationManager setDelegate:nil];
if (currentLocation != nil)
NSString *longitudeLabel = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
NSString *latitudeLabel = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
【问题讨论】:
你用的是哪个ios版本? 看下面我的回答 【参考方案1】:查看我的代码,您可以从当前位置获取地址
- (void)viewDidLoad
CLGeocoder *ceo;
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[locationManager startUpdatingLocation];
-(void)viewDidAppear:(BOOL)animated
ceo= [[CLGeocoder alloc]init];
[self.locationManager requestWhenInUseAuthorization];
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
[self.locationManager requestWhenInUseAuthorization];
CLLocationCoordinate2D coordinate;
coordinate.latitude=locationManager.location.coordinate.latitude;
coordinate.longitude=locationManager.location.coordinate.longitude;
//CLLocationCoordinate2D ctrpoint;
// ctrpoint.latitude = ;
//ctrpoint.longitude =f1;
//coordinate.latitude=23.6999;
//coordinate.longitude=75.000;
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = coordinate;
NSLog(@"%f",coordinate.latitude);
//[self.mapView addAnnotation:marker];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude
];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error)
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark %@",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSLog(@"addressDictionary %@", placemark.addressDictionary);
NSLog(@"placemark %@",placemark.region);
NSLog(@"placemark %@",placemark.country); // Give Country Name
NSLog(@"placemark %@",placemark.locality); // Extract the city name
NSLog(@"location %@",placemark.name);
NSLog(@"location %@",placemark.ocean);
NSLog(@"location %@",placemark.postalCode);
NSLog(@"location %@",placemark.subLocality);
NSLog(@"location %@",placemark.location);
//Print the location to console
NSLog(@"I am currently at %@",locatedAt);
_City.text=[placemark.addressDictionary objectForKey:@"City"];
[locationManager stopUpdatingLocation];
];
#pragma mark - CLLocationManagerDelegate
请添加这两个方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
希望这个作品
谢谢
【讨论】:
请确认我定义的坐标类型,如 CLLocationCoordinate2D *coordinate;但没有解决。 我更新了答案,你遇到什么问题告诉我 更正的是 CLLocationCoordinate2D *coordinate 读取为 CLLocationCoordinate2D 坐标。现在它可以工作了,谢谢如尚。 你能帮我实现这个 DTParallaxTableView github.com/toandk/DTTableView 我已经下载了它,但在 ios 8.0 xcode 6.4 中无法使用,显示 Apple o 链接器错误。 让我们continue this discussion in chat.【参考方案2】:您需要添加"NSLocationAlwaysUsageDescription"
"NSLocationWhenInUseUsageDescription"
键入Info.plist
并显示一条消息。
【讨论】:
使用 NSLocationWhenInUseUsageDescription 显示警报并获得许可后,这将导致错误 -[__NSArrayM 坐标]:无法识别的选择器发送到实例 0x1454b210 2015-12-03 13:57:19.546 alootamatar[925:251385 ] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSArrayM 坐标]:无法识别的选择器发送到实例 0x1454b210” 添加异常断点并显示导致错误的行。我认为您将数组存储在变量中。 您实际上是在将一个数组分配给变量。看看你的行 CLLocation *currentLocation = locations; 位置:阵列响应为 (" +/- 75.28m (速度 -1.00 mps / course -1.00) @ 03/12/15 14:42:50 India Standard Time" ) 分配后类似 CLLocation *currentLocation = locations;结果是错误。【参考方案3】:在调用startUpdatingLocation
之前,你需要先调用函数来请求权限。
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
【讨论】:
更新此代码后未收到响应和任何许可警报。【参考方案4】:You need to add
"NSLocationAlwaysUsageDescription"
"NSLocationWhenInUseUsageDescription" key in
Info.plist with a message to be displayed.
In .h file
<CLLocationManagerDelegate>
CLGeocoder *geoCoder;
CLLocationManager *locationManager;
CLPlacemark *placeMark;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
and .m file
in viewDidLoad Method
_mapView.showsUserLocation = YES;
[self geoLocation];
after that we have to call Delegate methods for CLLocationManager
-(void)geoLocation
geoCoder = [[CLGeocoder alloc] init];
if (locationManager == nil)
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
CLLocation *newLocation = [locations lastObject];
//[self getCountryDet:lattitude1];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error)
if (error == nil && [placemarks count] > 0)
NSString *userLat,*userLong;
placeMark = [placemarks lastObject];
userLat = [NSString stringWithFormat:@"%.8f",newLocation.coordinate.latitude];
userLong= [NSString stringWithFormat:@"%.8f",newLocation.coordinate.longitude];
// For user address
NSString *locatedAt = [[placeMark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placeMark.locality];
NSString *Country = [[NSString alloc]initWithString:placeMark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
// For Zooming Level.
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// add the Pin annotation
MKPointAnnotation *pin = [[MKPointAnnotation alloc] init];
pin.coordinate = newLocation.coordinate;
pin.title = Address;
pin.subtitle = Area;
[self.mapView addAnnotation:pin];
else
NSLog(@"%@", error.debugDescription);
];
// Turn off the location manager to save power.
[manager stopUpdatingLocation];
【讨论】:
【参考方案5】: // IN this code use for get current location address
// Create Objet :
1)create object: CLGeocoder *geocoder;
2) add viewDidLoad method :
geocoder = [[CLGeocoder alloc] init];
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations: (NSArray *)locations
CLLocation *newLocation = [位置 lastObject];
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
[locationManager stopUpdatingLocation];
if (currentLocation != nil)
self.longitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
self.latitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
NSLog(@"Found placemarks current: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0)
// placemark = [placemarks lastObject];
placemark = [placemarks objectAtIndex:0];
NSString *name = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",
placemark.subLocality,
placemark.locality,
placemark.administrativeArea,placemark.postalCode,
placemark.country];
self.addressview.text=name;
else
NSLog(@"%@", error.debugDescription);
];
【讨论】:
以上是关于在 IOS 中使用 CLLocation 获取用户当前位置的主要内容,如果未能解决你的问题,请参考以下文章
CLLocation 在我的 xamarin.ios 项目中为 Null
Swift 中的 CLLocation 管理器获取用户的位置
iOS - CLLocation Manager didUpdateLocations 在一个类中被调用,而不是在另一个类中?