首页 > 解决方案 > Xcode Swift,地理位置不会显示我在哪里

问题描述

任何人都明白为什么地理位置不会告诉我我在哪里,权限也不起作用......我很困惑......笔记本电脑位置很好,应用程序权限也设置了,还有允许权限点击,用户框也不会出现

(iv在上面解释了这一切,除非我在框中输入更多内容,否则它不会发布,但是有人可以解释为什么这段代码不起作用或者它根本没有显示错误,我也检查过 - 调试 - 位置... 依然没有

  import UIKit
  import MapKit
  import CoreLocation

  class MapScreen: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()
    let regionInMeters: Double = 10000

    override func viewDidLoad() {
        super.viewDidLoad()
        checkLocationServices()
    }


    func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }


    func centerViewOnUserLocation() {
        if let location = locationManager.location?.coordinate {
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
            mapView.setRegion(region, animated: true)
        }
    }


    func checkLocationServices() {
        if CLLocationManager.locationServicesEnabled() {
            setupLocationManager()
            checkLocationAuthorization()
        } else {
            // Show alert letting the user know they have to turn this on.
        }
    }


    func checkLocationAuthorization() {
        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            centerViewOnUserLocation()
            locationManager.startUpdatingLocation()
            break
        case .denied:
            // Show alert instructing them how to turn on permissions
            break
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .restricted:
            // Show an alert letting them know what's up
            break
        case .authorizedAlways:
            break
        }
    }
}


extension MapScreen: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)
    }


    func locationManager(_ manager: CLLocationManager,       didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()
    }
}

标签: swiftxcode

解决方案


您是否将权限字符串添加到您的 info.plist?

您需要为这些添加解释,否则不会出现权限提示,并且不会向您的应用发送位置更新。

NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription

你也应该在你的控制台中得到一个错误,所以也要检查一下。


推荐阅读