由于项目的需要,我们在开发产品的过程中需要使用到定位系统。
这个过程中,我们需要使用到两个库:CoreLocation.framework 与MapKit.framework。前者是用来获取定位的坐标信息,后者是通过坐标信息来获取地址信息。
首先增加库文件:
通过这三步,然后就打开一个类库来进行查找。
输入关键字,找到对应的类库,加入到我们的项目之中。
可以看到这两个包已经引入到我们的项目之中来了,下面我们在需要使用的地方增加代码。
首先import,然后添加这个delegate
现在我们点击进入这个delegate看一下对应的方法:
看一下比较重要的方法:
1、发生错误的时候调用这个
获取到定位信息后调用这个方法:
这里我们可以看到这里有个解释:osx开始版本为iphone6.0以上,如果是6.0一下的版本该如何呢
我们看到了这个方法,iphone2.0以上iphone6.0以后废弃,所以为了代码健壮性,我们要实现这两个方法。
*注意:要将后面的_osx这段删掉。
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
if(locations!=nil&&locations.count>0){
CLLocation *newLocation= locations[0];
CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
NSLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);
//停止获取location
[manager stopUpdatingLocation];
//------------------位置反编码---5.0之后使用-----------------
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *placemarks, NSError *error){
for (CLPlacemark *place in placemarks) {
UILabel *label = (UILabel *)[self.window viewWithTag:101];
label.text = place.name;
NSLog(@"您当前的位置为,%@",place.name); // 位置名
// NSLog(@"thoroughfare,%@",place.thoroughfare); // 街道
// NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
// NSLog(@"locality,%@",place.locality); // 市
// NSLog(@"subLocality,%@",place.subLocality); // 区
// NSLog(@"country,%@",place.country); // 国家
}
}];
}
}
这样就可以获取了。