FCCurrentLocationGeocoder封裝了原生的iOS定位api,可以使用block形式獲取用戶位置信息,但是使用過(guò)程中也有不少坑。
1、git地址
2、如果你使用的CocoaPods管理第三方庫(kù),那么在引用FCCurrentLocationGeocoder的時(shí)候,還需要引用FCIPAddressGeocoder,這個(gè)是對(duì)ip進(jìn)行反地理編碼的第三方庫(kù),并且在引用這兩個(gè)庫(kù)的時(shí)候,不能使用官方的master版本,需要使用下面的版本
pod 'FCIPAddressGeocoder' , '~> 1.0.0'
pod 'FCCurrentLocationGeocoder', '~> 1.1.11'
默認(rèn)的master版本為1.1.1和1.1.5
3、在項(xiàng)目中導(dǎo)入頭文件,然后使用測(cè)試代碼
FCCurrentLocationGeocoder *geocoder = [FCCurrentLocationGeocoder new];
geocoder.canPromptForAuthorization = NO; //(optional, default value is YES)
geocoder.canUseIPAddressAsFallback = YES; //(optional, default value is NO. very useful if you need just the approximate user location, such as current country, without asking for permission)
geocoder.timeFilter = 30; //(cache duration, optional, default value is 5 seconds)
geocoder.timeoutErrorDelay = 10; //(optional, default value is 15 seconds)
if ([geocoder canGeocode]) {
//current-location reverse-geocoding
[geocoder reverseGeocode:^(BOOL success) {
if(success)
{
NSLog(@"%@",geocoder.locationCountry);
NSLog(@"%@",geocoder.locationCity);
//you can access the current location using 'geocoder.location'
//you can access the current location placemarks using 'geocoder.locationPlacemarks'
//you can access the current location first-placemark using 'geocoder.locationPlacemark'
//you can access the current location country using 'geocoder.locationCountry'
//you can access the current location country-code using 'geocoder.locationCountryCode'
//you can access the current location city using 'geocoder.locationCity'
//you can access the current location zip-code using 'geocoder.locationZipCode'
//you can access the current location address using 'geocoder.locationAddress'
}
else {
NSLog(@"%@",geocoder.error);
//you can debug what's going wrong using: 'geocoder.error'
}
}];
}
關(guān)鍵是geocoder.canUseIPAddressAsFallback = YES;屬性在FCCurrentLocationGeocoder的版本中沒(méi)有
4、啟動(dòng)模擬器,需要在debug-->location中選擇一個(gè)位置,然后運(yùn)行程序就可以了
遇到問(wèn)題:
1、在ios8.0之后,還需要在info.plist文件中加入字符串NSLocationWhenInUseUsageDescription,在程序第一次請(qǐng)求數(shù)據(jù)的時(shí)候,會(huì)顯示你這里輸入的字符串
2、ios9.0對(duì)于后臺(tái)定位還有一些特殊的要求,或者想使用系統(tǒng)的定位功能,可以參考下面的文章,寫的比較詳細(xì)
iOS開(kāi)發(fā)之CoreLocation框架(地圖/定位)