CloudKit - CKRecord returning nil

Not sure what I am doing wrong here, but my "record" variable keeps returning "nil".

When I run the savetoCloud() function, it crashes because record is "nil" (when it should have the data to be uploaded to CloudKit instead).

Help please.

I have this in a .swift file:

import Foundation
import CloudKit

public class dbData: NSObject{

    var record: CKRecord?


    var lightDB: Bool?{
        didSet{
            record!["Light"] = lightDB
        }
    }


    init(record: CKRecord){
        self.record = record
        self.lightDB = self.record!["Light"] as? Bool
    }

    convenience init(light: Bool) {
        self.init(record: CKRecord(recordType: "Location", recordID: CKRecord.ID(recordName: UUID().uuidString)))
        self.lightDB = light
        }
}

And then this on the main View Controller:


import UIKit
import CloudKit

class MapViewController: UIViewController {


    let publicDatabase = CKContainer(identifier: "iCloud.XXXX").database(with: .public)

    var dbdata: dbData?


    @IBOutlet weak var lightSW: UISwitch!


    override func viewDidLoad() {
        super.viewDidLoad()

    public func savetoCloud(){

        let light = lightSW.isOn
        let record = self.dbdata?.record
        record!["Light"] = light
        self.dbdata?.record = record

        publicDatabase.save(record!) { (record, error) in
            if let error = error{
                print("Error\(error.localizedDescription)")
                return
        }
        print("Record saved: \(record?.recordID.recordName ?? "")")

        }

}


Answered by leo008 in 711424022

Problem was the injection of the dependency.

Moving the code from the separate .Swift file to the main ViewController solved it.

Accepted Answer

Problem was the injection of the dependency.

Moving the code from the separate .Swift file to the main ViewController solved it.

CloudKit - CKRecord returning nil
 
 
Q