我正在尝试构建一个 iOS,我可以在其中每 x 秒更新一次我的位置并发送通知以更新 UI。 我得到了我的位置,但更新是随机的。任何想法如何添加间隔?
这是我的代码:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
[self sendNotification :@"long"
:[NSString stringWithFormat:@"%.8f",location.coordinate.longitude]];
[self sendNotification :@"lat"
:[NSString stringWithFormat:@"%.8f",location.coordinate.latitude]];
}
最佳答案
试试这个:
在.h文件中声明
@property (strong, nonatomic) NSDate *lastTimestamp;
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *mostRecentLocation = locations.lastObject;
NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));
NSDate *now = [NSDate date];
NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;
if (!self.lastTimestamp || interval >= 5 * 60)
{
self.lastTimestamp = now;
NSLog(@"update your UI");
}
}
关于ios - iOS 每 x 秒更新一次位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537723/