Geolocation asynchronous iOS [closed] - ios

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I would like to geolocalize in the background with a thred! But I can not, I tried scheduler, thred, operation ect ect ... but all I block the progress of the progressBar.

I use a singleton object for the location like this...
#implementation LocationManager
#pragma mark - singleton method
+ (LocationManager*)sharedInstance
{
static dispatch_once_t predicate = 0;
__strong static id sharedObject = nil;
dispatch_once(&predicate, ^{
sharedObject = [[self alloc] init];
});
return sharedObject;
}
#pragma mark - instance methods
-(id) init {
if (self = [super init]) {
_currentLocation = [[CLLocation alloc] init];
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
_locationManager.delegate = self;
}
return self;
}
- (void)start
{
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
if ( abs((int) [newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {
self.currentLocation = newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
// [[[UIAlertView alloc] initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
#end
Then I just need to call...
[[LocationManager sharedInstance] start];
and the singleton will start tracking location.
Than I call...
[[LocationManager sharedInstance] currentLocation];
for the current location.
You can then use this to pass into the already asynchronous methods of CLGeocoder.
You can't rely on starting the location tracking and then instantly having the location. You need to use a method like this.

CLGeocoder is running in background.

Related

Method orders in viewDidLoad

I have methods in viewDidLoad, and it seems like the order of methods getting called is weird.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
// Retrieve Data
[self retrieveData];
}
After viewDidLoad is called, it calls the retrieveData method before locationManager.
Shouldn't the locationManager be called before retrieveData because of the order?
I am new in Objective C, thank you for your help in advance.
as per your need call your method in inside the delegate methods, so remove the [self retrieveData]; from ViewDidLoad and add into inside the didFailWithError or didUpdateLocations methods.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
// call here
[self retrieveData];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// set or stop your location update
manager = nil;
[self.locationManager stopUpdatingLocation];
[manager stopUpdatingLocation];
CLLocation *newLocation = locations[[locations count] -1];
CLLocation *currentLocation = newLocation;
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
if (currentLocation != nil) {
NSLog(#"latitude: %#", latitude);
NSLog(#"longitude: #"%#", longitude);
}else {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
}
// call here
[self retrieveData];
}
Note
objective -C is the interpreter , it execute the every in step by step , so or may be your [self retrieveData]; is called in main thread, that is the reason it execute in prior.

Repeat Calls to geolocation Singleton class from multiple views in iOS app

After reading some recommendations on stack overflow and some other articles I have implemented a singleton class that allows me to call a method to update a user's current location. To avoid continuous update of the location information, I added a StopUpdatingPosition call. This works fine for the first time, however following calls fail.
I believe this is because of the way the geolocation stuff is initiated in the examples provided where it checks to see if the singleton is already in place(?)
If a singleton is initialised does it remain in memory? On subsequent calls can I check to see if this is the case and just request it to start updating position?
Here is what I have tried so far.
- (id)init {
self = [super init];
if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setHeadingFilter:kCLHeadingFilterNone];
[self.locationManager startUpdatingLocation];
geocoder = [[CLGeocoder alloc] init];
}
return self;
}
+ (LocationFunction*)sharedSingleton {
static LocationFunction* sharedSingleton;
if(!sharedSingleton) {
#synchronized(sharedSingleton) {
sharedSingleton = [LocationFunction new];
}
}
return sharedSingleton;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
myLat = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
myLong = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
}
// Store the Long & Lat to global variables here
NSLog(#"Resolving the Address");
} else {
// Handle location lookup fail here
}
} ];
[manager stopUpdatingLocation];
}
I am looking for a way of calling method in an external class from different view controllers. This method obtains the user's current position (Long & Lat), records the info in a global variable, stops any requests to update location method and notifies the view controller when it is done.
Pointers appreciated.
Another stackoverflow question has an answer that provides a solution. Note however that the call is not correct (I am unable to comment on the answer - too new to stackoverflow!). It should reference "sharedManager" :
- (void)viewDidLoad
{
[super viewDidLoad];
[[MyClass sharedManager] startCapture];
}
Hope this helps anyone searching.

How to get 'current location only' in iOS?

I am using Core Location framework to getting location in iOS. I use, CLLocationManager *locationManager; and call [locationManager startUpdatingLocation];
Problem is I only need instantaneous location but startUpdatingLocation keep on giving me location. To stop this I can use [self.locationManager stopUpdatingLocation], but this look like a way out or hack.
Is there any better way to just get current location in iOS?
in your .h file
#import <CoreLocation/CoreLocation.h>
#interface LocationSearchViewController : UIViewController<UITextFieldDelegate,CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
in your .m file
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
[locationManager stopUpdatingLocation]; // when u got the lat and long it stop uoatde the location
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *getcurrlong = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSSting *getcurrlat = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
You can't think of location in those precise terms. You'll get back increasingly accurate locations from the location manager and it's up to you to decide when it's accurate enough. You have to weigh this against power usage and time. The location updates will never be completely accurate. The will never be returned immediately. The device has to power up hardware, then listen for GPS/WiFi/Cell signals and use all those to calculate location.
There's no way to ask for "my precise current location" and have it given to you immediately. Location is not a property like [NSDate date]. You can only ask for best-estimate location updates and they will only come to you in imprecise measurements, and never instantaneously (excepting cached location).
Check it
-(void)getCurrentLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
startLocation = nil;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (startLocation == nil)
{
startLocation = newLocation;
[locationManager setDelegate:nil];
locationManager = nil;
}
}

Why am I getting all of these compilation errors in my iOS app? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to add this UI on top of my map in my app to show the current speed a driver is driving. I get these errors in main.m. Why, and how can I fix it?
Use of undeclared identifier 'viewSpeed'
Instance method '-setViewSpeed:' not found (return type defaults to 'id')
locationmanager.m
Expected ':'
Expected method body
Expected identifier or '('
Missing '#end'
#import "locationManager.h"
#implementation locationManager
#synthesize locationManager;
#synthesize fastView;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self; // send loc updates to myself
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
NSLog(#"Location: %#", newLocation description);
{
self.currentLocation = newLocation;
BOOL newLocationIsValid = [self isValidLocation:newLocation witholdLocation:oldLocation];
if(newLocationIsValid && oldLocation)
{
int distance = [newLocation distanceFromLocation:oldLocation];
if(distance >2 && distance<10)
{
[self.fastView setText:[NSString stringWithFormat:#"%i meters ", distance]];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)errort
{
NSLog(#"Error: %#", [error description]);
}
#end
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog (#"%s", __func__);
}
main.m
-(void)userDidLoagin
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)dealloc
{
[userMap release];
[_Speed release];
[viewSpeed release];
[_fastView release];
[super dealloc];
}
- (void)viewDidUnload
{
[userMap release];
userMap = nil;
[self setSpeed:nil];
[self setViewSpeed:nil];
[self setFastView:nil];
[super viewDidUnload];
}
Whoah. You need to take two steps back and review the basic architecture of iOS applications.
If the code you claim to be in main.m really is in main.m, then your app is not structured correctly at all. In fact, in just about all iOS applications, you should never touch the main.m file at all. And those are obviously instance method implementations which means they should be in a class's #implementation.
Change this:
NSLog(#"Location: %#", newLocation description);
{
To this:
{
NSLog(#"Location: %#", newLocation);
(note I moved it to after the { and removed descirption).
That will fix that error you're getting.
Looks to me like viewSpeed isn't a property, because it is not synthesized and is not prefaced with self. or _ when it is used in dealloc. Therefore the method you are trying to call does not exist. Change that line to
viewSpeed = nil;
And it should fix your problem.
EDIT: Didn't see that viewSpeed was also undeclared. You need to declare it as an ivar or property. With that said, in the code you have posted you don't seem to use it anywhere, so why bother releasing it and setting it to nil? Your #end also seems to be misplaced, it is above the "locationManager:" method.

can't get location on iOS - doesn't call delegate methods

i have a problem with the locationManager under iOS 6.
-(void) getLocationTest {
// Create a location manager instance to determine if location services are enabled. This manager instance will be
// immediately released afterwards.
manager = [[CLLocationManager alloc] init];
if (![manager locationServicesEnabled]) {
UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:#"Location Services Disabled" message:#"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[servicesDisabledAlert show];
//[servicesDisabledAlert release];
}
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
manager.distanceFilter = 500;
[manager startUpdatingLocation];
//[manager release];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
double testDe = 2.434;
testDe = testDe * 2;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations objectAtIndex:0];
double locDouble = location.coordinate.latitude;
NSString* locName = [[NSString alloc] initWithFormat:#"Hello, %f!", locDouble];
//[locations lastObject];
//NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
double testD = 2.434;
testD = testD * 2;
}
i have breakpoints in all the delegate methods, but none of them is being called.
Does someone know what i'm doing wrong? or how i can find out where the error is?
i would be grateful for every answer!
thanks!
Are you testing this on a device or in the simulator? In the simulator you have to manually set some location from the simulator app menu. It's in Debug/Location/.

Resources