如何在Apple Watch中使用CoreLocation获取当前位置?

时间:2018-04-11 18:16:51

标签: ios swift watchkit core-location watch-os

我在Apple Watch上获取用户位置时遇到了问题。当我尝试在模拟器上运行时,我无法获得该位置,但在实际手表上运行它会返回我的位置。但是有些情况不会让我回到我的位置。为什么会这样?

另外,我应该如何在info.plist中进行位置访问的条目?目前我已添加到iPhone和Apple Watch应用程序。

这是我请求位置的方式。

func requestLocation() {
        guard !isRequestingLocation else {
            manager.stopUpdatingLocation()
            isRequestingLocation = false

            return
        }

        let authorizationStatus = CLLocationManager.authorizationStatus()

        switch authorizationStatus {
        case .notDetermined:
            print("notDetermined")
            isRequestingLocation = true
            manager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse, .authorizedAlways:
            print("authorizedWhenInUse")
            isRequestingLocation = true
            manager.requestLocation()
            infoLabel.setText("Fetching Location...")
        case .denied:
            print("denied location")
        case .restricted:
            print("restricted location")
        }
    }

在委托方法下面找到找到的位置。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard !locations.isEmpty else { return }

        DispatchQueue.main.async {
            self.currentLocation = locations.last!.coordinate
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        DispatchQueue.main.async {
        print(error.localizedDescription)
            self.currentLocation = nil
        }
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        DispatchQueue.main.async {
            guard self.isRequestingLocation else { return }

            switch status {
            case .authorizedWhenInUse:
                manager.requestLocation()

            case .denied:
                print("Auth Denied")
                self.currentLocation = nil

            default:
                print("Auth Default")
                self.currentLocation = nil
            }
        }
    }

0 个答案:

没有答案