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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25296691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:49:55  来源:igfitidea点击:

Get User's Current Location / Coordinates

iosswiftiphonelocationcllocationmanager

提问by Awais Hussain

How can I store the user's current location and also show the location on a map?

如何存储用户的当前位置并在地图上显示该位置?

I am able to show pre-defined coordinates on a map, I just don't know how to receive information from the device.

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

Also I know I have to add some items into a Plist. How can I do that?

我也知道我必须将一些项目添加到 Plist 中。我怎样才能做到这一点?

回答by Annu

To get a user's current location you need to declare:

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

let locationManager = CLLocationManager()

In viewDidLoad()you have to instantiate the CLLocationManagerclass, like so:

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()
}

Then in CLLocationManagerDelegate method you can get user's current location coordinates:

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

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

In the info.plist you will have to add NSLocationAlwaysUsageDescriptionand your custom alert message like; AppName(Demo App) would like to use your current location.

在 info.plist 中,您必须添加NSLocationAlwaysUsageDescription自定义警报消息,例如;AppName(Demo App) 想使用您当前的位置。

回答by itzhar

you should do those steps:

你应该做这些步骤:

  1. add CoreLocation.frameworkto BuildPhases -> Link Binary With Libraries (no longer necessary as of XCode 7.2.1)
  2. import CoreLocationto your class - most likely ViewController.swift
  3. add CLLocationManagerDelegateto your class declaration
  4. add NSLocationWhenInUseUsageDescriptionand NSLocationAlwaysUsageDescriptionto plist
  5. init location manager:

    locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    
  6. get User Location By:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
    
  1. 添加CoreLocation.framework到 BuildPhases -> Link Binary With Libraries(从 XCode 7.2.1 开始不再需要)
  2. 导入CoreLocation到您的类 - 很可能是 ViewController.swift
  3. 添加CLLocationManagerDelegate到您的类声明
  4. 添加NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription到 plist
  5. 初始化位置管理器:

    locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    
  6. 通过以下方式获取用户位置:

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

回答by swiftBoy

Update for iOS 12.2with Swift 5

使用Swift 5更新iOS 12.2

you must add following privacy permissions in plist file

您必须在 plist 文件中添加以下隐私权限

<key>NSLocationWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Description</string>


Here is how I am

这就是我的样子

getting current location and showing on Map in Swift 2.0

获取当前位置并在 Swift 2.0 中的地图上显示

Make sure you have added CoreLocationand MapKitframework to your project(This doesn't required with XCode 7.2.1)

确保您已将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)
    }
}

Here is the result screen

这是结果屏幕

a screenshot of the map, centered in Mumbai

a screenshot of the map, centered in Mumbai

回答by Mr.Javed Multani

Import library like:

导入库如:

import CoreLocation

set Delegate:

设置委托:

CLLocationManagerDelegate

Take variable like:

取变量,如:

var locationManager:CLLocationManager!

On viewDidLoad() write this pretty code:

在 viewDidLoad() 上写下这段漂亮的代码:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        locationManager.startUpdatingLocation()
    }

Write CLLocation delegate methods:

编写 CLLocation 委托方法:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error \(error)")
}

Now set permission for access the location, so add these key value into your info.plistfile

现在设置访问该位置的权限,因此将这些键值添加到您的info.plist文件中

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

enter image description here

enter image description here

100% working without any issue. TESTED

100% 工作没有任何问题。已测试

回答by Annu

@wonderwhy I have added my code screenshot. pls check it. You will have to add <code>NSLocationWhenInUseUsageDescription in the plist for authorisation.</code>

@wonderwhy I have added my code screenshot. pls check it. You will have to add <code>NSLocationWhenInUseUsageDescription in the plist for authorisation.</code>

NSLocationWhenInUseUsageDescription = Request permission to use location service when the apps is in background. in your plist file.

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

If this works then please vote the answer.

如果这有效,那么请投票给答案。

回答by MiladiuM

First import Corelocation and MapKit library:

首先导入 Corelocation 和 MapKit 库:

import MapKit
import CoreLocation

inherit from CLLocationManagerDelegate to our class

从 CLLocationManagerDelegate 继承到我们的类

class ViewController: UIViewController, CLLocationManagerDelegate

create a locationManager variable, this will be your location data

创建一个 locationManager 变量,这将是您的位置数据

var locationManager = CLLocationManager()

create a function to get the location info, be specific this exact syntax works:

创建一个函数来获取位置信息,具体来说这个确切的语法有效:

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

in your function create a constant for users current location

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

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

stop updating location, this prevents your device from constantly changing the Window to center your location while moving (you can omit this if you want it to function otherwise)

停止更新位置,这可以防止您的设备在移动时不断更改窗口以将您的位置居中(如果您希望它以其他方式运行,您可以省略此项)

manager.stopUpdatingLocation()

get users coordinate from userLocatin you just defined:

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

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

define how zoomed you want your map be:

定义您希望地图的缩放程度:

let span = MKCoordinateSpanMake(0.2,0.2)combine this two to get region:

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

now set the region and choose if you want it to go there with animation or not

现在设置区域并选择是否希望它带有动画

mapView.setRegion(region, animated: true)

close your function }

关闭你的功能 }

from your button or another way you want to set the locationManagerDeleget to self

从您的按钮或您想将 locationManagerDeleget 设置为 self 的其他方式

now allow the location to be shown

现在允许显示位置

designate accuracy

指定准确度

locationManager.desiredAccuracy = kCLLocationAccuracyBest

authorize:

授权:

 locationManager.requestWhenInUseAuthorization()

to be able to authorize location service you need to add this two lines to your plist

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

enter image description here

enter image description here

get location:

获取位置:

locationManager.startUpdatingLocation()

show it to the user:

显示给用户:

mapView.showsUserLocation = true

This is my complete code:

这是我的完整代码:

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)

    }
}

回答by Lyju I Edwinson

Swift 3.0

斯威夫特 3.0

If you don't want to show user location in map, but just want to store it in firebase or some where else then follow this steps,

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

import MapKit
import CoreLocation

Now use CLLocationManagerDelegate on your VC and you must override the last three methods shown below. You can see how the requestLocation() method will get you the current user location using these methods.

现在在您的 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)")
}

}

Now you can code the below call once user sign in to your app. When requestLocation() is invoked it will further invoke didUpdateLocations above and you can store the location to Firebase or anywhere else.

现在,一旦用户登录到您的应用程序,您就可以对以下调用进行编码。调用 requestLocation() 时,它将进一步调用上面的 didUpdateLocations,您可以将位置存储到 Firebase 或其他任何地方。

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

if you are using GeoFire then in the didUpdateLocations method above you can store the location as below

如果您使用的是 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. 

Last but not least, go to your Info.plist and enable "Privacy -Location when in Use Usage Description."

最后但并非最不重要的是,转到您的 Info.plist 并启用“使用使用说明时的隐私 - 位置”。

When you use simulator to test it always give you one custom location that you configured in Simulator -> Debug -> Location.

当您使用模拟器进行测试时,它始终为您提供一个您在模拟器 -> 调试 -> 位置中配置的自定义位置。

回答by Krutarth Patel

first add two frameworks in your project

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

1: MapKit

1:地图套件

2: Corelocation(no longer necessary as of XCode 7.2.1)

2:核心定位(从 XCode 7.2.1 开始不再需要)

Define in your class

在你的班级中定义

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

then in viewDidLoad method code this

然后在 viewDidLoad 方法中编码这个

manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()

//Setup our Map View
mapobj.showsUserLocation = true

do not forget to add these two value in plist file

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

1: NSLocationWhenInUseUsageDescription

2: NSLocationAlwaysUsageDescription

回答by ScottyBlades

import CoreLocation
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status != .authorizedWhenInUse {return}
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        let locValue: CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

Because the call to requestWhenInUseAuthorizationis asynchronous, the app calls the locationManagerfunction after the user has granted permission or rejected it. Therefore it is proper to place your location getting code inside that function given the user granted permission. This is the best tutorial on this I have found on it.

由于对 的调用requestWhenInUseAuthorization是异步的,应用程序locationManager在用户授予权限或拒绝后调用该函数。因此,在用户授予权限的情况下,将您的位置获取代码放置在该函数中是合适的。 这是我在上面找到的最好的教程

回答by Tek Raj

 override func viewDidLoad() {

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

This is your view did load method and in the ViewController Class also include the mapStart updating method as follows

这是您的视图确实加载方法,并且在 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();
}

Also do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project(no longer necessary as of XCode 7.2.1)

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