ios - 我怎么知道我的应用程序在后台运行?

标签 ios swift cocoa-touch cllocation background-mode

我写了这个程序,当应用程序显示在屏幕上时它可以工作

如果应用程序在后台,它会停止打印纬度,当我恢复应用程序时,它会再次开始打印。

我已经在 xcode 中启用了后台模式,并且还检查了位置更新,为什么我的应用程序仍然没有在后台运行?

如果应用程序正在运行,只是print函数在后台不起作用,我怎么知道应用程序正在运行?

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()

如果它仍然不起作用,请通过在委托(delegate)函数中添加打印语句来确保您的位置管理器完全触发更新。

二、如何在后台打印东西:

我最喜欢的方式是在 UserDefaults 中记录内容,因为这些内容在应用重启后仍然存在。例如,我会将打印语句设置为 log 键的值。重新启动后,我将从 log 键中读取 UserDefaults 的内容。

关于ios - 我怎么知道我的应用程序在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839247/

相关文章:

ios - 无法将类型 "Any"的值分配给类型 "String?"Swift 3 (iOS)

ios - 从 NavigationController 到 TabBarController

cocoa - 以时间戳格式获取当前 NSDate

iphone - 将数组保存到包含自定义对象 iPhone 的 Plist 文件

ios - 如何从 Kinvey 获取自定义属性

Swift 5 结果类型

ios - NSURL(字符串 : fullURL) returns error

ios - 选择 UITableViewCell 时标签背景颜色发生变化

ios - 如何在 Swift 中传递类型为 "Sequence"的 "T"作为参数?

ios - 在 Xcode 6 中对 super View 的边缘进行水平布局时,如何摆脱 -16?