iPhone中GPS定位如何使用 關鍵詞 1.info.plist配置授權描述 2.引入庫 3.CLLocationManager的使用 info.plist配置 在info.plist中根據情況加入以下兩個string類型配置項,並填寫描述 1.NSLocationAlwaysUsageDescr
iPhone中GPS定位如何使用
關鍵詞
1.info.plist配置授權描述
2.引入庫
3.CLLocationManager的使用
info.plist配置
在info.plist中根據情況加入以下兩個string類型配置項,並填寫描述
1.NSLocationAlwaysUsageDescription
2.NSLocationWhenInUseUsageDescription
引入庫
-引入CoreLocation.framework
-在原文件中引入 <CoreLocation/CoreLocation.h>
代碼實現
// 初始化
2.- (void)setupLocationManager {
3. _locationManager = [[CLLocationManager alloc] init];
4. _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
5. _locationManager.distanceFilter = kCLDistanceFilterNone;
6.
7. if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
8. [_locationManager requestWhenInUseAuthorization];
9. }
10.}
11.
12.// 調用此方法開始定位
13.- (void) startUpdatingLocation {
14. if ([CLLocationManager locationServicesEnabled]) {
15. _shouldHandleLocation = YES;
16. _locationManager.delegate = self;
17. [_locationManager startUpdatingLocation];
18. } else {
19. [SVProgressHUD showErrorWithStatus:@"請開啟定位功能!"];
20. }
21.}
22.
23.#pragma mark - CLLocationManagerDelegate
24.- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
25.{
26. CLLocation *newLocation = [locations lastObject];
27. if (_shouldHandleLocation) {
28. _shouldHandleLocation = NO;
29. _latitude = newLocation.coordinate.latitude;
30. _longitude = newLocation.coordinate.longitude;
31.
32. [self commitCheckinInfo];
33. }
34.
35. _locationManager.delegate = nil;
36. [_locationManager stopUpdatingLocation];
37.}
38.
39.- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
40.{
41. [SVProgressHUD showErrorWithStatus:@"定位失敗!"];
42. _locationManager.delegate = nil;
43. [manager stopUpdatingLocation];
44.}