我想检索当前位置并通过POST请求将其发送到服务器。
我使用mapView.userLocation.location.coordinate
但它不起作用,并且对于lat而言始终为0.0,对于lng则为0.0。
这是我的控制器的.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface CustomViewController : UIViewController
<MKMapViewDelegate>
@property NSMutableArray * shops;
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *loadingIcon;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
和这个.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_mapView.showsUserLocation = YES;
_mapView.delegate = self;
_shops = [[NSMutableArray alloc] init];
[_loadingIcon startAnimating];
CLLocationCoordinate2D coordinate;
coordinate = _mapView.userLocation.location.coordinate;
NSNumber *lat = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *lng = [NSNumber numberWithDouble:coordinate.longitude];
//here the post method
NSArray *keys = [NSArray arrayWithObjects:@"lat", @"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:lat,lng, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
.....
NSLog(@"posizione %@", jsonString);
}
Log中的我总是有0.0 0.0。
我也有这种方法:
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation: (MKUserLocation *)userLocation
{
[_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
userLocation.title = @"Posizione attuale";
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000);
[_mapView setRegion:region animated:YES];
NSLog(@"lat %f", (double)userLocation.location.coordinate.latitude);
}
在这种情况下,日志显示当前位置。 有人有想法吗?