//
// ViewController.m
// MyLocation
//
// Created by JohnFighting on 16/11/2015.
// Copyright © 2015 john. All rights reserved.
//
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
//經度
@property (weak, nonatomic) IBOutlet UITextField *txtLng;
//緯度
@property (weak, nonatomic) IBOutlet UITextField *txtLat;
//高度
@property (weak, nonatomic) IBOutlet UITextField *txtAlt;
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//定位服務管理對象初始化
//創建並初始化locationManager屬性
self.locationManager = [[CLLocationManager alloc]init];
//設置定位服務委託對象爲self
self.locationManager.delegate = self;
//設置desiredAccuracy屬性(定位精度)
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//設置distanceFilter屬性, 定義了設備移動後獲得位置信息的最小距離, 單位是米
self.locationManager.distanceFilter = 1000.0f;
//彈出用戶授權對話框
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
//在視圖出現時調用
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//開始定位, 在視圖控制器的聲明週期方法viewWillAppear:中使用這個方法最爲合適
[self.locationManager startUpdatingLocation];
}
//在視圖消失時調用
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//停止定位,
[self.locationManager stopUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *currLocation = [locations lastObject];//獲得集合中的最後一個元素, 即爲設備的當前位置
//coordinate封裝經度和緯度的結構體
self.txtLat.text = [NSString stringWithFormat:@"%3.5f",currLocation.coordinate.latitude];//獲取設備當前的緯度
self.txtLng.text = [NSString stringWithFormat:@"%3.5f",currLocation.coordinate.longitude];//獲取設備當前的經度
self.txtAlt.text = [NSString stringWithFormat:@"%3.5f",currLocation.altitude];//獲取設備當前的高度
}
//定位失敗時調用
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"error: %@",error);
}
//授權狀態發生變化時調用
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{//status是獲得的授權信息, 也可以使用self.locationManager.authorizationStatus = kCLAuthorizationStatusNotDetermined;獲得授權信息
if (status == kCLAuthorizationStatusAuthorizedAlways) {
NSLog(@"Authorized");
}else if (status == kCLAuthorizationStatusAuthorizedWhenInUse){
NSLog(@"AuthorizedWhenInUse");
}else if (status == kCLAuthorizationStatusDenied){
NSLog(@"Denied");
}else if (status == kCLAuthorizationStatusRestricted){
NSLog(@"Restricted");
}else if (status == kCLAuthorizationStatusNotDetermined){
NSLog(@"Determined");
}
}
@end
定位-01-定位服務編程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.