ios - 如何在 iOS 中从用户那里获取当前位置

如何在 iOS 中从用户那里获取当前位置?

最佳答案

RedBlueThing 的答案对我来说效果很好。这是我如何做到的一些示例代码。

标题

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

主文件

在init方法中

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

回调函数

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

iOS 6

在 iOS 6 中,委托(delegate)函数已被弃用。新代表是

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

因此获得新的位置使用

[locations lastObject]

iOS 8

在 iOS 8 中,应在开始更新位置之前明确询问权限

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

您还必须为 NSLocationAlwaysUsageDescription 添加一个字符串或 NSLocationWhenInUseUsageDescription应用程序 Info.plist 的键。否则对 startUpdatingLocation 的调用将被忽略,您的委托(delegate)将不会收到任何回调。

最后,当你读完位置后,在合适的地方调用 stopUpdating location。

[locationManager stopUpdatingLocation];

https://stackoverflow.com/questions/4152003/

相关文章:

objective-c - ARC 和桥接铸件

objective-c - 什么时候应该在 Objective-C 中使用 nil 和 NULL?

ios - 从后台打开应用程序时不调用 ViewDidAppear

ios - 删除 UITableView 中单元格前的空白

objective-c - 使用 block 在 `self` 上保留循环

objective-c - 在 View Controller 之间进行通信的最佳方式是什么?

ios - 处理 NSDateFormatter 语言环境 "feature"的最佳方法是什么?

ios - 如何将本地 html 文件加载到 UIWebView

ios - UIImageView 方面适合和居中

iphone - 在iOS前台应用程序时获取推送通知