Search code examples
xcodeswiftmapkitwatchkitapple-watch

Location always nil on WatchOS2


I'm trying to retrieve de Lat Long of my current position on my WatchOS2 app. The app is authenticated and the iPhone app works fine.
info.plist: NSLocationWhenInUseUsageDescription is set.

I use the following code in the willActivate()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if   (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse)
        {
            locationManager.requestWhenInUseAuthorization()
            print("Logon: Location not authorized1")
        }

    }   

        locationManager.requestLocation()

In the locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) i run this code:

    if locationManager.location != nil
    {
        self.userLat = String(self.locationManager.location!.coordinate.latitude)
        self.userLong = String(self.locationManager.location!.coordinate.longitude)

        print("Lat\(userLat) Long \(userLong)")
    }
    else
    {
        print("An error occurred") <- It always prints this error
    }
}


locationManager(manager: CLLocationManager, didFailWithError error: NSError)

is not being called


Solution

  • I've found a library which solved my problem. I don't know what exactly happend but it works now.

    I used the OneShotLocationManger by icanzilb

    I've you want to use this in your WatchOS2 app, you'll have to change startUpdatingLocation() to requestLocation(), because WatchOS doesn't allow continues updates.
    like so:

        //location authorization status changed
    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    
        switch status {
        case .AuthorizedWhenInUse:
            self.locationManager!.requestLocation()
        case .Denied:
            _didComplete(nil, error: NSError(domain: self.classForCoder.description(),
                code: OneShotLocationManagerErrors.AuthorizationDenied.rawValue,
                userInfo: nil))
        default:
            break
        }
    }
    

    Give Credit Where Credit Is Due -