// 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()
}
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)")
}
}
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.
//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)")
}
现在设置访问该位置的权限,因此将这些键值添加到 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>
100% working without any issue. TESTED
14
首先在项目中添加两个框架
1: MapKit
2: Corelocation (从XCode 7.2.1开始不再需要)
在课堂上定义
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
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();
}
也 do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project (自 XCode 7.2.1 起不再需要)
// 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)
11 回答
你应该做这些步骤:
将
CoreLocation.framework
添加到BuildPhases - >使用库链接二进制文件(从XCode 7.2.1开始不再需要)import
CoreLocation
到你的 class - 很有可能是ViewController.swift将
CLLocationManagerDelegate
添加到您的 class 声明中将
NSLocationWhenInUseUsageDescription
和NSLocationAlwaysUsageDescription
添加到plist初始位置管理员:
要获取用户的当前位置,您需要声明:
在
viewDidLoad()
中,您必须实例化CLLocationManager
类,如下所示:然后在CLLocationManagerDelegate方法中,您可以获取用户的当前位置坐标:
在info.plist中,您必须添加
NSLocationAlwaysUsageDescription
和您的自定义警报消息; AppName(演示应用程序)想要使用您当前的位置 .我就是这样
确保已将 CoreLocation 和 MapKit 框架添加到项目中(XCode 7.2.1不需要这样做)
这是结果屏幕
NSLocationWhenInUseUsageDescription =在应用程序处于后台时请求使用位置服务的权限 . 在你的plist文件中 .
如果这样有效,那么请投票给答案 .
首先导入Corelocation和MapKit库:
从CLLocationManagerDelegate继承到我们的类
创建一个locationManager变量,这将是您的位置数据
创建一个函数来获取位置信息,具体这个确切的语法有效:
在您的函数中为用户创建一个常量当前位置
停止更新位置,这可以防止您的设备在移动时不断更改窗口以使您的位置居中(如果您希望它以其他方式运行,您可以省略它)
从刚刚定义的userLocatin获取用户坐标:
定义你想要你的 Map 缩放的方式:
let span = MKCoordinateSpanMake(0.2,0.2)
将这两个结合起来得到区域:现在设置区域,然后选择是否要用动画去那里
关闭你的功能
}
从您的按钮或您想要将locationManagerDeleget设置为self的其他方式
现在允许显示位置
指定准确性
授权:
to be able to authorize location service you need to add this two lines to your plist
获取位置:
向用户显示:
这是我的完整代码:
Swift 3.0
如果您不想在 Map 中显示用户位置,但只想将其存储在firebase或其他地方,请按照以下步骤操作:
现在在VC上使用CLLocationManagerDelegate,您必须覆盖下面显示的最后三个方法 . 您可以看到requestLocation()方法如何使用这些方法获取当前用户位置 .
现在,您可以在用户登录您的应用后对以下呼叫进行编码 . 调用requestLocation()时,它将进一步调用上面的didUpdateLocations,您可以将该位置存储到Firebase或其他任何位置 .
如果您使用的是GeoFire,那么在上面的didUpdateLocations方法中,您可以按如下方式存储位置
最后但同样重要的是,转到您的Info.plist并启用“隐私 - 使用时的位置使用说明” .
当您使用模拟器进行测试时,它总是为您提供一个在Simulator - > Debug - > Location中配置的自定义位置 .
导入库如:
设置代表:
变量如下:
在viewDidLoad()上写这个漂亮的代码:
编写CLLocation委托方法:
现在设置访问该位置的权限,因此将这些键值添加到 info.plist 文件中
100% working without any issue. TESTED
首先在项目中添加两个框架
1: MapKit
2: Corelocation (从XCode 7.2.1开始不再需要)
在课堂上定义
然后在viewDidLoad方法代码中这样做
不要忘记在plist文件中添加这两个值
这是你的视图做的加载方法,并且在ViewController类中还包括mapStart更新方法如下
也 do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project (自 XCode 7.2.1 起不再需要)
由于对
requestWhenInUseAuthorization
的调用是异步的,因此应用程序在用户授予权限或拒绝权限后调用locationManager
函数 . 因此,在用户授予权限的情况下,将您的位置置于该函数内是正确的 . This is the best tutorial on this I have found on it .