xcode - 使用 xcode swift 3 从 osx/cocoa 应用程序获取当前位置
问题描述
我很抱歉没有提供代码。我用图像发布它的原因是因为 xcode 是LLVM(低级虚拟机)编译器,它主要具有UI 环境,尤其是配置部分。例如,通过将对象拖到视图控制器而不是直接通过代码定义对象来为对象创建出口或动作。因此,既然如此,我认为人们会更容易更快地注意到我的错误。
import Cocoa
import MapKit
class ViewController: NSViewController, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView!
var locManager = CLLocationManager()
var currentLocation = CLLocation()
var locationManager = CLLocationManager()
var didFindMyLocation = false
var strForCurLatitude = "";
var strForCurLongitude = "";
override func viewDidLoad() {
super.viewDidLoad()
let distancespan:CLLocationDegrees = 2000
let busCScampuslocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude)
mapView.setRegion(MKCoordinateRegion.init(center: bsuCScampuslocation, latitudinalMeters: distancespan, longitudinalMeters: distancespan), animated: true)
print(currentLocation.coordinate.latitude)
}
...
}
解决方案
斯威夫特 5:
ViewController.swift
import Cocoa
import CoreLocation
import MapKit
class ViewController: NSViewController, CLLocationManagerDelegate {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
//This is where you can update the MapView when the computer is moved (locations.last!.coordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print("location manager auth status changed to: " )
switch status {
case .restricted:
print("restricted")
case .denied:
print("denied")
case .authorized:
print("authorized")
case .notDetermined:
print("not yet determined")
default:
print("Unknown")
}
}
将这些行添加到 Info.plist 或将NSLocationAlwaysAndWhenInUseUsageDescription
and/(or?)NSLocationUsageDescription
设置为您需要访问用户位置的明文描述
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Allows us to locate you</string>
<key>NSLocationUsageDescription</key>
<string>Allows us to locate you</string>
如果用户关闭了定位服务,授权状态将是“拒绝”
推荐阅读
- flutter - 颤振:使用 Float64List Matrix4 转换 CustomPaint 中的路径
- python - Python 和 C# TcpListener - 无法建立连接,因为目标机器主动拒绝它
- python - 在不平衡的数据集上使用 KNN 时,为什么设置 score='recall' 会将我的所有概率都变成二进制?
- angular - Angular 10匹配器孩子没有显示孩子
- python - 如何在 Django 中订购 URL?由于错误的网址,我收到“找不到页面”错误?
- android - 从 PlayStore 下载时,我无法登录我的 android 应用程序
- sql-server - 与 SQL Server 中的临时表相比,CTE 需要永远执行查询
- azure-cosmosdb - 如何从命令行启动 cosmosdb 模拟器?
- angularjs - Webpack 2.7.0 LoaderRunnerError: Module '*\node_modules\less\index.js' is not a loader (必须有正常或pitch函数)
- c++ - musl 的 GCC 包装器与 musl 的交叉编译器有何不同?