为什么我的应用程序不显示提示询问访问用户位置的提示?

时间:2019-03-05 14:11:19

标签: ios swift location

我正在使用位置服务的iOS中开发一个导航应用程序,但是我遇到了问题。我有一个UITableViewController对象,它创建一个LocationManager的实例,并对其进行配置以实现所需的精度,距离过滤器等。我有didUpdateLocationsdidChangeAuthorization的委托,但出于某些原因在以下情况下会崩溃。位置服务已关闭,我启动了该应用程序,并且收到了打开位置服务的警报,然后返回到该应用程序,期望它显示另一条有关要求访问用户位置的警报,但该警报从未出现。当我在表格中选择一行时,应用崩溃,因为用户的当前位置尚未在我的UITableViewController中初始化。 didUpdateLocations没有被呼叫。

//  CountiesTableVC.swift
//  TableViewsApp
//
//  Created by Stephen Learmonth on 10/12/2018.
//  Copyright © 2018 Stephen Learmonth. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit

class CountiesTableVC: UITableViewController {

    let england : England = England()
    var countiesArray : [String] = ["Northamptonshire",
                                    "Bedfordshire",
                                    "Hertfordshire",
                                    "Staffordshire",
                                    "Essex",
                                    "North Yorkshire",
                                    "Herefordshire",
                                    "Cornwall",
                                    "Dorset",
                                    "Derbyshire",
                                    "Leicestershire",
                                    "Lancashire",
                                    "Cheshire",
                                    "Merseyside",
                                    "Suffolk",
                                    "County Durham",
                                    "Cumbria",
                                    "Gloucestershire",
                                    "Wiltshire",
                                    "Nottinghamshire",
                                    "Devon",
                                    "Somerset",
                                    "Lincolnshire"
                                    ]
    var sortedCounties : [ String ] = []

    var selectedCounty : String? = nil

    var currentCoordinate: CLLocationCoordinate2D! = nil
    var locationManager = CLLocationManager()

    override func viewDidLoad() {

        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        locationManager.distanceFilter = 10.0
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.requestWhenInUseAuthorization()

        sortedCounties = countiesArray.sorted{ $0 < $1 }

   }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sortedCounties.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CountyTableViewCell", for: indexPath) as! CountyTableViewCell

        let county = sortedCounties[indexPath.row]
        let countySites = england.counties[county]
        var siteIsSelectable = false
        if (countySites?.isEmpty)! == true {
            cell.backgroundColor = .gray
            cell.isUserInteractionEnabled = false
        } else {
            siteIsSelectable = true
            cell.backgroundColor = .blue
            cell.isUserInteractionEnabled = true
        }

        cell.setLabel(cellLabel: sortedCounties[indexPath.row], selectable: siteIsSelectable)

        return cell
    }


    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "toSitesTableVC" {

            let sitesTableVC = segue.destination as? SitesTableVC

            if let indexPath = self.tableView.indexPathForSelectedRow {
                selectedCounty = sortedCounties[indexPath.row]
                sitesTableVC?.selectedCounty = selectedCounty
                sitesTableVC?.currentCoordinate = currentCoordinate
            }

        } else {
            return
        }
    }


}

extension CountiesTableVC: CLLocationManagerDelegate {

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

    // get current location if avaialble
    guard let currentLocation = locations.last else { return }

    // get coordinates of current user location
    currentCoordinate = currentLocation.coordinate

    locationManager.stopUpdatingLocation()

    }

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

        if status == .authorizedWhenInUse {

            // authorized location status when app is in use; update current location
            locationManager.startUpdatingLocation()
            // implement additional logic if needed...
        }

    }

}

任何帮助将不胜感激。 谢谢。

3 个答案:

答案 0 :(得分:0)

检查此答案https://stackoverflow.com/a/38727017/2376336

几乎说您需要将这些密钥添加到info.plist中:

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription

过去,您只需添加它们,然后将它们留为空白,就不再是这种情况了。请确保输入正确简洁的说明,以说明为什么需要用户的位置。

答案 1 :(得分:0)

如果您的应用要求用户在“使用中”位置,则需要添加

Privacy - Location When In Use Usage Descriptioninfo.plist

如果您的应用要求用户位置“始终使用”,则需要添加

Privacy - Location When In Use Usage Description

Privacy - Location Always and When In Use Usage Description  在info.plist

答案 2 :(得分:0)

locationManager(manager:didChangeAuthorization)中,我需要将if条件表达式更改为status != .authorizedWhenInUse并调用 locationManager.requestWhenInUseAuthorization(),然后提示我第二个警告,要求您访问用户的位置。授权级别没有从.notDetemined更改为.authorizedWhenInuse,因此locationManager(manger:didUpdateLocations)的用户当前位置没有非零值。该nil值传递给另一个视图控制器,该控制器期望一个非nil值并且没有,因此崩溃了。