第一步
Info.plist中添加一项 NSLocationAlwaysUsageDescription 类型为 Boolean 值为 true
第二步
点击项目,选择 Build Phases 选项卡,如下图:
在 Build Phases 选项卡中 如下图操作引入 CoreLocation.framework 框架
第三步
以下代码实现:
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let changeLocation:NSArray = locations as NSArray
let currentLocation = changeLocation.lastObject
label1.text = "\(currentLocation!.coordinate.latitude)"
label2.text = "\(currentLocation!.coordinate.longitude)"
label3.text = "\(currentLocation!.altitude)"
}
}
第四步
编译、运行,显示应用,第一次打开的时候需要授权。