点击按钮时获取用户位置

Get user location when tap a Button

在我的应用程序中有一个用于将记录添加到数据库的按钮。每次用户点击该按钮时,他都会向数据库添加一条记录。该记录的一部分应该是用户点击按钮时的位置。

因此,在我的代码中,当点击按钮时,我会调用一个跟踪用户位置的方法。问题是 iPhone 无法立即找到用户的位置,因此保存的记录没有坐标(如果我在大约 10 秒后创建另一条记录,一切正常)。

有没有办法只在用户按下按钮时跟踪用户并在可用时添加坐标?

@property(nonatomic,strong) CLLocationManager *locationManager;

在 ViewDidLoad 中

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
    [self.locationManager requestAlwaysAuthorization];
}

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
    [self.locationManager requestWhenInUseAuthorization];
}

然后

-(IBAction)button_Clicked:(id)sender
{
    [self.locationManager startUpdatingLocation];
}


#pragma mark - Location Manager delegate
- (void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations firstObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
}