IOS 學習(基於 iOS 8.0 以上的地理信息查詢)

當 iOS 版本 大於 8.0 時 添加兩個 配置信息
要利用CoreLocation,必須在frameworks裏面加入“CoreLocation.framework”。在最新版本的Xcode中加入新的framework步驟如下:

單擊項目的target =>在出來的xcodeproj面板中點擊“Link Binary With Libraries” =>點擊“+”,然後選擇需要的framework即可。
在info.plist中添加

-NSLocationAlwaysUsageDescription   Bealoon YES
-NSLocationWhenInUseUsageDescription Bealoon YES  
調用 requestAlwaysAuthorization 方法
/*
When the current authorization status is kCLAuthorizationStatusNotDetermined, this method runs asynchronously and prompts the user to grant permission to the app to use location services. The user prompt contains the text from the NSLocationWhenInUseUsageDescription key in your app’s Info.plist file, and the presence of that key is required when calling this method. After the status is determined, the location manager delivers the results to the delegate’s locationManager:didChangeAuthorizationStatus: method. If the current authorization status is anything other than kCLAuthorizationStatusNotDetermined, this method does nothing and does not call the locationManager:didChangeAuthorizationStatus: method.
You must call this method or the requestAlwaysAuthorization method prior to using location services. If the user grants “when-in-use” authorization to your app, your app can start most (but not all) location services while it is in the foreground. (Apps cannot use any services that automatically relaunch the app, such as region monitoring or the significant location change service.) When started in the foreground, services continue to run in the background if your app has enabled background location updates in the Capabilities tab of your Xcode project. Attempts to start location services while your app is running in the background will fail. The system displays a location-services indicator in the status bar when your app moves to the background with active location services.
For more information about the NSLocationWhenInUseUsageDescription key, see Information Property List Key Reference./
或者 requestWhenInUseAuthorization 方法
/*When the current authorization status is kCLAuthorizationStatusNotDetermined, this method runs asynchronously and prompts the user to grant permission to the app to use location services. The user prompt contains the text from the NSLocationAlwaysUsageDescription key in your app’s Info.plist file, and the presence of that key is required when calling this method. After the status is determined, the location manager delivers the results to the delegate’s locationManager:didChangeAuthorizationStatus: method. If the current authorization status is anything other than kCLAuthorizationStatusNotDetermined, this method does nothing and does not call the locationManager:didChangeAuthorizationStatus: method.
Important:Important
Requesting “Always” authorization is discouraged because of the potential negative impacts to user privacy. You should request this level of authorization only when doing so offers a genuine benefit to the user.
You must call this method or the requestWhenInUseAuthorization method prior to using location services. When the user grants “Always” authorization to your app, your app can start any of the available location services while your app is running in the foreground or background. In addition, services that allow your app to be launched in the background continue to do so.
For more information about the NSLocationAlwaysUsageDescription key, see Information Property List Key Reference.*/

ViewControl.h

#import <UIKit/UIKit.h>
#include <CoreLocation/CoreLocation.h>
#include <CoreLocation/CLLocationManagerDelegate.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *cityName;
@property (weak, nonatomic) IBOutlet UITextField *txtLat;
@property (weak, nonatomic) IBOutlet UITextField *txtLon;
@property (weak, nonatomic) IBOutlet UITextField *txtAlt;
- (IBAction)showLocationInformation:(id)sender;
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

ViewControl.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     _locationManager = [[CLLocationManager alloc]init];
     _locationManager.delegate = self;
     /*值得注意的是,一定要設置locationManager的delegate是類本身,這樣startUpdatingLocation運行的時候纔會調用第二步實現的方法。 
如果機器沒有開啓地理位置的服務,那麼就不需要做多餘的動作。*/
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        NSLog(@"ios 8.0");
        [self.locationManager requestAlwaysAuthorization];// 前後臺同時定位
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)showLocationInformation:(id)sender {


    _locationManager.desiredAccuracy = kCLLocationAccuracyBest//設置精度
    _locationManager.distanceFilter = 1000.0f;//設置需要更新時的移動距離
    [_locationManager startUpdatingLocation];
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = [locations lastObject];
    //_cityName.text = [location cur]
    _txtLat.text = [NSString stringWithFormat:@"%3.5f",location.coordinate.latitude];
    _txtLon.text = [NSString stringWithFormat:@"%3.5f", location.coordinate.longitude];
    _txtAlt.text = [NSString stringWithFormat:@"%3.5f", location.altitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray * array, NSError *error){
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];

          //  NSLog(@"%@", placemark);

            NSString *cityName = [placemark locality];
            if (!cityName) {
                cityName = [placemark administrativeArea];
            }
            self.cityName.text = cityName;
        }
        else if (error == nil && [array count] == 0)

        {

            NSLog(@"No results were returned.");

        }

        else if (error != nil)

        {

            NSLog(@"An error occurred = %@", error);

        }

    }];
    [_locationManager stopUpdatingLocation];
}
@end
發佈了448 篇原創文章 · 獲贊 3 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章