iOS如何用模拟器调试GPS坐标?

How to get GPS coordinate debugging with simulator in iOS?

我尝试获取我所在位置的坐标。

我用 Whosebug,所以我的代码如下:

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];

CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];

self.longitude=coordinate.longitude;
self.latitude=coordinate.latitude;

NSLog(@"dLongitude : %f",self.longitude);
NSLog(@"dLatitude : %f", self.latitude);

但我总是得到 0。上面的代码错了吗?或者 我没有为我的模拟器设置 GPS 定位?

我不明白为什么我在获取坐标时遇到问题。

首先,您的代码中存在几个问题:

  1. 你应该在某个地方保留 locationManager 来保存它 运行
  2. 实现 -locationManager:didUpdateLocations:-locationManager:didFailWithError: 委托方法
  3. 此外,如果你在iOS8,你应该添加[locationMamager requestWhenInUseAuthorization];[locationMamager requestAlwaysAuthorization];
  4. 在 Info.plist
  5. 中相应地指定 NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription

可以用Xcode模拟定位,看看苹果的资料:https://developer.apple.com/library/ios/recipes/xcode_help-debugger/articles/simulating_locations.html

[CLLocationManager location] 将 return 您最近检索到的用户位置,但如文档所述:

The value of this property is nil if no location data has ever been retrieved.

一开始你的位置还未知。当 CLLocationManager 找到您的位置时,您应该使用委托方法做出反应。实现这个方法:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    //User your location...
}

看看documentation

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    BOOL shouldIAllow = FALSE;
    NSString* locationStatus = @"";

    switch (status) {
        case kCLAuthorizationStatusRestricted:
            locationStatus = @"Restricted Access to location";
            break;
        case kCLAuthorizationStatusDenied:
            locationStatus = @"User denied access to location";
            break;
        case kCLAuthorizationStatusNotDetermined:
            locationStatus = @"Status not determined";
        default:
            locationStatus = @"Allowed to location Access";
            shouldIAllow = TRUE;
            break;
    }

    if (shouldIAllow) {
        NSLog(@"Location to Allowed");
        // Start location services
        [_locationManager startUpdatingLocation];
    } else {
        NSLog(@"Denied access: \(locationStatus)");
    }
}