小編給大家分享一下iOS中如何獲取地理位置及設(shè)置plist,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比五指山網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式五指山網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋五指山地區(qū)。費(fèi)用合理售后完善,10年實(shí)體公司更值得信賴。
1、在前臺(tái)的時(shí)候獲取地理位置信息
ios 8/9
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
調(diào)用.requestWhenInUseAuthorization()獲取前臺(tái)獲取地理位置權(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, withEvent event: UIEvent?) { self.locateM.startUpdatingLocation() } } extension ViewController : CLLocationManagerDelegate{ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("位置信息已經(jīng)更新") } }
2、前后臺(tái)獲取,但是后臺(tái)獲取的時(shí)候,屏幕上方有藍(lán)框提示用戶正在后臺(tái)獲取
ios8
調(diào)用.requestWhenInUseAuthorization()獲取前臺(tái)獲取地理位置權(quán)限
在info.plist中配置NSLocationWhenInUseUsageDescription的值,否則上面的方法無效
設(shè)置Capabilities>BackgroundModes>Location Updates 打?qū)?/p>
調(diào)用.startUpdatingLocation()
ios9
調(diào)用.requestWhenInUseAuthorization()獲取前臺(tái)獲取地理位置權(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可以后臺(tái)藍(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, withEvent event: UIEvent?) { self.locateM.startUpdatingLocation() } } extension ViewController : CLLocationManagerDelegate{ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("位置信息已經(jīng)更新") } }
3、后臺(tái)獲取,后臺(tái)獲取的時(shí)候,屏幕上方無藍(lán)框提示
調(diào)用.requestAlwaysAuthorization()獲取前臺(tái)獲取地理位置權(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, 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)時(shí),會(huì)直接進(jìn)入監(jiān)聽狀態(tài),不必再次調(diào)用startUpdateingLocation
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .AuthorizedAlways: print("始終") case .AuthorizedWhenInUse: print("使用的時(shí)候") case .Denied: print("拒絕") if CLLocationManager.locationServicesEnabled() { print("真拒絕了") }else{ print("是關(guān)閉了定位服務(wù)") } case .NotDetermined: print("第一次,尚未決定") case .Restricted: print("沒有權(quán)限的") } }
5、過濾距離
很多時(shí)候我們需要監(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、精度
注意:越精確越耗電,定位的時(shí)間越長,如果要定位城市,沒有必要選最精確的
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 } //位置確定的時(shí)間戳 public var floor: CLFloor? { get } //樓層(前提是已經(jīng)注冊(cè)的建筑),如果沒有為nil //計(jì)算兩個(gè)經(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)前磁力計(jì)有問題") } } } extension ViewController : CLLocationManagerDelegate{ func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { //1.拿到當(dāng)前設(shè)備對(duì)正朝向的角度 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)聽某個(gè)區(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("進(jìn)入了區(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("錯(cuò)誤 \(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("錯(cuò)誤 \(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])
注意同一個(gè)CLGeocoder對(duì)象,不能同時(shí)編碼與反編碼
比如
let geoCoder = CLGeocoder() geoCoder.geocodeAddressString("廣州") { (pls:[CLPlacemark]?, error : NSError?) in ... } geoCoder.reverseGeocodeLocation(CLLocation(latitude:23.125,longitude: 113.280)) { (pls:[CLPlacemark]?, error:NSError?) in ... }
這樣只會(huì)打印第一個(gè)編碼成功的結(jié)果
11、CLPlacemark對(duì)象詳解
@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 } //時(shí)間域 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 } //興趣點(diǎn)
看完了這篇文章,相信你對(duì)“iOS中如何獲取地理位置及設(shè)置plist”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!