简体   繁体   English

使用Swift查找纬度和经度

[英]Find Latitude and Longitude using Swift

I like to know if it is possible to find the Latitude and the Longitude on iPhone that is not connected to WIFI and using cellular data while inside a building with Swift? 我想知道是否可以在装有Swift的建筑物内的iPhone上找到未连接到WIFI并使用蜂窝数据的iPhone上的纬度和经度?

IF not what is the alternative way of determine that? 如果不是,还有其他确定方法吗?

Try this code in order to get the Latitude and the Longitude: 尝试以下代码以获取纬度和经度:

First create an instance of CLLocationManager and Request Authorization 首先创建CLLocationManager的实例和请求授权

var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()

then check if the user allowed authorization. 然后检查用户是否允许授权。

var currentLocation = CLLocation!

if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){

      currentLocation = locManager.location

}

to use it just do this 用它来做到这一点

label1.text = "\(currentLocation.coordinate.longitude)"
label2.text = "\(currentLocation.coordinate.latitude)"

For iOS 8 and swift2.3 add your project's info.plist privacy for always location use and then use this code 对于iOS 8和swift2.3,请添加项目的info.plist隐私权,以便始终在位置上使用,然后使用此代码

let locationManager = CLLocationManager()
var userLatitude:CLLocationDegrees! = 0
var userLongitude:CLLocationDegrees! = 0

use this code in viewDidLoad - 在viewDidLoad中使用此代码-

self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled()

{
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startMonitoringSignificantLocationChanges()

    userLatitude  = locationManager.location?.coordinate.latitude
    userLongitude  = locationManager.location?.coordinate.longitude
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM