Search code examples
iosobjective-cwatchkit

iOS: Watch Kit get current location and show on map


I have an iOS app that uses a users current location to show directions/ distance between the users current location and a destination point. I am able to show the destination point on the map, however when I try to get the user's current location using CLlocationManager, it returns coordinates (0,0). Below is my code for retrieving the users location.

Is retrieving current location possible on the Apple Watch?

If so, what am I doing wrong here that the location is returning (0,0)?

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = 5;
CLLocation *location = locationManager.location;

CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

Also, I have #import < CoreLocation/CoreLocation.h> in my .h file and < CLLocationManagerDelegate>


Solution

  • Try the following code:

    @property (nonatomic, strong) CLLocationManager *locationManager;
    
    - (void)willActivate
    {
        self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        [self.locationManager requestLocation];
    }
    
    - (void)locationManager:(CLLocationManager *)manager
         didUpdateLocations:(NSArray *)locations
    {
        if ([locations count] == 0) {
            // error
            return;
        }
    
        // success
        self.currentLocation = [locations firstObject];
        CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(
            self.currentLocation.coordinate.latitude, 
            self.currentLocation.coordinate.longitude);
    }
    
    - (void)locationManager:(CLLocationManager *)manager
           didFailWithError:(nonnull NSError *)error
    {
        // error
    }