在iOS系统中, 使用CoreLocation可以获取到用户当前位置, 以及设备移动信息.
基本步骤:
- import CoreLocation,
- ViewController 继承 CLLocationManagerDelegate 协议,
- 实现CLLocationManager的didUpdateLocations, didUpdateToLocation等方法,
- 开始定位: 调用CLLocationManager的startUpdatingLocation方法.
- 设备自身的定位要开启.
ViewController
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
let locationManager: CLLocationManager = CLLocationManager()
var currentLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLLocationAccuracyKilometer
}
override func viewWillAppear(animated: Bool) {
locationManager.startUpdatingLocation()
println("start location")
}
override func viewWillDisappear(animated: Bool) {
locationManager.stopUpdatingLocation()
println("stop location")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("didUpdateLocations")
currentLocation = locations.last as! CLLocation
latitudeLabel.text = "\(currentLocation.coordinate.latitude)"
longitudeLabel.text = "\(currentLocation.coordinate.longitude)"
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
println("didUpdateToLocation")
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("didFailWithError")
}
}
模拟器定位设置
使用iPhone simulator时, 最初只看到打印”start location”, 即没有成功调用didUpdateLocations.
原因在于simulator默认将定位关闭, 需要我们自己打开.
1. 打开定位调试选项, 这里, 我们可以选择Apple:
2. 设置simulator中的Settings->Privacy->Location中的定位选项, 设为always: | 3. 回到APP界面, 即可看到位置信息: |
---|---|
4. 我们也可以自己选取模拟位置, 如选择Hong Kong: | 5. 可以看到, 对应模拟位置的经纬度信息: |
- | - |
6. 我们也可以自行输入经纬度值来设置位置:
CoreLocation的基本使用就是以上这些了, 更加复杂的以后再补充了.
时间: 2024-12-07 18:14:13