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

标签 ios objective-c iphone cllocationmanager currentlocation

如何在 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];

关于ios - 如何在 iOS 中从用户那里获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4152003/

相关文章:

ios - 如何使用 SwiftUI LazyVGrid 创建交错网格?

objective-c - 将 NSData 中的字节解码为整数

stringByReplacingOccurrencesOfString 后调试器中的 Objective-C 奇怪外观

ios - NSURLSessionDataTask 导致 CPU 使用率过高

ios - 嵌套设置页面在 iOS13 中崩溃

ios - 如何在表格单元格中自动更改标签的大小?

iphone - iOS检查对象是否可以保留

iphone - iPhone:如何在WebView中设置字体大小?

iphone - NSDateFormatter,我做错了什么还是这是一个错误?

iphone - iOS 中文章搜索的搜索栏