小編給大家分享一下iOS中如何獲取地理位置及設置plist,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
1、在前臺的時候獲取地理位置信息
ios 8/9
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
調用.requestWhenInUseAuthorization()獲取前臺獲取地理位置權限
調用.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("位置信息已經更新")
}
}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可以后臺藍框定位的代碼示例:
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()
代碼示例
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
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、過濾距離
很多時候我們需要監聽函數只調用一次來獲取用戶當前的位置
在監聽函數中停止監聽
設置監聽的過濾距離
//如果監聽器已經開啟,此值修改之后立即生效 self.locateM.distanceFilter = 100 //每100米,調用一次監聽
6、精度
注意:越精確越耗電,定位的時間越長,如果要定位城市,沒有必要選最精確的
self.locateM.desiredAccuracy = kCLLocationAccuracyBest //kCLLocationAccuracyBestForNavigation //kCLLocationAccuracyBest //kCLLocationAccuracyNearestTenMeters //kCLLocationAccuracyHundredMeters //kCLLocationAccuracyKilometer //kCLLocationAccuracyThreeKilometers
7.CLLocation詳解
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) -> CLLocationDistance8、指南針小例子
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、區域的監聽
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、地理編碼與反地理編碼
地理編碼
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
...
}這樣只會打印第一個編碼成功的結果
11、CLPlacemark對象詳解
@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”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。