I have a location getter code, and i want to put it into an IBAction, but it has many -(VOI开发者_高级运维D)'s in it. How do I use the same code, but put it into one IBAction.
Here is the Action:
o
Here is the code I want to put in it:
@synthesize locationManager, delegate;
BOOL didUpdate = NO;
- (void)startUpdates
{
NSLog(@"Starting Location Updates");
if (locationManager == nil)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// You have some options here, though higher accuracy takes longer to resolve.
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your location could not be determined." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manage didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (didUpdate)
return;
didUpdate = YES;
// Disable future updates to save power.
[locationManager stopUpdatingLocation];
// let our delegate know we're done
[delegate newPhysicalLocation:newLocation];
}
- (void)dealloc
{
[locationManager release];
[super dealloc];
}
@end
You might want to read up on what the word IBAction means; it is just a fancy term for void, used in both:
- (void)startUpdates;
and
- (IBAction)buttonClick:(id)sender;
to mean 'returns no values or objects'.
I assume by 'put into an IBAction' you mean have a UI button or similar element trigger a fetch for location and update the UI accordingly. This is not directly possible, since location is an asynchronous call. You could easily create a synchronous wrapper, which would block all other operation until the location data was returned, but this is strongly discouraged. Instead, when dealing with location, it's generally better to engineer you application to provide the user an indicator that computation is occurring (spinner/progress bar), and then update the UI when your location callback comes back.
That might look something like this:
- (IBAction)locationButtonClick:(id)sender {
self.spinner.hidden = NO;
[self.spinner startAnimating];
self.myLocationManager.delegate = self;
[self.myLocationManager startUpdates];
}
- (void)newPhysicalLocation:(id)newLocation {
//TODO: Update UI
[self.spinner stopAnimating];
self.spinner.hidden = YES;
}
精彩评论