码迷,mamicode.com
首页 > 移动开发 > 详细

CoreLocation---iOS中的位置信息

时间:2015-04-23 23:30:03      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:ios   location   swift   

在iOS系统中, 使用CoreLocation可以获取到用户当前位置, 以及设备移动信息.

基本步骤:

  1. import CoreLocation,
  2. ViewController 继承 CLLocationManagerDelegate 协议,
  3. 实现CLLocationManager的didUpdateLocations, didUpdateToLocation等方法,
  4. 开始定位: 调用CLLocationManager的startUpdatingLocation方法.
  5. 设备自身的定位要开启.

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的基本使用就是以上这些了, 更加复杂的以后再补充了.

CoreLocation---iOS中的位置信息

标签:ios   location   swift   

原文地址:http://blog.csdn.net/icetime17/article/details/45230483

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!