当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS获取到用户当前位置

iOS获取到用户当前位置

2019年07月24日  | 移动技术网移动技术  | 我要评论

通过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值查找原因所在
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网