我有以下Swift 3代码,使用MapKit和CoreLocation查找当前位置的中心,但它不起作用。我做错了什么?

时间:2017-04-20 21:35:56

标签: xcode swift3 macos-sierra

以下是Swift 3项目中ViewController.swift文件的代码片段。我应该改变什么来使它工作或者你能给出任何指示?你知道为什么它不起作用,而是在完成当前位置的通知后进入某个arbritrary位置而不是我的位置?

import Cocoa
import MapKit
import CoreLocation

class ViewController: NSViewController, CLLocationManagerDelegate , MKMapViewDelegate{

    @IBOutlet weak var STAVO_map: MKMapView!
    var manager: CLLocationManager!
    var currentLocation : CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        manager = CLLocationManager()

        STAVO_map.delegate = self
        STAVO_map.showsUserLocation = true
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.delegate = self

        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
        }

        DispatchQueue.main.async {
            self.manager.startUpdatingLocation()
        }


    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.last as! CLLocation
        self.manager.stopUpdatingLocation()
        let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
        self.STAVO_map.setRegion(region, animated: true)
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

1 个答案:

答案 0 :(得分:0)

有些事情,首先我会将didUpdateLocations更改为

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last as! CLLocation
    manager.stopUpdatingLocation()
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)


    self.STAVO_map.setRegion(region, animated: true)
}

在viewDidLoad中... startUpdatingLocation是一个异步函数,所以在调用didUpdateLocations之前,你总是要设置noLocation。我会删除你设置noLocation的3行,viewRegion和setRegion。您不需要调用startUpdatingLocation两次,因此您可以删除第二个调用(此外,viewDidLoad默认在主队列中运行,因此不需要DispatchQueue)