1
如果我在viewDidLoad上調用方法,但它不會返回任何數據。如果我將該方法添加到按鈕,並等待直到繪製位置,然後縮放它,則會正確拉取數據。我最初的想法是,一旦用戶允許定位,它將提取數據,而不必等待點擊按鈕來調用該方法。只有在提取用戶位置後才提取JSON數據
下面是代碼:
- (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);
}
我想根除雙重否定。 –
而且,在條件中使用它之前,您應該將它初始化爲一個理智的默認值。 –
好吧,所以我只是基本上添加布爾thisIsNotTheFirstTime;在我的伊娃頭,默認情況下布爾是否? – user3117785