【问题标题】:Background task or updating location in iphoneiphone中的后台任务或更新位置
【发布时间】:2012-06-09 08:03:15
【问题描述】:

我想创建一个应用程序,每 xx 分钟将用户位置更新到我的远程服务器,即使应用程序在后台 我试过下面的代码

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    i=0;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
        [app endBackgroundTask:bgTask]; 
        bgTask = UIBackgroundTaskInvalid;
    }];
    bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundTask:) userInfo:nil repeats:YES];

}

-(void)backgroundTask:(NSTimer*)timer{

    i++;
    NSLog(@"%s  %d",__func__,i);
}

但定时器回调在大约 10 分钟后停止 如何制作一个不断更新服务器当前位置的应用程序

【问题讨论】:

    标签: ios location cllocationmanager background-process


    【解决方案1】:

    您可能在应用的 Info.plist 文件中缺少 Background Modes 键:

    <key>UIBackgroundModes</key>
        <array>
                <string>location</string>
        </array>
    

    这可让您的应用在后台访问定位服务。

    但是,这种事情已经被问过很多次了,所以也请浏览一下other stack overflow questions以获取更多信息。

    Here's another one 阅读。

    【讨论】:

      【解决方案2】:

      您只能在后台更新 3 分钟。将 Capabilities-> BackgroundFetch 设置为多于或等于 3 个字段 使用以下代码

      调用这个 didenterbackground 或 foreground

      var time = 120
      func applicationDidEnterBackground(_ application: UIApplication)
          {
              time = 180
              self.doBackgroundTask()
          }
      
       var timerBack  = Timer()
          func doBackgroundTask() {
      
              DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
                  self.beginBackgroundUpdateTask()
      
      
                  self.timerBack = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.displayAlert), userInfo: nil, repeats: true)
                  RunLoop.current.add(self.timerBack, forMode: RunLoopMode.defaultRunLoopMode)
                  RunLoop.current.run()
      
                  self.endBackgroundUpdateTask()
              }
          }
          var backgroundUpdateTask: UIBackgroundTaskIdentifier!
      
          func beginBackgroundUpdateTask() {
              self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
                  self.endBackgroundUpdateTask()
              })
          }
      
          func endBackgroundUpdateTask() {
              UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
              self.backgroundUpdateTask = UIBackgroundTaskInvalid
          }
      

      //随心所欲

      func displayAlert{
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-12
        • 1970-01-01
        相关资源
        最近更新 更多