iOS中的地理位置的獲取及plist設(shè)置方法
1、在前臺的時候獲取地理位置信息
ios 8/9
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
調(diào)用.requestWhenInUseAuthorization()獲取前臺獲取地理位置權(quán)限
調(diào)用.startUpdatingLocation()
代碼示例
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("位置信息已經(jīng)更新")
}
}
2、前后臺獲取,但是后臺獲取的時候,屏幕上方有藍(lán)框提示用戶正在后臺獲取
ios8
調(diào)用.requestWhenInUseAuthorization()獲取前臺獲取地理位置權(quán)限
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
設(shè)置Capabilities>BackgroundModes>Location Updates 打?qū)?/p>
調(diào)用.startUpdatingLocation()
ios9
調(diào)用.requestWhenInUseAuthorization()獲取前臺獲取地理位置權(quán)限
設(shè)置 .allowsBackgroundLocationUpdates = true (ios 9需要執(zhí)行)
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
設(shè)置Capabilities>BackgroundModes>Location Updates 打?qū)?(如果第二步做了,此步?jīng)]做,直接crash)
調(diào)用.startUpdatingLocation()
ios8/ios9可以后臺藍(lán)框定位的代碼示例:
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("位置信息已經(jīng)更新")
}
}
3、后臺獲取,后臺獲取的時候,屏幕上方無藍(lán)框提示
調(diào)用.requestAlwaysAuthorization()獲取前臺獲取地理位置權(quán)限
在info.plist中配置NSLocationAlwaysUsageDescription的值,否則上面的方法無效
設(shè)置 .allowsBackgroundLocationUpdates = true (ios 9需要執(zhí)行)
設(shè)置Capabilities>BackgroundModes>Location Updates 打?qū)?(本步驟在ios 8中可以不做設(shè)置,但是在ios9中如果第三步做了,而此步?jīng)]有做,直接crash)
調(diào)用.startUpdatingLocation()
代碼示例
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("位置信息已經(jīng)更新")
}
}
4、權(quán)限改變的通知
注意:在Denied或者NotDetermined的狀態(tài)下startUpdatingLocation,開始監(jiān)聽之后,當(dāng)狀態(tài)改變成允許的狀態(tài)時,會直接進入監(jiān)聽狀態(tài),不必再次調(diào)用startUpdateingLocation
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .AuthorizedAlways:
print("始終")
case .AuthorizedWhenInUse:
print("使用的時候")
case .Denied:
print("拒絕")
if CLLocationManager.locationServicesEnabled() {
print("真拒絕了")
}else{
print("是關(guān)閉了定位服務(wù)")
}
case .NotDetermined:
print("第一次,尚未決定")
case .Restricted:
print("沒有權(quán)限的")
}
}
5、過濾距離
很多時候我們需要監(jiān)聽函數(shù)只調(diào)用一次來獲取用戶當(dāng)前的位置
在監(jiān)聽函數(shù)中停止監(jiān)聽
設(shè)置監(jiān)聽的過濾距離
//如果監(jiān)聽器已經(jīng)開啟,此值修改之后立即生效 self.locateM.distanceFilter = 100 //每100米,調(diào)用一次監(jiān)聽
6、精度
注意:越精確越耗電,定位的時間越長,如果要定位城市,沒有必要選最精確的
self.locateM.desiredAccuracy = kCLLocationAccuracyBest //kCLLocationAccuracyBestForNavigation //kCLLocationAccuracyBest //kCLLocationAccuracyNearestTenMeters //kCLLocationAccuracyHundredMeters //kCLLocationAccuracyKilometer //kCLLocationAccuracyThreeKilometers
7.CLLocation詳解
public var coordinate: CLLocationCoordinate2D { get } //經(jīng)緯度
public var altitude: CLLocationDistance { get } //海拔
public var horizontalAccuracy: CLLocationAccuracy { get } //位置信息是否有效,如果為負(fù)數(shù),則無效
public var verticalAccuracy: CLLocationAccuracy { get } //海拔數(shù)據(jù)是否有效,如果為負(fù)數(shù),則無效
public var course: CLLocationDirection { get } //當(dāng)前的角度(0-359.9)
public var speed: CLLocationSpeed { get } //當(dāng)前的速度
public var timestamp: NSDate { get } //位置確定的時間戳
public var floor: CLFloor? { get } //樓層(前提是已經(jīng)注冊的建筑),如果沒有為nil
//計算兩個經(jīng)緯度之間的距離
public func distanceFromLocation(location: CLLocation) -> CLLocationDistance
8、指南針小例子
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("當(dāng)前磁力計有問題")
}
}
}
extension ViewController : CLLocationManagerDelegate{
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
//1.拿到當(dāng)前設(shè)備對正朝向的角度
let angle = newHeading.magneticHeading
//2.把角度轉(zhuǎn)換成弧度
let hudu = CGFloat(angle / 180 * M_PI)
//3.反向旋轉(zhuǎn)照片
UIView.animateWithDuration(0.5) {
self.mImageView.transform = CGAffineTransformMakeRotation(-hudu)
}
}
}
9、區(qū)域的監(jiān)聽
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()
//首先應(yīng)該判斷當(dāng)前是否可以監(jiān)聽某個區(qū)域
if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion){
//1.創(chuàng)建區(qū)域
let center = CLLocationCoordinate2DMake(21.123, 121.345)
var distance : CLLocationDistance = 1000
//限制監(jiān)聽的范圍不能超過最大的范圍
if distance < locateM.maximumRegionMonitoringDistance{
distance = locateM.maximumRegionMonitoringDistance
}
let region = CLCircularRegion(center: center, radius: distance, identifier: "xiaoxiao")
//2.監(jiān)聽區(qū)域
self.locateM.startMonitoringForRegion(region)
//3.判斷當(dāng)前狀態(tài)是否是在區(qū)域內(nèi)還是區(qū)域外,
//在`didDetermineState`代理方法中獲得結(jié)果
self.locateM.requestStateForRegion(region)
}
}
}
extension ViewController : CLLocationManagerDelegate{
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("進入了區(qū)域"+region.identifier)
}
func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
print("出了區(qū)域"+region.identifier)
}
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
//獲取剛開始是否在區(qū)域內(nèi)或者區(qū)域外
if region.identifier == "xiaoxiao"{
switch state {
case .Inside:
print("已經(jīng)是區(qū)域內(nèi)的")
case .Outside:
print("沒有在區(qū)域內(nèi)")
case .Unknown:
print("不清楚")
}
}
}
}
10、地理編碼與反地理編碼
地理編碼
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString("廣州") { (pls:[CLPlacemark]?, error : NSError?) in
if error == nil{
print("地址編碼成功")
print(pls?.last?.location)
}else{
print("錯誤 \(error)")
}
}
打印
地址編碼成功
Optional(<+23.12517800,+113.28063700> +/- 100.00m (speed -1.00 mps / course -1.00) @ 8/14/16, 9:49:22 PM China Standard Time)
反地理編碼
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")
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對象,不能同時編碼與反編碼
比如
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString("廣州") { (pls:[CLPlacemark]?, error : NSError?) in
...
}
geoCoder.reverseGeocodeLocation(CLLocation(latitude:23.125,longitude: 113.280)) { (pls:[CLPlacemark]?, error:NSError?) in
...
}
這樣只會打印第一個編碼成功的結(jié)果
11、CLPlacemark對象詳解
@NSCopying public var location: CLLocation? { get } //經(jīng)緯度
@NSCopying public var region: CLRegion? { get } //所關(guān)聯(lián)的地理區(qū)域
@available(iOS 9.0, *)
@NSCopying public var timeZone: NSTimeZone? { get } //時間域
public var addressDictionary: [NSObject : AnyObject]? { get } //詳細(xì)地址信息
//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 } //行政區(qū)域 比如:CA
public var subAdministrativeArea: String? { get } //子行政區(qū)域
public var postalCode: String? { get } //郵政編碼
public var ISOcountryCode: String? { get } //國家代碼表
public var country: String? { get } //國家
public var inlandWater: String? { get } //內(nèi)陸水域
public var ocean: String? { get } //海洋
public var areasOfInterest: [String]? { get } //興趣點
以上這篇iOS中的地理位置的獲取及plist設(shè)置方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
ios利用RunLoop原理實現(xiàn)去監(jiān)控卡頓實例詳解
這篇文章主要為大家介紹了ios利用RunLoop原理實現(xiàn)去監(jiān)控卡頓實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
iOS使用UICollectionView實現(xiàn)列表頭部拉伸效果
這篇文章主要介紹了iOS使用UICollectionView實現(xiàn)列表頭部拉伸效果,OC和Swift兩個版本,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
iOS中tableView cell分割線的一些設(shè)置技巧
在項目開發(fā)中我們會常常遇到tableView 的cell分割線顯示不全,左邊會空出一截像素,更有甚者想改變系統(tǒng)的分割線,下面通過這篇文章來一起學(xué)習(xí)學(xué)習(xí)在iOS中tableView cell分割線的一些設(shè)置技巧,需要的朋友可以參考借鑒,下面來一起看看吧。2017-05-05
iOS動態(tài)調(diào)整UILabel高度的幾種方法
在iOS編程中UILabel是一個常用的控件,下面這篇文章主要給大家介紹了關(guān)于iOS動態(tài)調(diào)整UILabel高度的幾種方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
iOS 開發(fā)之 - 關(guān)閉鍵盤 退出鍵盤 的5種方式
這篇文章主要介紹了iOS 開發(fā)之 - 關(guān)閉鍵盤 退出鍵盤 的5種方式的相關(guān)資料,需要的朋友可以參考下2016-09-09

