iOS定位操作 iOS获取到用户当前位置

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

iOS定位操作 iOS获取到用户当前位置

  2021-03-22 我要评论
想了解iOS获取到用户当前位置的相关内容吗,在本文为您仔细讲解iOS定位操作的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:iOS定位,iOS获取用户当前位置,iOS获取当前位置,下面大家一起来学习吧。

通过CoreLocation定位,获取到用户当前位置,跟地图中的定位不同。

一、导入CoreLocation.framework

二、#import <CoreLocation/CoreLocation.h>

三、声明代理 <CLLocationManagerDelegate>

四、代码实现

1、声明

CLLocationManager *locationManager;//定义Manager
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
  CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];

   self.locationManager.delegate = self;
}else {
   //提示用户无法进行定位操作
}

// 开始定位
[locationManager startUpdatingLocation];


2、更新位置后代理方法,iOS6.0一下的方法

- (void)locationManager:(CLLocationManager *)manager 
  didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation {

 //latitude和lontitude均为NSString型变量
    //纬度
 self.latitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.latitude];

    //经度
 self.longitude = [NSString stringWithFormat:@"%.4f",     newLocation.coordinate.longitude];
 
}


3、iOS6.0以上苹果的推荐方法

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
  //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
  CLLocation *currentLocation = [locations lastObject];
  
  CLLocationCoordinate2D coor = currentLocation.coordinate;
  self.latitude = coor.latitude;
  self.longitude = coor.longitude;
  
  //[self.locationManager stopUpdatingLocation];
  
}

4、更新失败的方法

- (void)locationManager:(CLLocationManager *)manager
    didFailWithError:(NSError *)error {
 
 if (error.code == kCLErrorDenied) {
   // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
 }
}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们