后台任务或更新iPhone中的位置



我想制作一个应用程序,每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 分钟后停止如何使应用程序不断更新我的服务器当前位置

你可能缺少应用的 Info.plist 文件中的"后台模式"键:

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

这样,您的应用就可以在后台访问定位服务。

但是,这种事情已经被问了很多次了,所以也做一些浏览其他堆栈溢出问题以获取更多信息。

这是另一个要阅读的内容。

您只能在后台更新 3 分钟。为大于或等于 3 个字段设置功能> BackgroundFetch 打开使用以下代码

称之为 didenterbackground或前景

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{

}

最新更新