如何从iOS中获取用户的当前位置 [英] How can I get current location from user in iOS
问题描述
如何从iOS中的用户获取当前位置?
How can I get the current location from user in iOS?
推荐答案
RedBlueThing的答案对我来说效果很好。以下是我如何做到的一些示例代码。
The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
MainFile
在init方法中
MainFile
In the init method
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中,不推荐使用委托功能。新代表是
iOS 6
In iOS 6 the delegate function was deprecated. The new delegate is
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
因此,要获得新职位,请使用
Therefore to get the new position use
[locations lastObject]
iOS 8
在iOS 8中,在开始更新位置之前应明确询问权限
iOS 8
In iOS 8 the permission should be explicitly asked before starting to update location
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
的调用,并且您的代理人将不会收到任何回调。
You also have to add a string for the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
keys to the app's Info.plist. Otherwise calls to startUpdatingLocation
will be ignored and your delegate will not receive any callback.
并且当你结束时完成读取位置调用stopUpdating位置在适当的位置。
And at the end when you are done reading location call stopUpdating location at suitable place.
[locationManager stopUpdatingLocation];
这篇关于如何从iOS中获取用户的当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!