获取用户的当前位置/坐标

我对iOS开发很陌生。 不完全,但不完全是非常有经验的。

但基本上我只是想知道如何去存储用户的当前位置,并显示在地图上的位置。

我能够在地图上显示预先定义的坐标,我只是不知道如何从设备接收信息。

另外我知道我必须添加一些项目到Plist中。 你能和我一起去做我会怎么做吗?

要获取用户的当前位置,您需要声明:

 let locationManager = CLLocationManager() 

viewDidLoad()你必须立即CLLocationManager类,如下所示:

 // Ask for Authorisation from the User. self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } 

然后在CLLocationManagerDelegate方法中可以得到用户当前的位置坐标:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var locValue:CLLocationCoordinate2D = manager.location.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") } 

在info.plist中,您将不得不添加NSLocationAlwaysUsageDescription和您的自定义警报消息,如AppName(Demo App)想要使用您当前的位置。

你应该这样做:

  1. CoreLocation.framework添加到BuildPhases – >使用库链接二进制文件(不再需要XCode 7.2.1)
  2. 导入CoreLocation到你的类 – 可能ViewController.swift
  3. CLLocationManagerDelegate添加到您的类声明中
  4. 添加NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription来plist
  5. 初始位置pipe理器:

     locationManager = CLLocationManager() locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() 
  6. 获取用户地点通过:

     func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var locValue:CLLocationCoordinate2D = manager.location.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") } 

这是我的方式

获取当前位置并在Swift 2.0中显示在Map上

确保你已经添加了CoreLocationMapKit框架到你的项目中 (这在XCode 7.2.1中不需要)

 import Foundation import CoreLocation import MapKit class DiscoverViewController : UIViewController, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last! as CLLocation let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.map.setRegion(region, animated: true) } } 

这是结果屏幕

地图的屏幕截图,集中在孟买

@wonderwhy我已经添加了我的代码截图。请检查一下。您必须在plist中添加<code> NSLocationWhenInUseUsageDescription进行授权。</ code>

NSLocationWhenInUseUsageDescription =当应用程序在后台时请求使用位置服务的权限。 在你的plist文件中。

如果这个工作,然后请投票的答案。

首先导入Corelocation和MapKit库:

 import MapKit import CoreLocation 

从CLLocationManagerDelegateinheritance到我们的类

 class ViewController: UIViewController, CLLocationManagerDelegate 

创build一个locationManagervariables,这将是您的位置数据

 var locationManager = CLLocationManager() 

创build一个函数来获取位置信息,具体来说这个确切的语法工作原理:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

在你的函数中为用户当前的位置创build一个常量

 let userLocation:CLLocation = locations[0] as CLLocation // note that locations is same as the one in the function declaration 

停止更新位置,这可以防止您的设备在移动的同时不断地更改窗口以居中您的位置(如果您希望它可以正常工作,则可以省略)

 manager.stopUpdatingLocation() 

从userLocatin获取用户坐标,您刚定义:

 let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude) 

定义如何缩放你想要的地图:

let span = MKCoordinateSpanMake(0.2,0.2)结合这两个得到区域:

 let region = MKCoordinateRegion(center: coordinations, span: span)//this basically tells your map where to look and where from what distance 

现在设置该地区,并select是否要使用animation去那里

 mapView.setRegion(region, animated: true) 

closures你的function}

从你的button或另一种方式,你想将locationManagerDeleget设置为自我

现在允许显示位置

指定准确度

 locationManager.desiredAccuracy = kCLLocationAccuracyBest 

授权:

  locationManager.requestWhenInUseAuthorization() 

要能够授权位置服务,您需要将这两行添加到您的plist

在这里输入图像描述

获取位置:

 locationManager.startUpdatingLocation() 

展示给用户:

 mapView.showsUserLocation = true 

这是我的完整代码:

 import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func locateMe(sender: UIBarButtonItem) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() mapView.showsUserLocation = true } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let userLocation:CLLocation = locations[0] as CLLocation manager.stopUpdatingLocation() let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude) let span = MKCoordinateSpanMake(0.2,0.2) let region = MKCoordinateRegion(center: coordinations, span: span) mapView.setRegion(region, animated: true) } } 

首先在你的项目中添加两个框架

1: MapKit

2: Corelocation (不再需要XCode 7.2.1)

在你的class级定义

 var manager:CLLocationManager! var myLocations: [CLLocation] = [] 

然后在viewDidLoad方法中这个代码

 manager = CLLocationManager() manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestAlwaysAuthorization() manager.startUpdatingLocation() //Setup our Map View mapobj.showsUserLocation = true 

不要忘记在plist文件中添加这两个值

 1: NSLocationWhenInUseUsageDescription 2: NSLocationAlwaysUsageDescription 

Swift 3.0

如果您不想在地图中显示用户位置,但只想将其存储在Firebase或其他位置,请按照下列步骤操作,

 import MapKit import CoreLocation 

现在在你的VC上使用CLLocationManagerDelegate,你必须覆盖下面显示的最后三个方法。 您可以看到requestLocation()方法如何使用这些方法获取当前用户位置。

 class MyVc: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() isAuthorizedtoGetUserLocation() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters } } //if we have no permission to access user location, then ask user for permission. func isAuthorizedtoGetUserLocation() { if CLLocationManager.authorizationStatus() != .authorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } } //this method will be called each time when a user change his location access preference. func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { print("User allowed us to access location") //do whatever init activities here. } } //this method is called by the framework on locationManager.requestLocation(); func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("Did location updates is called") //store the user location here to firebase or somewhere } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Did location updates is called but failed getting location \(error)") } } 

现在,只要用户login到您的应用程序,您就可以编写以下通话。 调用requestLocation()时,它将进一步调用上面的didUpdateLocations,并且可以将该位置存储到Firebase或其他位置。

 if CLLocationManager.locationServicesEnabled() { locationManager.requestLocation(); } 

如果您正在使用GeoFire,那么在上面的didUpdateLocations方法中,您可以像下面那样存储位置

 geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation. 

最后但并非最不重要的,转到您的Info.plist并启用“隐私 – 位于使用中的使用说明”。

当你使用模拟器进行testing时,总会给你一个在模拟器 – >debugging – >位置中configuration的自定义位置。

  override func viewDidLoad() { super.viewDidLoad() locationManager.requestWhenInUseAuthorization(); if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } else{ print("Location service disabled"); } } 

这是你的视图加载方法,并且在ViewController类中还包括如下的mapStart更新方法

 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var locValue : CLLocationCoordinate2D = manager.location.coordinate; let span2 = MKCoordinateSpanMake(1, 1) let long = locValue.longitude; let lat = locValue.latitude; print(long); print(lat); let loadlocation = CLLocationCoordinate2D( latitude: lat, longitude: long ) mapView.centerCoordinate = loadlocation; locationManager.stopUpdatingLocation(); } 

另外不要忘记在你的项目中添加CoreLocation.FrameWork和MapKit.Framework (不再需要XCode 7.2.1

 import CoreLocation import UIKit class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() } //ViewDidLoad func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() let locValue: CLLocationCoordinate2D = (manager.location?.coordinate)! print("locations = \(locValue.latitude) \(locValue.longitude)") }//if authorized }//locationManager func declaration }//VC Class 

由于requestWhenInUseAuthorization的调用是asynchronous调用,因此应用程序在用户授予权限或拒绝它之后调用locationManager函数。 因此,在用户授予权限的情况下,将您的位置放置在该函数内部是正确的。 关于这个我find的最好的教程是: https : //www.hackingwithswift.com/read/22/2/requesting-location-core-location

 // its with strongboard @IBOutlet weak var mapView: MKMapView! //12.9767415,77.6903967 - exact location latitude n longitude location let cooridinate = CLLocationCoordinate2D(latitude: 12.9767415 , longitude: 77.6903967) let spanDegree = MKCoordinateSpan(latitudeDelta: 0.2,longitudeDelta: 0.2) let region = MKCoordinateRegion(center: cooridinate , span: spanDegree) mapView.setRegion(region, animated: true) 

你不必做很多东西,只需添加这两行,你就可以在地图上显示用户的当前位置,当用户点击button(你会有显示currnt位置button作为一个额外的好处:))

 mapView.myLocationEnabled = true mapView.settings.myLocationButton = true