Ser*_*yov 1 cocoa-touch core-location nsstring ios
我想在我的应用程序中完成的是获取当前用户位置并在屏幕上显示它UILabel
.我希望NSString
当前用户的位置具有与此类似的格式:@"City, State/Country"
.这将是应用程序启动开始时的一次性操作.
我以前没有在iOS中的位置经验,我想得到一些关于这个的建议 - 我确信这是一个非常简单的任务.
过程如下:
添加CoreLocation.framework
到您的项目.请参见链接到库或框架.如果要使用我在下面使用的地址簿常量,您可能也想将其添加AddressBook.framework
到项目中.
开始位置服务.为此,"重大变化"服务(精度较低但功耗较低)可能足以满足城市级精度要求.
停止位置服务.
因此,这可能看起来像:
#import <CoreLocation/CoreLocation.h>
#import <AddressBook/AddressBook.h>
@interface ViewController () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self startSignificantChangeUpdates];
}
- (void)startSignificantChangeUpdates
{
if ([CLLocationManager locationServicesEnabled])
{
if (!self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
}
- (void)stopSignificantChangesUpdates
{
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = [placemark addressDictionary];
NSString *city = addressDictionary[(NSString *)kABPersonAddressCityKey];
NSString *state = addressDictionary[(NSString *)kABPersonAddressStateKey];
NSString *country = placemark.country;
self.label.text = [NSString stringWithFormat:@"%@, %@, %@", city, state, country];
}];
[self stopSignificantChangesUpdates];
}
Run Code Online (Sandbox Code Playgroud)
请注意,位置管理员的位置通知取决于用户选择与您的应用程序共享该位置,即使在最佳情况下,也会异步发生.同样,反向地理编码异步发生.
见获取用户位置从位置感知编程指南.
归档时间: |
|
查看次数: |
2208 次 |
最近记录: |