在"拉取刷新"中完成位置提取?



>我已经在我的应用程序中实现了拉取以刷新,当拉取时启动位置管理器以修复用户位置,然后显示显示该位置的模式视图控制器。

我遇到的问题是,在获取用户位置之前,模态视图控制器正在呈现,导致空白地图再持续几秒钟,直到获取和更新为止。

我有一个保存用户当前位置的属性。是否可以"保持"直到该属性不为零(即已建立位置)在拉取刷新调用"showMap"之前,也许如果在设定的时间后无法找到用户,它只会显示错误?我尝试使用"while"循环来不断检查当前位置属性,但这似乎不是正确的做法,无论如何都不起作用。

这是我在viewDidLoad中设置的刷新代码的拉取:

__typeof (&*self) __weak weakSelf = self;
[self.scrollView addPullToRefreshWithActionHandler:^ {
    int64_t delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [weakSelf showMap];
    });
}];

使用拉取刷新时,它会调用以下方法:

- (void)showMap
{
    [self.locationManager updateCurrentLocation];
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(finishRefresh) userInfo:nil repeats:NO];
}
- (void)finishRefresh
{
    [self.scrollView.pullToRefreshController didFinishRefresh];
    [self performSegueWithIdentifier:@"showMap" sender:self];
}

抽象

为了避免过早显示映射,您实际上应该等待异步更新操作,并且这样做的最干净的模式将是委派。这是一个不错的Apple Doc,关于它在Cocoa/Cocoa Touch中的应用程序。

然后它将大致像这样工作:

  1. 下拉刷新触发器位置更新。
  2. 位置更新完成后,locationManager会通知您的控制器,控制器会显示地图。

如何做到

我不知道您的位置管理器类的界面,但如果它是CLLocationManager,则可以通过这种方式完成。

CLLocationManager 有一个委托属性。您的视图控制器应:

  1. 符合 CLLocationManagerDelegate 协议
  2. 将自己添加为locationManager的代理人
  3. 实现locationManager:didUpdateLocations:方法 — 当位置数据到达并可供使用时,将调用该方法。

此方法的实现应大致如下所示:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
{
    /*
     *  shouldShowMap — BOOL property of View Controller, actually optional 
     *  but allowing to filter out handling of unwanted location updates 
     *  so they will not trigger map segue every time
     */
    if (self.shouldShowMap) {
        [self performSegueWithIdentifier:@"showMap" sender:self];
        self.shouldShowMap = NO; 
    }
    // stop updating location — you need only one update, not a stream of consecutive updates
    [self.locationManager stopUpdatingLocation];
}

下拉刷新处理程序应如下所示:

__typeof (&*self) __weak weakSelf = self;
[self.scrollView addPullToRefreshWithActionHandler:^ {
    self.shouldShowMap = YES;
    [weakSelf.locationManager startUpdatingLocation];
}];

希望它有所帮助。学习的最好方法(在大多数情况下)是看看东西是如何在系统框架中实现的。朝这个方向思考,你一定会想出一个解决方案:)

如果您需要澄清,请随时询问,我可能解释得不够清楚。

最新更新