更新时间:2023-02-26 14:36:13
您可以使用CoreLocation
这样找到您的位置:
You can find your location using CoreLocation
like this:
导入CoreLocation
:
#import <CoreLocation/CoreLocation.h>
声明CLLocationManager
:
CLLocationManager *locationManager;
初始化viewDidLoad
中的locationManager
并创建一个函数,该函数可以将return
当前位置作为NSString
:
Initialize the locationManager
in viewDidLoad
and create a function that can return
the current location as an NSString
:
- (NSString *)deviceLocation {
return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
并调用deviceLocation
函数将返回预期的位置:
And calling the deviceLocation
function will return the location as expected:
NSLog(@"%@", [self deviceLocation]);
这只是一个例子.在没有用户准备的情况下初始化CLLocationManager
并不是一个好主意.而且,当然locationManager.location.coordinate
可用于在初始化CLLocationManager
之后随意获取latitude
和longitude
.
This is just an example. Initializing CLLocationManager
without the user being ready for it isn't a good idea. And, of course, locationManager.location.coordinate
can be used to get latitude
and longitude
at will after CLLocationManager
has been initialized.
请不要忘记在项目设置的构建阶段"选项卡(Targets->Build Phases->Link Binary
)下添加CoreLocation.framework
.
Don't forget to add the CoreLocation.framework
in your project settings under the Build Phases tab (Targets->Build Phases->Link Binary
).