Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone app - how to get the current location only once and store that to be used in another function?

I've been working on this for the past 2 weeks - i have an app that shows a legible route on a map that goes from a start point to a destination point. the destination point is the users address (as defined/entered by the user in the settings menu we have set up) and if i hard code the start point, the map, route and application all work fine. once i try to implement anything that involves using the cllocation or cllocationmanager, it crashes and gives me a thread error (there are 3).

Here is the current view controller header & implementation file for this:

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "MapView.h"
#import "Place.h"
#import <CoreLocation/CoreLocation.h>


@interface HomeMapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{

    IBOutlet UILabel *HomeAddressLabel;

}

@property (weak, nonatomic) IBOutlet MKMapView *MapView;
@property (strong, nonatomic) IBOutlet CLLocationManager *location;
@end

implementation file:

#import "HomeMapViewController.h"



@interface HomeMapViewController ()

@end


@implementation HomeMapViewController
@synthesize MapView;
@synthesize location;
double lat = 37.331706;
double lon = -122.030598;
- (id)initWithNibNameNSString *)nibNameOrNil bundleNSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    //Retrieve saved address before view loads
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *HomeAddress = [defaults objectForKey:@"HomeAddress"];
    NSString *HomeCity = [defaults objectForKey:@"HomeCity"];
    NSString *HomeProvince = [defaults objectForKey:@"HomeProvince"];
    NSString *HomeZip = [defaults objectForKey:@"HomeZip"];
    NSString *HomeCountry = [defaults objectForKey:@"HomeCountry"];
    NSString *HomeAddressFull = [NSString stringWithFormat:@"%@, %@, %@, %@, %@", HomeAddress, HomeCity, HomeProvince, HomeZip, HomeCountry];

    //Set address label to saved address values
    HomeAddressLabel.text = HomeAddressFull;



    //Map Route Code

        MapView* mapView = [[MapView alloc] initWithFrame:
                        CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        //Shows user location

    [self.MapView setShowsUserLocation:YES];
    //set which mapview to show
        [self.MapView addSubview:mapView];

    self.location = [[CLLocationManager alloc]init];
    location.delegate = self;
    location.desiredAccuracy=kCLLocationAccuracyBest;
    location.distanceFilter = kCLLocationAccuracyBestForNavigation;//constant update of device location
    [location startUpdatingLocation];


    Place* start = [[Place alloc] init];
    start.name = @"Start Location";
    start.description = @"You started here.";
    //^should be changed to current location once that is implemented
    //start.latitude =    37.331706;
    //start.longitude = -122.030598;
    start.latitude = lat;
    start.longitude = lon;
    //start.latitude = location.location.coordinate.latitude;
    //start.longitude = location.location.coordinate.longitude;


    //Geocoder Code
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:HomeAddressFull completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", [error localizedDescription]);
            return;
        }

        for (id object in placemarks) {
            CLPlacemark *placemark = object;



            Place* destination = [[Place alloc] init];
            destination.name = @"Destination";
            destination.description = [NSString stringWithFormat:@"%@, %@, %@", HomeAddress, HomeCity, HomeProvince];
            destination.latitude = placemark.location.coordinate.latitude;
            destination.longitude = placemark.location.coordinate.longitude;

            [mapView showRouteFrom:start toestination];
        }
    }];


    [super viewDidLoad];

}

- (void)locationManagerCLLocationManager *)manager didUpdateToLocationCLLocation *)newLocation fromLocationCLLocation *)oldLocation{
    [manager stopUpdatingLocation];

}



//************NEW METHOD
-(void)locationManagerCLLocationManager *)manager didFailWithErrorNSError *)error{
    NSString *msg = @"Error obtraining location:";
    UIAlertView *alert;
    alert = [[UIAlertView alloc]
             initWithTitle:@"Error"
             message:msg delegate:self
             cancelButtonTitle:@"OK"
             otherButtonTitles: nil];
    [alert show];

}

- (void)viewDidUnload
{
    [self setMapView:nil];
    HomeAddressLabel = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientationUIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


@end

I'd basically like to ask if anyone can help shed some light on how I might go about getting the users current location coordinates and storing them as the start.latitude and start.longitude values so the route shows a pathway from the users current location to their destination. the route is not supposed to update itself as the user moves, I would just like to have an annotation/placemark on the users current location and destination (as i do have) and then the blue point (aka the user) will be able to see themselves move along the route they are to take. I've tried all the suggestions on here - and some havent worked at all, some worked only once and then after that it failed to work again (even after resetting the simulator content!). some links are relevant but very outdated so the methods there don't work.

And here i was thinking getting the users current location coordinates would be the easier task of this function!

like image 419
Fee Avatar asked Nov 21 '12 10:11

Fee


People also ask

Can you make your iPhone location show somewhere else?

With your iPhone or iPad plugged in, select Toolbox at the top of the program, and then VirtualLocation from that screen. Select somewhere on the map, or use the search bar, to choose where you want to fake your location. Select Modify virtual location, and then select OK when you see the "succeeded" message.

How do I not show exact location on iPhone?

To stop sharing your location with all apps and services, for even a short period of time, go to Settings > Privacy > Location Services and turn off location sharing. This stops all apps on your device, such as Maps, from using your location.


1 Answers

.h file

#import <CoreLocation/CoreLocation.h>

@property (nonatomic,retain) CLLocationManager *locationManager;

.m file

- (NSString *)deviceLocation 
{
    NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
    return theLocation;
}

- (void)viewDidLoad
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.distanceFilter = kCLDistanceFilterNone; 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [self.locationManager startUpdatingLocation];
}
like image 184
Aitul Avatar answered Oct 13 '22 00:10

Aitul