基本上跟 Objective-C 的用法差不多 , 只是換成 Swift 語法

  1. 增加兩個字串到 info.plist (type : String)
    • NSLocationWhenInUseUsageDescription
    • NSLocationAlwaysUsageDescription
  2. import CoreLocation
  3. 繼承 CLLocationManagerDelegateViewController Class
  4. 設定 CLLocationManagerDelegate 的 function 來接收資料
  5. 別忘記 locationManager.startUpdatingLocation() << 這樣才會開始抓 location 資料
  6. 為了不一直抓取位置資訊 在抓到資訊的 delegate func 中加上 locationManager.stopUpdatingLocation() 來停止抓取位置資訊

Sample Code.

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager : CLLocationManager!
    var currentLocation : CLLocation?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.initLocationManager()
    }

    func initLocationManager(){
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    //MARK: Location Manager Delegate
    
    // get error
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
        println(error)
    }
    
    //get location
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        
        locationManager.stopUpdatingLocation()
        var locationArray = locations as Array
        self.currentLocation = locationArray[locationArray.count-1] as? CLLocation

        println(self.currentLocation)

        //getHotPlaceFromFacebook(self.currentLocation)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

以上~~!!