在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的基本使用就是以上這些了, 更加復雜的以後再補充了.