Swift仅在启用位置服务时仅执行代码



在启用我的位置服务时,仅执行代码需要一些帮助,因为我有一个tableView从firebase中获取数据并逐距离组织,并且不希望该应用程序为用户崩溃。我还有一个Uirefreshcontrol,我只想在启用位置服务时执行代码。我当前的设置没有做我想要的。我正在发布我的整个ViewDidload以及我的Uirefreshcontrol。GetTableViewData()是我要根据启用位置服务执行的代码。谢谢。

override func viewDidLoad() {
    super.viewDidLoad()
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar
    locationManager.delegate = self
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()
    locationManager.requestAlwaysAuthorization()
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
            print("No access")
        case .authorizedAlways, .authorizedWhenInUse:
            print("Access")
            getTableViewData()
        }
    } else {
        print("Location services are not enabled")
    }
    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: #selector(RegisteredLocations.handleRefresh(refreshControl:)), for: UIControlEvents.valueChanged)
    tableView.addSubview(refresher)
}

@objc func handleRefresh(refreshControl: UIRefreshControl) {
    self.usersArray.removeAll()
    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
            print("No access")
        case .authorizedAlways, .authorizedWhenInUse:
            print("Access")
            getTableViewData()
        }
    } else {
        print("Location services are not enabled")
    }
    self.tableView.reloadData()
    refreshControl.endRefreshing()
}

您应该在启动位置更新之前先检查此方法的返回值,以确定用户是否对当前设备启用了位置服务。位置服务提示用户第一次尝试在应用程序中使用与位置相关的信息,但并未提示随后的尝试。如果用户拒绝使用位置服务,并且您尝试启动位置更新,则位置管理器向其委托报告错误。

周围的工作是提出警报以打开应用程序设置供用户启用位置服务。

 let alert = UIAlertController(title: "", message: "Please Allow the location Service to open this screen.", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Go to Settings", style: UIAlertActionStyle.default, handler: { (alert: UIAlertAction!) in
        UIApplication.shared.openURL(NSURL(string:UIApplicationOpenSettingsURLString)! as URL)
    }))
    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)

最新更新