дождитесь завершения CLLocationManager, прежде чем писать в Твиттере - PullRequest
0 голосов
/ 18 марта 2010

Я хочу дождаться заполнения latitude.text и longtitude.text перед отправкой твита, этот код работает нормально, но я бы не стал помещать часть твита в locationManager, потому что я также хочу иногда обновлять текущее местоположение без отправки твита. Как я могу убедиться, что текст перед заполнением перед отправкой твита без этого?

- (IBAction)update {
    latitude.text =@"";
    longitude.text =@"";
    locmanager = [[CLLocationManager alloc] init]; 
    [locmanager setDelegate:self]; 
    [locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locmanager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    CLLocationCoordinate2D location = [newLocation coordinate];
    latitude.text =   [NSString stringWithFormat: @"%f", location.latitude];
    longitude.text  = [NSString stringWithFormat: @"%f", location.longitude];

    TwitterRequest * t = [[TwitterRequest alloc] init];
    t.username = @"****";
    t.password = @"****";
    [twitterMessageText resignFirstResponder];
    loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@"Posting To Twitter..." delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    [loadingActionSheet showInView:self.view];
    [t statuses_update:twitterMessageText.text andLat:latitude.text andLong:longitude.text delegate:self requestSelector:@selector(status_updateCallback:)];
twitterMessageText.text=@"";
 }

1 Ответ

2 голосов
/ 18 марта 2010

Вы можете зарегистрировать слушателей в своем классе, который реализует CLLocationManagerDelegate.Например,

@interface GPS : NSObject <CLLocationManagerDelegate> {

  CLLocationManager *locationManager;

  NSMutableArray *listeners;
}

- (void) addListener:(id<GPSListener>)listener;
@end

@implementation GPS
- (IBAction)update {
  latitude.text =@"";
  longitude.text =@"";
  locmanager = [[CLLocationManager alloc] init]; 
  [locmanager setDelegate:self]; 
  [locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
  [locmanager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{ 
  CLLocationCoordinate2D location = [newLocation coordinate];
  latitude.text =   [NSString stringWithFormat: @"%f", location.latitude];
  longitude.text  = [NSString stringWithFormat: @"%f", location.longitude];

  // Inform the listeners.
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  for ( id<GPSListener> listener in listeners )
  {
    @try
    {
      [listener onLocationChangeForLatitude:latitude.text longitude:longitude];
    }
    @catch (NSException *e)
    {
      NSLog(@"Unhandled exception in onLocationChange");
    }
  }
  [pool release];
}

- (void) addListener:(id<GPSListener>)listener
{  
  [listeners addObject:listener];
}
@end 

У вас может быть набор слушателей, которые регистрируются с вашим объектом GPS.

@protocol GPSListener {
- (void) onLocationChangeForLatitude:(NSString *)latitude longitude:(NSString *)longitude;
}

Так что теперь вы можете иметь TweetGPSListener

@interface TweetGPSListener : NSObject <GPSListener> {
}
@end

@implementation TweetGPSListener
- (void) onLocationChangeForLatitude:(NSString *)latitude longitude:(NSString *)longitude {
  TwitterRequest * t = [[TwitterRequest alloc] init];
  t.username = @"****";
  t.password = @"****";
  [twitterMessageText resignFirstResponder];
  loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@"Posting To Twitter..."     delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
  [loadingActionSheet showInView:self.view];
  [t statuses_update:twitterMessageText.text andLat:latitude andLong:longitude   delegate:self requestSelector:@selector(status_updateCallback:)];
  twitterMessageText.text=@"";  
}  
@end

Так что для случаев, когда вы не хотите твитнуть, либо не регистрируйте слушателя, удалите слушателя или добавьте некоторую логику в TweetListener, чтобы знать, когда это уместно для твита.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...