【问题标题】:Pulling JSON data only after user location is fetched仅在获取用户位置后提取 JSON 数据
【发布时间】:2014-01-23 06:20:36
【问题描述】:

我在 viewDidLoad 上调用方法时遇到问题,但它不会返回任何数据。如果我将该方法添加到一个按钮,并等到绘制位置并对其进行缩放,则数据被正确拉出。我最初的想法是,一旦用户允许定位,它就会拉入数据,而不必等待点击按钮来调用方法。

代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.mapView.delegate = self;
    [self.mapView setShowsUserLocation:YES];

    // Instantiating location object
    locationManager = [[CLLocationManager alloc] init];

    [locationManager setDelegate:self];

    // Setting some parameters for the location object
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

    // THIS IS THE METHOD NOT WORKING UNLESS ADDED TO A BUTTON, AND WAITING 
    // FOR IT TO ZOOM, WHICH I ASSUME READ THE USERS PLOTTED LOCATION?
    [self queryGooglePlaces:@"food|restaurant"];

    // Do any additional setup after loading the view.
}
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
    MKCoordinateRegion region;
    region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate, 10*METERS_PER_MILE, 10*METERS_PER_MILE);

    [mv setRegion:region animated:YES];
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    //Get the east and west points on the map so you can calculate the distance (zoom level) of the current map view.
    MKMapRect mRect = self.mapView.visibleMapRect;
    MKMapPoint eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect));
    MKMapPoint westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect));

    //Set your current distance instance variable.
    currentDist = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint);

    //Set your current center point on the map instance variable.
    currentCentre = self.mapView.centerCoordinate;
}
-(void) queryGooglePlaces: (NSString *) googleType
{
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%@&types=%@&sensor=true&key=%@", currentCentre.latitude, currentCentre.longitude, [NSString stringWithFormat:@"%i", currentDist], googleType, kGOOGLE_API_KEY];

    NSURL *url2 = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

    // Formulate the string as an URL object
    NSURL *googleRequestURL = url2;

    // Retrieve the results of the URL
    dispatch_async(kBgQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL: googleRequestURL];
        [self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
    });
}
-(void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData

                          options:kNilOptions
                          error:&error];

    //The results from Google will be an array obtained from the NSDictionary object with the key "results".
    NSArray* places = [json objectForKey:@"results"];

    //Write out the data to the console.
    NSLog(@"Google Data: %@", places);
}

【问题讨论】:

    标签: ios objective-c mkmapview core-location


    【解决方案1】:

    我猜currentCentre 的值在 viewDidLoad 时间为零,因此缺乏食物和餐馆。

    你将不得不等待你的用户位置通过钩子返回一个有效值

    - (void)mapView:(MKMapView *)amapView didUpdateUserLocation:(MKUserLocation *)userLocation

    可能

    - (void)mapView:(MKMapView *)amapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    
      currentCentre = userLocation.location.coordinate;
    
      if(thisIsNotTheFirstTime == NO) {
    
         [self queryGooglePlaces:@"food|restaurant"];
         thisIsNotTheFirstTime = YES;
      }
    
    }
    

    thisIsNotTheFirstTime 是一个 ivar。如果你想消除双重否定,你必须明确地初始化它。

    【讨论】:

    • 我要根除双重否定。
    • 而且,在条件中使用它之前,您应该将其初始化为合理的默认值。
    • 好的,所以我基本上只是添加布尔 thisIsNotTheFirstTime;在我的 ivar 标题中,默认情况下布尔值是 NO ?
    • 是的,布尔变量总是在初始化时重置为 NO。必须显式设置本地变量,否则它们会包含垃圾。
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多