Почему мое приложение не отображает предупреждающее сообщение о включении служб локации в процессе подготовки (для: отправителя)? - PullRequest
0 голосов
/ 06 марта 2019

Я создаю навигационное приложение, которое предлагает пользователю включить службы определения местоположения.Если пользователь выбирает нет, чтобы включить их, и он / она возвращается обратно в мое приложение, мое приложение отказывается запускать ту же самую подсказку для включения служб определения местоположения, когда я выполняю вызов locationManager.requestWhenInUseAuthorization() в prepare(for:send) перед выполнением перехода segue..

Может кто-нибудь подсказать, почему предупреждение о включении служб определения местоположения не отображается в prepare(for:sender)?

Спасибо.

//
//  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
//
//        print("inside viewDidLoad() BEFORE IF authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
//
        if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
//
//            print("inside viewDidLoad() & IF BEFORE call: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
//
//            // prompts user to turn on location services
            locationManager.requestWhenInUseAuthorization()
//
//            print("inside viewDidLoad() & IF AFTER call: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
        }

        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
    }

    // 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" {

//            if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
////
//                print("prepare(for:sender) inside BEFORE: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
////
//                locationManager.requestWhenInUseAuthorization()
//
//                print("prepare(for:sender) AFTER: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
//
//                // authorized location status when app is in use; update current location
//                locationManager.startUpdatingLocation()
//
//            }

            let sitesTableVC = segue.destination as? SitesTableVC

            if let indexPath = self.tableView.indexPathForSelectedRow {

                selectedCounty = sortedCounties[indexPath.row]
                sitesTableVC?.selectedCounty = selectedCounty
                sitesTableVC?.currentCoordinate = currentCoordinate

            }

        }

        return

    }

}

extension CountiesTableVC: CLLocationManagerDelegate {

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

//        print("inside locationManager(manager:didUpdateLocations")

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

//        print("inside locationManager(manager:didUpdateLocations) authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")

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

        manager.stopUpdatingLocation()

    }

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

        if status != .authorizedWhenInUse {

//            print("locationManager(manager:didChangeAuthorization) BEFORE: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
//            print("locationManager(manager:didChangeAuthorization) BEFORE: status = \(status.rawValue)")

            manager.requestWhenInUseAuthorization()

//            print("locationManager(manager:didChangeAuthorization) AFTER: authorizationStatus = \(CLLocationManager.authorizationStatus().rawValue)")
//            print("locationManager(manager:didChangeAuthorization) AFTER: status = \(status.rawValue)")

        }

        // authorized location status when app is in use; update current location
        manager.startUpdatingLocation()

        return

    }

}

Ответы [ 2 ]

0 голосов
/ 06 марта 2019

Из документации :

Когда текущий статус авторизации равен CLAuthorizationStatus.notDetermined, этот метод работает асинхронно и запрашивает у пользователя разрешение на использование приложениями служб определения местоположения.,Приглашение пользователя содержит текст из ключа NSLocationWhenInUseUsageDescription в файле Info.plist вашего приложения, и при вызове этого метода требуется наличие этого ключа.После определения статуса менеджер местоположений доставляет результаты в метод locationManager делегата (_: didChangeAuthorization :). Если текущее состояние авторизации отличается от CLAuthorizationStatus.notDetermined , этот метод ничего не делает и не вызывает метод locationManager (_: didChangeAuthorization :).

(выделено мной)

т.е.как только ваш пользователь ответит на диалоговое окно разрешений, оно больше не будет отображаться.

0 голосов
/ 06 марта 2019

Вы можете запросить iOS до 2 раз для служб определения местоположения. Если пользователь отменяет включение служб определения местоположения оба раза, то в следующий раз приложение запрашивает requestWhenInUseAuthorization предупреждение не отображается.

Здесь вы можете узнать, отключил ли пользователь базовое местоположение, вызвав CLLocationManager метод класса locationServicesEnabled. Затем вы можете представить свое собственное оповещение, которое поможет пользователю вручную включить службы определения местоположения из приложения настроек iOS.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...