Search code examples
iosobjective-cwatchkitapple-watch

Retrieving location on the Apple Watch


I want to get the latitude and longitude of the user and display it on the Apple Watch.

I have already included the core location framework in my Watchkit Extension.

When I run the program all I get for the lat and long is 0.0 and 0.0

I tested the same method in a class on the iPhone and it worked, and gave me the appropriate coordinates. What am I doing wrong?

The .h file:

#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface InterfaceController : WKInterfaceController

@end

The .m file:

#import "InterfaceController.h"

@interface InterfaceController()

@end

@implementation InterfaceController

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    // Configure interface objects here.
}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

- (IBAction)showLocation {
    NSString * geoLoc  = [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
    NSLog(geoLoc);
}

@end

Solution

  • In Xcode, you want use the Debug menu to simulate a location that's either pre-set or use a GPX file as the location source.