服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS中的地理位置的获取及plist设置方法

iOS中的地理位置的获取及plist设置方法

2021-04-19 19:56PinkJoker IOS

下面小编就为大家分享一篇iOS中的地理位置的获取及plist设置方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1、在前台的时候获取地理位置信息

ios 8/9

在info.plist中配置NSLocationWhenInUseUsageDescription的值,否则上面的方法无效

调用.requestWhenInUseAuthorization()获取前台获取地理位置权限

调用.startUpdatingLocation()

代码示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ViewController: UIViewController {
 lazy var locateM : CLLocationManager = {
  let locate = CLLocationManager()
  locate.delegate = self
  locate.requestWhenInUseAuthorization()
  return locate
 }()
 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
  self.locateM.startUpdatingLocation()
 }
}
extension ViewController : CLLocationManagerDelegate{
 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  print("位置信息已经更新")
 }
}

2、前后台获取,但是后台获取的时候,屏幕上方有蓝框提示用户正在后台获取

ios8

调用.requestWhenInUseAuthorization()获取前台获取地理位置权限

在info.plist中配置NSLocationWhenInUseUsageDescription的值,否则上面的方法无效

设置Capabilities>BackgroundModes>Location Updates 打对勾

调用.startUpdatingLocation()

ios9

调用.requestWhenInUseAuthorization()获取前台获取地理位置权限

设置 .allowsBackgroundLocationUpdates = true (ios 9需要执行)

在info.plist中配置NSLocationWhenInUseUsageDescription的值,否则上面的方法无效

设置Capabilities>BackgroundModes>Location Updates 打对勾 (如果第二步做了,此步没做,直接crash)

调用.startUpdatingLocation()

ios8/ios9可以后台蓝框定位的代码示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ViewController: UIViewController {
 lazy var locateM : CLLocationManager = {
  let locate = CLLocationManager()
  locate.delegate = self
  locate.requestWhenInUseAuthorization()
  if #available(iOS 9.0, *) {
   locate.allowsBackgroundLocationUpdates = true
  }
  return locate
 }()
 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
 
 
  self.locateM.startUpdatingLocation()
 }
}
extension ViewController : CLLocationManagerDelegate{
 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  print("位置信息已经更新")
 }
}

3、后台获取,后台获取的时候,屏幕上方无蓝框提示

调用.requestAlwaysAuthorization()获取前台获取地理位置权限

在info.plist中配置NSLocationAlwaysUsageDescription的值,否则上面的方法无效

设置 .allowsBackgroundLocationUpdates = true (ios 9需要执行)

设置Capabilities>BackgroundModes>Location Updates 打对勾 (本步骤在ios 8中可以不做设置,但是在ios9中如果第三步做了,而此步没有做,直接crash)

调用.startUpdatingLocation()

代码示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ViewController: UIViewController {
 lazy var locateM : CLLocationManager = {
  let locate = CLLocationManager()
  locate.delegate = self
  locate.requestAlwaysAuthorization()
  if #available(iOS 9.0, *) {
   locate.allowsBackgroundLocationUpdates = true
  }
  return locate
 }()
 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
 
 
  self.locateM.startUpdatingLocation()
 }
}
extension ViewController : CLLocationManagerDelegate{
 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  print("位置信息已经更新")
 }
}

4、权限改变的通知

注意:在Denied或者NotDetermined的状态下startUpdatingLocation,开始监听之后,当状态改变成允许的状态时,会直接进入监听状态,不必再次调用startUpdateingLocation

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
  switch status {
  case .AuthorizedAlways:
   print("始终")
  case .AuthorizedWhenInUse:
   print("使用的时候")
  case .Denied:
   print("拒绝")
   if CLLocationManager.locationServicesEnabled() {
    print("真拒绝了")
   }else{
    print("是关闭了定位服务")
   }
  case .NotDetermined:
   print("第一次,尚未决定")
  case .Restricted:
   print("没有权限的")
 
  }
 }

5、过滤距离

很多时候我们需要监听函数只调用一次来获取用户当前的位置

在监听函数中停止监听

设置监听的过滤距离

?
1
2
//如果监听器已经开启,此值修改之后立即生效
self.locateM.distanceFilter = 100 //每100米,调用一次监听

6、精度

注意:越精确越耗电,定位的时间越长,如果要定位城市,没有必要选最精确的

?
1
2
3
4
5
6
7
self.locateM.desiredAccuracy = kCLLocationAccuracyBest
 //kCLLocationAccuracyBestForNavigation
 //kCLLocationAccuracyBest
 //kCLLocationAccuracyNearestTenMeters
 //kCLLocationAccuracyHundredMeters
 //kCLLocationAccuracyKilometer
 //kCLLocationAccuracyThreeKilometers

7.CLLocation详解

?
1
2
3
4
5
6
7
8
9
10
11
public var coordinate: CLLocationCoordinate2D { get }  //经纬度
public var altitude: CLLocationDistance { get }   //海拔
public var horizontalAccuracy: CLLocationAccuracy { get } //位置信息是否有效,如果为负数,则无效
public var verticalAccuracy: CLLocationAccuracy { get } //海拔数据是否有效,如果为负数,则无效
public var course: CLLocationDirection { get }   //当前的角度(0-359.9)
public var speed: CLLocationSpeed { get }     //当前的速度 
public var timestamp: NSDate { get }      //位置确定的时间戳 
public var floor: CLFloor? { get }      //楼层(前提是已经注册的建筑),如果没有为nil 
 
//计算两个经纬度之间的距离 
public func distanceFromLocation(location: CLLocation) -> CLLocationDistance

8、指南针小例子

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class ViewController: UIViewController {
 
 @IBOutlet weak var mImageView: UIImageView!
 lazy var locateM : CLLocationManager = {
  let locate = CLLocationManager()
  locate.delegate = self
  locate.requestAlwaysAuthorization()
  if #available(iOS 9.0, *) {
   locate.allowsBackgroundLocationUpdates = true
  }
  return locate
 }()
 override func viewDidLoad() {
  super.viewDidLoad()
  if(CLLocationManager.headingAvailable()){
   self.locateM.startUpdatingHeading()
  }else{
   print("当前磁力计有问题")
  }
 }
}
extension ViewController : CLLocationManagerDelegate{
 func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
  //1.拿到当前设备对正朝向的角度
  let angle = newHeading.magneticHeading
  //2.把角度转换成弧度
  let hudu = CGFloat(angle / 180 * M_PI)
  //3.反向旋转照片
  UIView.animateWithDuration(0.5) {
   self.mImageView.transform = CGAffineTransformMakeRotation(-hudu)
  }
 }
}

9、区域的监听

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class ViewController: UIViewController {
 lazy var locateM : CLLocationManager = {
  let locate = CLLocationManager()
  locate.delegate = self
  locate.requestAlwaysAuthorization()
  if #available(iOS 9.0, *) {
   locate.allowsBackgroundLocationUpdates = true
  }
  return locate
 }()
 override func viewDidLoad() {
  super.viewDidLoad()
  //首先应该判断当前是否可以监听某个区域
  if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion){
   //1.创建区域
   let center = CLLocationCoordinate2DMake(21.123, 121.345)
   var distance : CLLocationDistance = 1000
   //限制监听的范围不能超过最大的范围
   if distance < locateM.maximumRegionMonitoringDistance{
    distance = locateM.maximumRegionMonitoringDistance
   }
   let region = CLCircularRegion(center: center, radius: distance, identifier: "xiaoxiao")
   //2.监听区域
   self.locateM.startMonitoringForRegion(region)
   //3.判断当前状态是否是在区域内还是区域外,
   //在`didDetermineState`代理方法中获得结果
   self.locateM.requestStateForRegion(region)
  }
 }
}
extension ViewController : CLLocationManagerDelegate{
 func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
  print("进入了区域"+region.identifier)
 }
 func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
  print("出了区域"+region.identifier)
 }
 func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
  //获取刚开始是否在区域内或者区域外
  if region.identifier == "xiaoxiao"{
   switch state {
   case .Inside:
    print("已经是区域内的")
   case .Outside:
    print("没有在区域内")
   case .Unknown:
    print("不清楚")
   }
  }
 }
}

10、地理编码与反地理编码

地理编码

?
1
2
3
4
5
6
7
8
9
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString("广州") { (pls:[CLPlacemark]?, error : NSError?) in
 if error == nil{
  print("地址编码成功")
  print(pls?.last?.location)
 }else{
  print("错误 \(error)")
 
}

打印

地址编码成功

?
1
Optional(<+23.12517800,+113.28063700> +/- 100.00m (speed -1.00 mps / course -1.00) @ 8/14/16, 9:49:22 PM China Standard Time)

反地理编码

?
1
2
3
4
5
6
7
8
9
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(CLLocation(latitude:23.125,longitude: 113.280)) { (pls:[CLPlacemark]?, error:NSError?) in
   if error == nil{
    print("地址反编码成功 城市:\(pls?.last?.locality)")
    print(pls?.last?.addressDictionary)
   }else{
    print("错误 \(error)")
   }
  }

打印

地址反编码成功 城市:Optional("Guangzhou")

?
1
2
3
4
5
6
Optional([SubLocality: Yuexiu, Street: Yunhai Tongjin No.11, State: Guangdong, CountryCode: CN, Thoroughfare: Yunhai Tongjin No.11, Name: Luo Sangmeidi, Country: China, FormattedAddressLines: <__NSArrayM 0x7ff1da5652d0>(
Yunhai Tongjin No.11 Yuexiu,
Guangzhou,
Guangdong China
)
, City: Guangzhou])

注意同一个CLGeocoder对象,不能同时编码与反编码

比如

?
1
2
3
4
5
6
7
8
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString("广州") { (pls:[CLPlacemark]?, error : NSError?) in
 ...
 
}
geoCoder.reverseGeocodeLocation(CLLocation(latitude:23.125,longitude: 113.280)) { (pls:[CLPlacemark]?, error:NSError?) in
 ...
 }

这样只会打印第一个编码成功的结果

11、CLPlacemark对象详解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@NSCopying public var location: CLLocation? { get }    //经纬度
@NSCopying public var region: CLRegion? { get }     //所关联的地理区域
@available(iOS 9.0, *)
@NSCopying public var timeZone: NSTimeZone? { get }    //时间域
public var addressDictionary: [NSObject : AnyObject]? { get } //详细地址信息
 
//addressDictionary中的属性
public var name: String? { get }     //名字
public var thoroughfare: String? { get }   //街道名字
public var subThoroughfare: String? { get }  //子街道名字
public var locality: String? { get }    //城市名称
public var subLocality: String? { get }   //邻城市名称
public var administrativeArea: String? { get }  //行政区域 比如:CA
public var subAdministrativeArea: String? { get } //子行政区域
public var postalCode: String? { get }    //邮政编码
public var ISOcountryCode: String? { get }   //国家代码表
public var country: String? { get }    //国家
public var inlandWater: String? { get }   //内陆水域
public var ocean: String? { get }     //海洋
public var areasOfInterest: [String]? { get }  //兴趣点

以上这篇iOS中的地理位置的获取及plist设置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/syh523364/article/details/58587116

延伸 · 阅读

精彩推荐
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01