【问题标题】:How can I stop a background service in iOS after a certain period of time一段时间后如何在iOS中停止后台服务
【发布时间】:2014-08-22 15:20:12
【问题描述】:

我正在使用这个插件开发一个 Cordova 项目:Cordova Plugin Background Geolocation 在我的应用处于后台时获取 GPS 更新。

我想在应用程序在后台运行 3 分钟后停止获取更新。 我没有 Objective-C 技能来修改插件来实现这一点。

我想有一种方法可以在 Objective-C 上使用计时器在 3 分钟后停止服务。

谁能帮我解决这个问题?

更新

插件有一个stop方法here

【问题讨论】:

    标签: ios object cordova cordova-plugins


    【解决方案1】:

    试试这个解决方案,这里你需要创建 NSTimer 的全局对象并检查 NSTimer 对象是否有效

    -(void)applicationDidEnterBackground:(UIApplication *)application {
    
    if ([objTimer isValid]) {
        [objTimer invalidate];
    }else{
        objTimer = [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(stopGPS:)  userInfo:nil repeats:NO];
    }
    objTimer = nil;}
    
    
    
    - (void)stopGPS:(NSTimer *)timer {
    // code for stoping GPS service.}
    

    【讨论】:

      【解决方案2】:

      您必须修改您的 .plist 文件以表明您将在应用程序进入后台后运行任务...话虽如此,您想要的可能看起来像这样(全部在 AppDelegate 中)

      - (void)applicationDidEnterBackground:(UIApplication *)application {
          NSLog(@"Entered background");
          [self monitorLocation];
      }
      
      - (void)monitorLocation
      {
      [NSTimer scheduledTimerWithTimeInterval:180 //That's in seconds
          target:self
          selector:@selector(stopMonitoring)
          userInfo:nil
          repeats:NO];
          //Do whatever monitoring here
      
      }
      
      - (void)stopMonitoring
      {
          //Stop monitoring location
      }
      
       - (void)applicationWillEnterForeground:(UIApplication *)application {
          NSLog(@"app will enter foreground");
          [self stopMonitoring];
      }
      

      【讨论】:

      • 好的,但是如何调用AppDelegate上的插件方法呢?
      • 和你在其他地方做的完全一样。也就是说,我假设您创建了一个 CDVBackgroundGeoLocation 实例,然后在其上调用了适当的方法。
      • 我使用的是 Cordova,所以它创建了一个 JavaScript 接口来访问插件方法。
      • @user1840001 NSTimer 会在每次应用程序进入后台的 180 秒后调用 stopMonitor 方法,所以想想当用户在 180 秒之前进入后台超过一个时会发生什么。
      • @Arvind 我已经修改了我的答案以处理该用户行为
      猜你喜欢
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多