获取用户在Cocoa-touch上的位置

时间:2016-04-08 20:55:06

标签: ios objective-c cocoa-touch

我正试图通过iphone上的GPS数据获取用户Lat和Long。

这是我的代码:

//
//  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

来自NSLog的我的当前输出(@“纬度值是%f”,纬度);是

2016-04-08 21:54:29.170 AMR App[1394:467604] Value of latitude is 0.000000

但NSLog(@“%@”,[locations lastObject]);输出

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

任何关于为什么会发生这种情况的帮助都会很棒

1 个答案:

答案 0 :(得分:1)

CLLocationManager的文档指出它以异步方式解析位置信息,这意味着您无法对任何给定时间可用的内容做出任何假设。

AppleDoc对-startUpdatingLocation的讨论解释了第一条日志消息中值为零的原因:

  

此方法立即返回。调用此方法会导致   位置管理器获取初始位置修复(可能需要   几秒钟)并通过调用它来通知你的代表   locationManager:didUpdateLocations:method。

因此,在调用-locationManager:didUpdateLocations:委托方法之前,您不应期望获得任何有效的位置信息。根据日志消息中的时间戳,很明显该位置需要花费大约1秒的时间来解决,这实际上与Apple工程中记录的时间范围一致。

注意:文档还建议实施失败方法......

  

除了你的委托对象实现了   locationManager:didUpdateLocations:方法,它也应该实现   locationManager:didFailWithError:响应潜力的方法   错误。