Ios 我如何知道我的应用程序在后台工作?
我写了这个程序,它是工作时,应用程序显示在屏幕上 如果应用程序在后台,它会停止打印纬度,当我恢复应用程序时,它会再次开始打印 我已经在xcode中启用了后台模式,还检查了位置更新,为什么我的应用程序还没有在后台运行 如果应用程序正在运行,只是Ios 我如何知道我的应用程序在后台工作?,ios,swift,cocoa-touch,cllocation,background-mode,Ios,Swift,Cocoa Touch,Cllocation,Background Mode,我写了这个程序,它是工作时,应用程序显示在屏幕上 如果应用程序在后台,它会停止打印纬度,当我恢复应用程序时,它会再次开始打印 我已经在xcode中启用了后台模式,还检查了位置更新,为什么我的应用程序还没有在后台运行 如果应用程序正在运行,只是打印功能在后台不起作用,我如何知道应用程序正在运行 class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager: CLLoc
打印
功能在后台不起作用,我如何知道应用程序正在运行
class ViewController: UIViewController,
CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation])
{
let latestLocation: CLLocation = locations[locations.count - 1]
print(latestLocation.coordinate.latitude)
}
override func viewDidLoad() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
startLocation = nil
}
}
首先,你的问题:
locationManager.requestWhenInUseAuthorization()
这要求您的位置管理器仅在您的应用位于前台时更新其位置。您必须将此更改为:
locationManager.requestAlwaysAuthorization()
如果仍然不起作用,请确保您的位置管理器通过在委托函数中添加print语句来触发更新
第二,如何在后台打印内容:
locationManager.requestWhenInUseAuthorization()
我最喜欢的方法是在UserDefaults中记录这些内容,因为这些内容会在应用程序重启时保持不变。例如,我将打印语句设置为
log
键的值。重新启动后,我将从日志
键读取UserDefaults的内容。如果你的应用程序在后台使用位置)。除了在Info.plist
中设置后台模式功能外,你还必须将allowsBackgroundLocationUpdates
设置为是。否则,位置更新仅在前台交付
如果首先调用CLLocationManager
startUpdatingLocation
方法,并在projectname-Info.plist文件中添加所需的Background Modes
->应用程序注册位置更新。您只请求了“使用时”权限,因此您的应用程序在后台时将无法获得位置。因此,您需要请求“始终”权限现在我使用requestAlwaysAuthorization()
,它仍然没有在后台运行。您是否将所需的用法字符串添加到info.plist?你是否被提升为“永远”许可?当您的应用程序挂起时,此视图控制器是否处于活动状态?如果我将allowsBackgroundLocationUpdates
设置为true,则此视图控制器有效。但是不显示蓝色状态栏的是什么意思?你是说如果我设置allowsBackgroundLocationUpdates
,蓝色条可以隐藏吗?但是现在蓝色的条显示出来了。