[英]Show current location in map ios with CLLocationmanager
我試圖在地圖上顯示當前位置,但失敗了。 由於location為null,因此會給出錯誤。 在模擬器調試位置選項中應選擇哪個選項。 如果我嘗試不使用任何方法,則返回自定義的空位置nd,它給出預定坐標的位置。 我想獲得當前位置!
首先創建對象
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
if(IS_OS_8_OR_LATER)
{
[locationManager requestAlwaysAuthorization];
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
//Below two lines give you current location (lat-long).
Latitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.latitude];
NSLog(@"Lat====%@",Latitude);
Longitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.longitude];
NSLog(@"Log====%@",Longitude);
您可以在AppDelegate.h
添加它
@property (nonatomic, strong) CLLocationManager *locationManager;
您可以使用它來獲取當前位置。 您可以在AppDelegate.m
文件中添加此代碼
if ([CLLocationManager locationServicesEnabled]) {
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10.0;
[self.locationManager startMonitoringSignificantLocationChanges];
}
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
[_locationManager requestAlwaysAuthorization];
[_locationManager startUpdatingLocation];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.