问题描述
我需要使用CoreLocation
查找当前位置,我尝试了多种方法,但到目前为止,我的CLLocationManager
只返回了0..(0.000.00.000
).
I need to find my current location with CoreLocation
, I tried multiple methods but so far my CLLocationManager
has only returned 0's.. (0.000.00.000
).
这是我的代码(已更新为正常工作):
导入:
#import <CoreLocation/CoreLocation.h>
已声明:
IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *latLabel;
IBOutlet UILabel *longLabel;
功能:
- (void)getLocation { //Called when needed
latLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude];
longLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];
}
- (void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
推荐答案
您可以使用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
).
这篇关于如何使用CoreLocation查找当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!