0

I'm getting my current location with no problems. However when I try to calculate my distance, my currentLoc has a 0 value. What am I missing to carry that currentLoc over so it's not 0?

My NSLog in LocationManager gives the correct value.

#import "AuthorViewController.h"
#import "Author.h"
#import <sqlite3.h>


@implementation AuthorViewController
@synthesize theauthors;
@synthesize currentLoc;

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    currentLoc = newLocation;

    if (newLocation.horizontalAccuracy <= 100.0f) {
        [locMgr stopUpdatingLocation];
}
    NSLog(@"Lat: %f, Long: %f", currentLoc.coordinate.latitude, currentLoc.coordinate.longitude);

    [self barList];
    [self.tableView reloadData];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *msg = [[NSString alloc]initWithString:@"Error obtaining location"];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Done" otherButtonTitles:nil];
    [alert show];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    locMgr = [[CLLocationManager alloc] init];
    locMgr.delegate = self;
    [locMgr startUpdatingLocation];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [self.theauthors count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
    int rowCount = indexPath.row;

    Author *author = [self.theauthors objectAtIndex:rowCount];

    cell.textLabel.text = author.barName;

    if (currentLoc == nil) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"?"];
    }else
    {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%.02f km", author.cachedDist];
    }


    return cell;
}

It's in my Array where my NSLog shows 0 value for the current locations lat and long.

-(NSMutableArray *) barList{
    theauthors = [[NSMutableArray alloc] init];
    @try {
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"TulsaBars.sqlite"];
        BOOL success = [fileMgr fileExistsAtPath:dbPath];
    if(!success)
    {
        NSLog(@"Cannot locate database file '%@'.", dbPath);
    }
    if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
    {
        NSLog(@"An error has occured: %@", sqlite3_errmsg(db));

    }


    const char *sql = "SELECT * FROM  TulsaBars";
    sqlite3_stmt *sqlStatement;
    if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
    {
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
    }else{

        while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
            Author * author = [[Author alloc] init];
            author.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
            author.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
            author.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
            author.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
            author.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];


            if (currentLoc == nil) {
                NSLog(@"current location is nil %@", currentLoc);
            }

            CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[author.barLat doubleValue] longitude:[author.barLong doubleValue]];
            CLLocationDistance distancekm = [currentLoc distanceFromLocation: barLocation]/1000;
            NSString *distanceString = [[NSString alloc] initWithFormat: @"%f", distancekm];
            author.cachedDist = distanceString;

            [theauthors addObject:author];

            NSLog(@"Lat3: %@, Long3: %@, CurLocLat: %f, CurLocLong: %f, BarLoc: %@, DistKM: %@", author.barLat, author.barLong, currentLoc.coordinate.latitude, currentLoc.coordinate.longitude, barLocation, distancekm);

        }
    }
    sqlite3_finalize(sqlStatement);
}
@catch (NSException *exception) {
    NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
}
@finally {
    sqlite3_close(db);

    return theauthors;
}
}
end
  • -1. I don't see a connection. You seem to be getting data from the database but where are you inserting? I don't see any insertion being done in the database. Also, you are printing at 2 different places for latitude and longitude. One place is a property and the other is from the sql database. How can you expect them to be same? You have NOT even mentioned the filenames. Bad bad question! – S.P. Jun 29 '12 at 16:49
  • Excuse me, how is this a bad question. If I new all the answers I would not be asking questions. I'm printing in two locations to see what is going on. I'm trying to use the currentLoc to calculate the distance and insert into my Array with [theAuthors addObject:author]; I'm not trying to insert anything into the DB. I'm just trying to use the DB to update the Array and display in my TableView. Maybe I do need to insert the distance into the DB and then pull it all back out, but I didn't think I had to do it that way. Once again thats why I'm asking the question. – user1454340 Jun 29 '12 at 17:18
  • You need to provide all the details. You have NOT shown us where you have inserted in the database. you have NOT shown us how the 2 portions of the code are connected. You have "I'm getting my current location with no problems. However when I try to calculate my distance, my currentLoc has a 0 value. " how is this even a right question? you have 2 different settings for printing... your point of reference is incorrect. – S.P. Jun 29 '12 at 17:28
  • The DB is an sql DB preloaded. My first code shows where I'm getting my current location and printing to make sure it works. My second code is showing where I pull the info from that preloaded sql DB and add it to my "theauthors" Array. I'm printing here again to see if my currentLoc is still populated with the correct location as I perform the calculation. I have not shown where I inserted into the DB, because I'm not. The main question is why is my currentLoc losing its location data from the top code to the bottom code. I have updated the full code. – user1454340 Jun 29 '12 at 18:33
  • In `didUpdateToLocation`, try changing `currentLoc = newLocation;` to `self.currentLoc = newLocation;`. –  Jun 29 '12 at 19:28
  • Anna, I tried that earlier as well and it didn't change anything. I still think it has to do with the order in which I'm doing things. I feel like my Array is being loaded before my currentLoc is being set with the current location. – user1454340 Jun 29 '12 at 19:54
  • Is barList getting called before didUpdateToLocation? If you must have the location before running barList, change your code accordingly. Otherwise, check if currentLoc is nil before trying to get distance just like you check in cellForRowAtIndexPath. –  Jun 29 '12 at 20:11
  • barList is in viewDidLoad and didUpdateToLocation is in viewWillAppear. I think I remember reading that viewWillAppear comes before viewDidLoad, so that would make sense to switch those, but no change. I tried the if statement and it confirms that currentLoc is null. – user1454340 Jun 29 '12 at 21:16
  • I apologize barList loading last makes sense. Switched back, based on viewWillAppear happening first. – user1454340 Jun 29 '12 at 21:23
  • To make absolutely sure that you have a current location when barList is called is to call barList in didUpdateToLocation itself (not in viewDidLoad or viewWillAppear) probably before the reloadData. –  Jun 29 '12 at 21:51
  • I believe that fixed my empty currentLoc and my if statement seems to be working. I did a break in the code and I can see my distanceString has a value that is correct. However I'm still getting 0.00 km displayed in my Table. You have answered my original problem, but let me know if you have any ideas. Thanks – user1454340 Jun 29 '12 at 22:25

0 Answers0