在iOS系統中, 使用CoreLocation可以獲取到用戶當前位置, 以及設備移動信息.
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:
6. 我們也可以自行輸入經緯度值來設置位置:
CoreLocation的基本使用就是以上這些了, 更加復雜的以後再補充了.