Reputation: 600
I am very new to threads so please be gracious.
In the Login View Controller after the user is authenticated, I launch a thread to get the users geolocation every 30 seconds (only want to do this when the user is logged in) and then move to the main view controller of the application which displays the applications main information.
When the user logs out, I want to cancel the thread created to gather the geolocation every 30 seconds.
How do I do this?
Am I approaching this correct? If not, code examples and explanation pleases
Thanks so much!!!!
Loggin View Controller
...
- (IBAction)loginButton:(id)sender {
NSInteger success = 0;
//Check to see if the username or password texfields are empty or email field is in wrong format
if([self validFields]){
//Try to login user
success = [self loginUser];
}
//If successful, go to the MainView
if (success) {
//Start getting users Geolocation in a thread
[NSThread detachNewThreadSelector:@selector(startGeolocation:) toTarget:self withObject:nil];
//Go to Main view controller
[self performSegueWithIdentifier:@"loginSuccessSegue" sender:self];
}
else
{
//Reset password text field
self.passwordTextField.text = @"";
}
}
...
//Thread to get Geolocation every 30 seconds
-(void)startGeolocation:(id)param{
self.geoLocation = [[GeoLocation alloc] init];
while(1)
{
//****************START GEOLOCATION*******************************//
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.databaseLock lock];
NSLog(@"Geolocation:(%f,%f)", [self.geoLocation getLatitude], [self.geoLocation getLongitude]);
sleep(30);
[appDelegate.databaseLock unlock];
}
}
Main View Controller
...
//When the Logout Button in MenuView is pressed this method will be called
- (void)logoutButton{
//Cancel the geolocation tread
//????????????????????????????
//Log the user out
[self logoutUser]
}
...
Upvotes: 0
Views: 142
Reputation: 552
I would recommend using GCD for this.
dispatch_queue_t dq = dispatch_queue_create("bkgrndQueue", NULL);
dispatch_async(dq, ^{
@autoreleasepool{
while(SEMAPHORE_NAME){
// do stuff in here
}
}
}
and then in your other view controller
SEMAPHORE_NAME = NO;
Upvotes: 1