GPS を使用して実際の位置をいくつかのラベルに表示するアプリケーションを入手しました。場所を更新する方法は次のとおりです。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
NSArray *locationArray = [[NSArray alloc] initWithObjects:placemark.thoroughfare,placemark.subThoroughfare,
placemark.postalCode,placemark.locality,placemark.country, nil];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[locationArray objectAtIndex:0],
[locationArray objectAtIndex:1],
[locationArray objectAtIndex:2],
[locationArray objectAtIndex:3],
[locationArray objectAtIndex:4]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
現在、'locationArray' の一部のオブジェクトが 'null' である場合があり、アプリケーション上で相対ラベルに '(null)' と表示されることがありますが、これはあまり良くありません。したがって、「locationArray」のオブジェクトが「null」であるかどうかをチェックする「if」サイクルが必要で、そうであれば表示されません。何か案は?
アップデート
アレイを削除し、@trojanfoe のメソッドを使用して問題を解決しました (わずかに変更されています)。コードは次のとおりです。
- (NSString *)sanitizedDescription:(NSString *)obj {
if (obj == nil)
{
return @"";
}
return obj;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[self sanitizedDescription:placemark.thoroughfare],
[self sanitizedDescription:placemark.subThoroughfare],
[self sanitizedDescription:placemark.postalCode],
[self sanitizedDescription:placemark.locality],
[self sanitizedDescription:placemark.country]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
助けてくれて本当にありがとう:)