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

问题描述 投票:0回答:1

如果我的位置服务已启用,则需要一些仅执行代码的帮助,因为我有一个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()
}
ios swift location cllocation uirefreshcontrol
1个回答
0
投票

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

解决方法是提供警报以打开用户的应用程序设置以启用位置服务。

 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)
© www.soinside.com 2019 - 2024. All rights reserved.