swift学习笔记(七)(定位)

swift学习笔记(七)(定位),第1张

概述代码如下: import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate {     @IBOutlet weak var locationLabel: UILabel!  // sb里的定位显示label          var locationManager


代码如下:


import UIKit

import CoreLocation


class VIEwController: UIVIEwController,CLLocationManagerDelegate {


@IBOutlet weak var locationLabel: UILabel! // sb里的定位显示label

var locationManager: CLLocationManager!

overrIDe func vIEwDIDLoad() {

super.vIEwDIDLoad()

}

overrIDe func preferredStatusbarStyle() -> UIStatusbarStyle {

return UIStatusbarStyle.lightContent

}

@IBAction func myLocationbuttonDIDtouch(sender: AnyObject) { // sb里的定位触发按钮

locationManager = CLLocationManager()

locationManager.delegate = self

locationManager.desiredAccuracy = kCLLocationAccuracyBest

locationManager.requestAlwaysAuthorization()

locationManager.startUpdatingLocation()

}


overrIDe func dIDReceiveMemoryWarning() {

super.dIDReceiveMemoryWarning()

// dispose of any resources that can be recreated.

}

func locationManager(manager: CLLocationManager,dIDFailWithError error: NSError) {

self.locationLabel.text = "Error while updating location " + error.localizedDescription

}

func locationManager(manager: CLLocationManager,dIDUpdateLocations locations: [CLLocation]) {

CLGeocoder().reverseGeocodeLocation(manager.location!,completionHandler: {(placemarks,error)->VoID in

if (error != nil) {

self.locationLabel.text = "Reverse geocoder Failed with error" + error!.localizedDescription

return

}

if placemarks!.count > 0 {

let pm = placemarks![0]

self.displayLocationInfo(pm)

} else {

self.locationLabel.text = "Problem with the data received from geocoder"

}

})

}

func displayLocationInfo(placemark: CLPlacemark?) {

if let containsPlacemark = placemark {

//stop updating location to save battery life

locationManager.stopUpdatingLocation()

let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""

let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""

let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""

let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""

self.locationLabel.text = locality! + postalCode! + administrativeArea! + country!

}

}


}


1.定位要用到coreLocation.framework,记得在info.pList中添加键值如下: NSLocationAlwaysUsageDescription String where are you
NSLocationWhenInUseUsageDescription String Allow to use location and can send it to me
这样就可以编写定位代码并定位了,这样会有是否允许定位的提示 总结

以上是内存溢出为你收集整理的swift学习笔记(七)(定位)全部内容,希望文章能够帮你解决swift学习笔记(七)(定位)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1079897.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存