Swift基礎--定位

//
//  ViewController.swift
//  JieCoreLocation
//
//  Created by jiezhang on 14-10-4.
//  Copyright (c) 2014年 jiezhang. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate{

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    @IBOutlet weak var longitudeTxt: UITextField!
    @IBOutlet weak var latitudeTxt: UITextField!
    @IBOutlet weak var HeightTxt: UITextField!
    @IBOutlet weak var addressTxt: UILabel!
    var currLocation : CLLocation!
    
    //地址反編譯出錯誤,不清楚什麼問題,我是在模擬器上模擬的
    @IBAction func reverseGeocode(sender: AnyObject) {
        var geocoder = CLGeocoder()
        var p:CLPlacemark?
        geocoder.reverseGeocodeLocation(currLocation, completionHandler: { (placemarks, error) -> Void in
            if error != nil {
                println("reverse geodcode fail: \(error.localizedDescription)")
                return
            }
            let pm = placemarks as [CLPlacemark]
            if (pm.count > 0){
                p = placemarks[0] as? CLPlacemark
                println(p)
            }else{
                println("No Placemarks!")
            }
        })
    }
    //用於定位服務管理類,它能夠給我們提供位置信息和高度信息,也可以監控設備進入或離開某個區域,還可以獲得設備的運行方向
    let locationManager : CLLocationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        //設備使用電池供電時最高的精度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //精確到1000米,距離過濾器,定義了設備移動後獲得位置信息的最小距離
        locationManager.distanceFilter = kCLLocationAccuracyKilometer
        
    }
    
    override func viewWillAppear(animated: Bool) {
        locationManager.startUpdatingLocation()
        println("定位開始")
    }
    
    override func viewWillDisappear(animated: Bool) {
        locationManager.stopUpdatingLocation()
        println("定位結束")
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
        currLocation = locations.last as CLLocation
        longitudeTxt.text = "\(currLocation.coordinate.longitude)"
        latitudeTxt.text = "\(currLocation.coordinate.latitude)"
        HeightTxt.text = "\(currLocation.altitude)"
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
        println(error)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }


}





發佈了200 篇原創文章 · 獲贊 29 · 訪問量 222萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章