Reputation: 11
I am trying to get the users Lat and Long from GPS data on iphone.
here is my code:
//
// SendLocView.m
// AMR App
//
// Created by Fletcher on 07/04/2016.
// Copyright © 2016 LaserCamel Programing. All rights reserved.
//
#import "SendLocView.h"
@import CoreLocation;
@interface SendLocView ()
@end
@implementation SendLocView
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)location_send:(id)sender {
[self.locationManager requestAlwaysAuthorization];
NSString *Globalusername = @"1111";
float latitude = locationManager.location.coordinate.latitude;
float longitude = locationManager.location.coordinate.longitude;
NSLog(@"Value of username is %@", Globalusername);
NSLog(@"Value of latitude is %f", latitude);
NSLog(@"Value of longitude is %f", longitude);
NSString *post =[[NSString alloc] initWithFormat:@"lat=%f&long=%f&username=%@",latitude,longitude,Globalusername];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"https://www.webaddress.org.uk/mobile/jsontracking.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(@"%@", [locations lastObject]);
}
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}
}
@end
My Current output from NSLog(@"Value of latitude is %f", latitude); is
2016-04-08 21:54:29.170 AMR App[1394:467604] Value of latitude is 0.000000
But the NSLog(@"%@", [locations lastObject]); output is
2016-04-08 21:55:38.186 AMR App[1394:467604] <+51.50483880,-3.16954134> +/- 65.00m (speed -1.00 mps / course -1.00) @ 08/04/2016, 21:55:38 British Summer Time
any help as to why this is happening would be great
Upvotes: 1
Views: 80
Reputation: 1972
The documentation for CLLocationManager
states that it resolves location information asynchronously, meaning that you cannot make any assumptions about what might be available to you at any given time.
The AppleDoc discussion for -startUpdatingLocation
explains why the values are nil in the first log message:
This method returns immediately. Calling this method causes the location manager to obtain an initial location fix (which may take several seconds) and notify your delegate by calling its locationManager:didUpdateLocations: method.
So, you should not expect to have any valid location information until the -locationManager:didUpdateLocations:
delegate method is called. Based on the timestamps in your log message, it's clear that the location took about 1 second longer to resolve, which is actually in line with the documented timeframe from Apple engineering.
Note: the docs also suggest implementing the failure method...
In addition to your delegate object implementing the locationManager:didUpdateLocations: method, it should also implement the locationManager:didFailWithError: method to respond to potential errors.
Upvotes: 1