如何使用CLLocationManager-Swift获取当前经度和纬度
发布时间:2020-12-14 05:42:12 所属栏目:百科 来源:网络整理
导读:我想使用Swift获取当前的纬度和纬度,并通过标签显示.我试图这样做,但标签上没有显示. import UIKit import CoreLocation class ViewController: UIViewController,CLLocationManagerDelegate{ @IBOutlet weak var longitude: UILabel! @IBOutlet weak var la
我想使用Swift获取当前的纬度和纬度,并通过标签显示.我试图这样做,但标签上没有显示.
import UIKit import CoreLocation class ViewController: UIViewController,CLLocationManagerDelegate{ @IBOutlet weak var longitude: UILabel! @IBOutlet weak var latitude: UILabel! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() if (CLLocationManager.locationServicesEnabled()) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } else { println("Location services are not enabled"); } } // MARK: - CoreLocation Delegate Methods func locationManager(manager: CLLocationManager!,didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() removeLoadingView() if ((error) != nil) { print(error) } } func locationManager(manager: CLLocationManager!,didUpdateLocations locations: [AnyObject]!) { var locationArray = locations as NSArray var locationObj = locationArray.lastObject as CLLocation var coord = locationObj.coordinate longitude.text = coord.longitude latitude.text = coord.latitude longitude.text = "(coord.longitude)" latitude.text = "(coord.latitude)" } }
IMHO,当您正在查找的解决方案非常简单时,您的代码过于复杂.
我已经通过使用以下代码: 首先创建一个CLLocationManager和请求授权的实例 var locManager = CLLocationManager() locManager.requestWhenInUseAuthorization() 然后检查用户是否允许授权. var currentLocation = CLLocation! if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){ currentLocation = locManager.location } 使用它只是这样做 label1.text = "(currentLocation.coordinate.longitude)" label2.text = "(currentLocation.coordinate.latitude)" 您将它们设置为label.text是正确的,但我可以想到的唯一原因是用户没有给您权限,这就是为什么您的当前位置数据将为零. 但是,您需要调试并告诉我们. 希望这有帮助.如果有疑问,请问 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 如何从服务器目录中制作Paperclip流程文件
- 从一张表中复制数据到另一张表中
- c# – 将动态变量强制转换为给定的Type
- dojo.query的简单使用
- log4j2.xml 配置
- 尝试在同一连接中运行多个命令时,C#Winforms Npgsql 3.0.5“
- ruby-on-rails – 在没有HTTP重定向的情况下,从另一个控制器
- c# – 将MidpointRounding.AwayFromZero设置为默认的舍入方
- reactjs – TypeError:dispatch不是函数.在React无状态组件
- react-native – 在本机中滚动到ScrollView组件底部时调用事