CloudKit - 如何在后台修改记录

CloudKit - How to modify the record in the background

我的应用程序现在可以在后台使用位置更新。 那么,是否可以在用户移动时在后台修改记录呢?

代码:

@IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager!


override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self

    locationManager = CLLocationManager()
    locationManager.delegate = self

    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    locationManager.allowsBackgroundLocationUpdates = true

}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
    recordLocation()   
}


func recordLocation() {

    let publicDatabase = CKContainer.default().publicCloudDatabase

    let predicate = NSPredicate(format: "accountID == %@", argumentArray: [myID!])
    let query = CKQuery(recordType: "Accounts", predicate: predicate)

    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {(records, error) in

        if let error = error {
            print("error1: \(error)")
            return
        }

        for record in records! {

            record["currentLocation"] = self.mapView.userLocation.location

            publicDatabase.save(record, completionHandler: {(record, error) in

                if let error = error {
                    print("error2: \(error)")
                    return
                }
                print("success!")
            })
        }
    })
}

image - Capability of Background Modes

顺便说一句,只要我的应用程序在前台运行,一切都很好。

版本

Xcode 12.2 / Swift 4.2

总结

请问如何在后台修改记录?首先,我们可以这样做吗?

谢谢。

我理解错了。我已经在后台记录了我的位置,但是没有获取到最新的。

record["currentLocation"] = self.mapView.userLocation.location

通过使用此代码,我记录了 我查看 MKMapView 的最后一刻的位置。

也就是说,后台录制的问题,从一开始就解决了

我改写成如下代码:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {

    if let location = locations.first {
        recordLocation(currentLocation: location)
    }

}


func recordLocation(currentLocation: CLLocation) {

    let publicDatabase = CKContainer.default().publicCloudDatabase

    let predicate = NSPredicate(format: "accountID == %@", argumentArray: [myID!])
    let query = CKQuery(recordType: "Accounts", predicate: predicate)

    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {(records, error) in

        if let error = error {
            print("error1: \(error)")
            return
        }

        for record in records! {

            record["currentLocation"] = currentLocation as CLLocation

            publicDatabase.save(record, completionHandler: {(record, error) in

                if let error = error {
                    print("error2: \(error)")
                    return
                }
                print("success!: \(String(describing: currentLocation))")
            })
        }
    })

}