简体   繁体   English

IOS didUpdateLocations 多次调用

[英]IOS didUpdateLocations called multi time

I'm using didUpdateLocation.我正在使用 didUpdateLocation。 Inside, I have called a webservices.在里面,我调用了一个网络服务。

And, I want to every 2 minutes, I will call webservices.而且,我想每 2 分钟调用一次网络服务。

But, didUpdateLocation update location multi time.但是, didUpdateLocation 多次更新位置。 So, I have to call webservices.所以,我必须调用网络服务。 This is not good.这是不好的。

How to I can call webservices every 2 minutes.如何我可以每 2 分钟调用一次网络服务。

Please help me!请帮我!

You have to trigger the call with something other than didUpdateLocation , because the frequency of that call is up to the user of the device, and not your code.您必须使用didUpdateLocation以外的其他内容触发调用,因为该调用的频率取决于设备的用户,而不是您的代码。 If you only need to call the web service if there has been a significant change in location, you can do as follows.如果您只需要在位置发生重大变化时调用 Web 服务,您可以执行以下操作。

  1. Save the location passed to didUpdateLocation .保存传递给didUpdateLocation的位置。
  2. Use a repeating NSTimer on a two minute interval.每隔两分钟使用一个重复的NSTimer
  3. Every time the timer fires, check the current location versus the location when the last request was made.每次计时器触发时,检查当前位置与上次请求时的位置。 If it exceeds the threshold, make the request.如果超过阈值,则提出请求。
  4. If the request is made, save the location for the next iteration.如果发出请求,则保存下一次迭代的位置。

An alternative algorithm:另一种算法:

  1. Make the web request.发出网络请求。 Remember the time.记住时间。
  2. When didUpdateLocation fires, check the last time you made the web request.didUpdateLocation触发时,检查您上次发出 Web 请求的时间。 If it was more than 2 minutes ago, make the request, else ignore the update.如果超过 2 分钟前,则发出请求,否则忽略更新。

You might need a bit of each, depending on your exact needs.根据您的具体需求,您可能需要每一种。 If the cadence for the request is most important, start with the first.如果请求的节奏最重要,请从第一个开始。 If the only important bit is that you don't call more frequently than every 2 minutes, but longer intervals are perfectly OK, go with the second.如果唯一重要的一点是你不会比每 2 分钟更频繁地打电话,但更长的时间间隔是完全可以的,那就选择第二个。

Use NSTimer.使用 NSTimer。

  NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                  target:self
                                                selector:@selector(handleTimer:)
                                                userInfo:nil repeats:YES];

Put this code in DidLoad Method and Add the below code in somewhere else.将此代码放在 DidLoad 方法中,并将以下代码添加到其他地方。

     - (void)handleTimer:(NSTimer*)theTimer {

       NSLog (@"Working");

     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM