iOS項目開發實戰——使用CoreLocation擷取當前位置資訊

來源:互聯網
上載者:User

標籤:基於   memory   warning   uiview   control   執行   ==   rac   res   

       隨著基於位置服務LBS和移動互連網的興起,你的位置是越來越重要的一個資訊。位置服務已經是當前的熱門 App如。陌陌等社交應用的殺手鐧。而在iOS開發中,蘋果已經給我們提供了一個位置介面。CoreLocation,我們能夠使用該介面方便的獲得當前位置的經緯度資訊。詳細實現例如以下:

(1)建立基於Swift的iOS項目。在ViewController中匯入CoreLocation介面:

import CoreLocation

(2)在ViewController類中實現例如以下:

import UIKitimport CoreLocationclass ViewController: UIViewController,CLLocationManagerDelegate {    let locationManager:CLLocationManager = CLLocationManager()        override func viewDidLoad() {        super.viewDidLoad()        locationManager.delegate = self        locationManager.desiredAccuracy = kCLLocationAccuracyBest                if ios8(){                    locationManager.requestAlwaysAuthorization()                    }        locationManager.startUpdatingLocation()    }        func ios8()->Bool{        return UIDevice.currentDevice().systemVersion == "8.0"            }         func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){            var location:CLLocation = locations[locations.count-1] as! CLLocation        if(location.horizontalAccuracy > 0){                    println("緯度=\(location.coordinate.latitude)  ;經度=\(location.coordinate.longitude)")                                    locationManager.stopUpdatingLocation()        }    }    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){            println(error)    }        override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

(3)因為位置資訊是比較隱私的資訊,訪問使用者位置資訊前要徵求使用者的允許,所以須要在執行前進行提示:在Info.plist中配置內容:

key-value    :  NSLocationUsageDescription     "程式要訪問您的位置資訊"

key-value   :   NSLocationAlwaysUsageDescription     "程式要訪問您的位置資訊"


(4)執行程式。查看結果:



       總結一下。對於程式輸出結果。和我當前所處城市的位置資訊進行比較,發現存在較大誤差。我也不清楚這個因為什麼原因,眼下我在南方某城,經緯度資訊卻是在北方,可能是蘋果的位置服務有bug吧。

眼下國內基於百度地圖API,高德地圖等開發的應用也是比較多的,之前我也用百度地圖Android SDK開發過應用。介面也是很方便。定位等服務也是比較全面的,很適合開發,個人覺得假設要進行位置服務,還是不要用蘋果內建的吧。。。




github首頁:https://github.com/chenyufeng1991  。歡迎大家訪問。

iOS項目開發實戰——使用CoreLocation擷取當前位置資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.