標籤:
iOS定位和地圖功能要用到兩個架構:mapkitcoreLocation
兩個專門術語:lbs(Location Based Service)基於定位服務的APP和solomo(Social Local Mobile)社交+本地+手機。
1.匯入架構,匯入標頭檔。
2.建立CALocationManager對象。
3.設定代理。
4.實現方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations這個方法調用頻率很高,一般情況下需要在該方法下寫
停止語句。
#import "ViewController.h"#import <CoreLocation/CoreLocation.h>@interface ViewController () <CLLocationManagerDelegate>@property (nonatomic,strong) CLLocationManager *manager;//注意點@end@implementation ViewController- (CLLocationManager *)manager{ if(!_manager) { _manager = [[CLLocationManager alloc]init]; _manager.delegate = self; } return _manager;}- (void)viewDidLoad { [super viewDidLoad]; [self.manager startUpdatingLocation];//開啟定位}- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ NSLog(@"%@",locations); [self.manager stopUpdatingLocation];//停止定位}
注意點:要把CoreLocation對象設為全域變數,不然方法走完就被銷毀了。
在info.plist裡添加Privacy - Location Usage Description,增加描述(非必選)。
iOS8實現方法定位服務
#import "ViewController.h"#import <CoreLocation/CoreLocation.h>@interface ViewController () <CLLocationManagerDelegate>@property (nonatomic,strong) CLLocationManager *manager;@end@implementation ViewController- (CLLocationManager *)manager{ if(![CLLocationManager locationServicesEnabled]) { NSLog(@"不可用"); } if(!_manager) { _manager = [[CLLocationManager alloc]init]; _manager.delegate = self; if([[[UIDevice currentDevice]systemVersion]doubleValue]>8.0) { [_manager requestWhenInUseAuthorization];//前台定位。 //[_manager requestAlwaysAuthorization];//前後台同時定位。 } } return _manager;}- (void)viewDidLoad { [super viewDidLoad]; [self.manager startUpdatingLocation];//開啟定位}- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ NSLog(@"%@",locations); [self.manager stopUpdatingLocation];//停止定位}
在 info.plist裡加入對應的預設欄位 ,值設定為YES(前台定位寫上邊欄位,前後台定位寫下邊欄位)
NSLocationWhenInUseUsageDescription //允許在前台擷取GPS的描述
NSLocationAlwaysUsageDescription //允許在前、後台擷取GPS的描述
為了嚴謹期間,應該先判斷使用者是否開啟了定位服務,在進行後續的代碼。
if(![CLLocationManager locationServicesEnabled]) { NSLog(@"服務不可用"); return nil; }
iOS定位和地圖