ios - 在 viewDidLoad 中获取位置

标签 ios swift cllocationmanager

我正在尝试获取用户位置,但在加载 View 时它不起作用。我有一个刷新方法,效果很好,但需要用户点击刷新按钮。当 View 加载时,用户位置出现在 map 上,但在 getLocation() 中,myLocation 为 nil。再一次,点击调用 refreshLocation() 的刷新按钮按预期工作。

override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer

        mapView.userTrackingMode = .follow

        getLocationAuthorizationStatus()
    }

请求授权

func getLocationAuthorizationStatus() {
        print("getLocationAuthorizationStatus()")
        if CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        } else if CLLocationManager.authorizationStatus() == .denied {
            // Display UIAlertController
            let locationDeniedAlert = BasicAlert(title: "", message: "Location services were denied. Please enable location services in Settings.", preferredStyle: .alert)

            let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: {
                (action) -> Void in
                let settingsURL = URL(string: UIApplicationOpenSettingsURLString)
                if let url = settingsURL {
                    // UIApplication.shared.openURL(url)
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }

                locationDeniedAlert.dismiss(animated: true, completion: nil)
            })

            locationDeniedAlert.addAction(settingsAction)

            self.present(locationDeniedAlert, animated: true, completion: nil)

        } else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            if fromSearch {
                fromSearch = false
            } else {
                getLocation()
            }
        }
    }

获取位置

func getLocation() {
        print("getLocation()")
        locationManager.startUpdatingLocation()

        if locationManager.location != nil {
            myLocation = locationManager.location!
            if mapView.annotations.count == 1 && mapView.annotations[0] as! MKUserLocation == mapView.userLocation {
                retrieveGymsWithLocation()
            }
        } else {
            myLocation = nil
            print("location = nil")
        }
    }

    @objc func refreshLocation() {
        print("refreshLocation()")
        let annotationsToRemove = mapView.annotations
        mapView.removeAnnotations(annotationsToRemove)
        gyms.removeAll()
        imageArrays.removeAll()
        gymLocations.removeAll()

        getLocationAuthorizationStatus()
    }

位置管理器

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        manager.stopUpdatingLocation()
        myLocation = locations.last
    }

最佳答案

CLLocationManager 需要一段时间才能确定当前位置,具体取决于 gps 卫星可用性和其他各种影响。因此,您只需要等待一段时间,直到位置属性被设置。 您通常会在委托(delegate)方法中执行此操作:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    myLocation = locations.last

    if mapView.annotations.count == 1 && mapView.annotations[0] as! MKUserLocation == mapView.userLocation {
        retrieveGymsWithLocation()
    } 
}

关于ios - 在 viewDidLoad 中获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283989/

相关文章:

c# - iOS UI 的 MVVM 交叉图片选择器插件不会在 Bytes 类型 View 模型属性上使用 InMemoryImage 进行更新

swift - 使用未声明的类型 'MainGameScreenViewController'

ios - XCTest CLLocationManager 的委托(delegate)方法不会被调用

ios - 如何旋转 GMSMarker 以显示用户移动方向?

ios - UIImage 内存未释放 VM : ImageIO_JPEG_DATA?

ios - UIBarButtonItem 错误的编辑/完成动画

IOS Swift如何使用后台获取

swift - 如何在 swift 4.2 中解析以下动态 JSON?

ios - 位置管理器 :didFailWithError: not called if user Location Services are off

ios - Uber API 端点不适用于真实服务器域,但适用于沙箱