最近做基于XMPP的即時通訊,把相關內容總結整理下來看看!
一.利用CoreLocation獲取地理位置
利用CoreLocation,必須在frameworks里面加入"CoreLocation.framework",然后類中import <CoreLocation/CoreLocation.h>
1.定義成員變量
#import "LocationHelper.h"@interface LocationHelper ()<CLLocationManagerDelegate>{ CLLocationManager *_locationManager;}@PRoperty(nonatomic,copy)GetLocationCompledBlock getLocationCompledBlock;
2.實現單例
#pragma mark - shareLocationHelper單例+ (id)shareLocationHelper{ static LocationHelper *instance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[LocationHelper alloc] init]; }); return instance;}
3.進行初始化CLLocationManager位置管理器
- (void)setup { _locationManager = [[CLLocationManager alloc] init]; _locationManager.delegate = self; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; _locationManager.distanceFilter = 5.0; [_locationManager requestAlwaysAuthorization];}
desiredAccuracy為設置定位的精度,可以設為最優,裝置會自動用最精確的方式去定位。
distanceFilter是距離過濾器,為了減少對定位裝置的輪詢次數,位置的改變不會每次都去通知委托,而是在移動了足夠的距離時才通知委托程序,它的單位是米,這里設置為移動5再通知委托處理更新
4.實現外界要求獲取位置的請求
- (void)getCurrentGeolocationsCompled:(GetLocationCompledBlock)compled{ self.getLocationCompledBlock = compled; [_locationManager startUpdatingLocation];}
在此使用startUpdatingLocation啟動定位管理了,一般來說,在不需要更新定位時最好關閉它,用stopUpdatingLocation,可以節省電量。
5.實現CLLocationManagerDelegate代理方法獲取位置更新信息
#pragma mark - CLLocationManager Delegate// 代理方法實現- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLGeocoder* geocoder = [[CLGeocoder alloc] init]; [geocoder reverseGeocodeLocation:newLocation completionHandler: ^(NSArray* placemarks, NSError* error) { if (self.getLocationCompledBlock) { self.getLocationCompledBlock(placemarks); } }]; [manager stopUpdatingLocation];}- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { [manager stopUpdatingLocation];}- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{ switch (status) { casekCLAuthorizationStatusNotDetermined: if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [_locationManager requestAlwaysAuthorization]; } break; default: break; } }
6.控制器中調用方法獲取位置信息后加TAG發送
[self.locationHelper getCurrentGeolocationsCompled:^(NSArray *placemarksA) { CLPlacemark *placemark = [placemarksA lastObject]; if (placemark) { NSDictionary *addressDictionary = placemark.addressDictionary; NSArray *formattedAddressLines = [addressDictionary valueForKey:@"FormattedAddressLines"]; NSString *geoLocations = [formattedAddressLines lastObject]; if (geoLocations) { //geoLocations===中國**** [weakSelf didSendGeolocationsMessageWithGeolocaltions:geoLocations]; } }}];
二.CLLocationManager為什么就不調用代理
代碼方法開開心心的寫完了,但是在發送地理位置消息的時候老是沒有消息,郁悶了,斷點發現代理根本都沒進,最后分析找資料得到解決
上述編碼均完成后在Plist文件中添加字段NSLocationAlwaysUsageDescription
新聞熱點
疑難解答