首页 > 解决方案 > 使用 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)
   }
   ...
}

标签: xcodecocoaswift3mapkit

解决方案


斯威夫特 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 或将NSLocationAlwaysAndWhenInUseUsageDescriptionand/(or?)NSLocationUsageDescription设置为您需要访问用户位置的明文描述

    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>Allows us to locate you</string>
    <key>NSLocationUsageDescription</key>
        <string>Allows us to locate you</string>

如果用户关闭了定位服务,授权状态将是“拒绝”


推荐阅读