如何在iOS中使用模拟器进行GPS坐标调试?

时间:2015-03-12 07:43:12

标签: ios objective-c gps

我试着获得我所在位置的坐标。

我堆栈溢出,所以我编码的内容如下:

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定位设置我的模拟器?

我不明白为什么我在协调方面遇到了麻烦。

3 个答案:

答案 0 :(得分:6)

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

  1. 您应该在某处保留locationManager以使其保持正常运行
  2. 实施-locationManager:didUpdateLocations:-locationManager:didFailWithError:委托方法
  3. 此外,如果您使用的是iOS 8,则应添加[locationMamager requestWhenInUseAuthorization];[locationMamager requestAlwaysAuthorization];
  4. 在Info.plist
  5. 中相应指定NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription

    您可以使用Xcode模拟位置,查看来自Apple的信息:https://developer.apple.com/library/ios/recipes/xcode_help-debugger/articles/simulating_locations.html

答案 1 :(得分:1)

[CLLocationManager location]会返回最近检索到的用户位置,但正如文档中所述:

  

如果从未检索到任何位置数据,则此属性的值为nil。

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

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

查看documentation

答案 2 :(得分:0)

- (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)");
    }
}