Search code examples
swift3cloudkit

I cant save records in CloudKit, why?


I am trying to run an app that besides other things will load school classes into a table view. The code looks like this:

import UIKit
import CloudKit

class AddPostVC: UIViewController {

    @IBOutlet weak var postText: UITextView!
    let database = DatabaseController()

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

        view.addGestureRecognizer(tap)
    }

    //Calls this function when the tap is recognized.
    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }

    @IBAction func postButtonPressed() {
        let newPost = Post()

        newPost.text = postText.text
        newPost.user = CKReference(recordID: CKRecordID(recordName: UserDefaults.standard.string(forKey: "userRecordID")!), action: CKReferenceAction.none)

        newPost.save() { _, error in
            if error == nil {
                DispatchQueue.main.async {
                    self.navigationController?.popViewController(animated: true)

                    self.dismiss(animated: true, completion: nil)
                }
            } else {
                if !self.database.networkCheck() {
                    DispatchQueue.main.async {
                        self.displayErrorMessage(message: "It seems that there is no internet connection, try again")
                    }
                } else {
                    DispatchQueue.main.async {
                        self.displayErrorMessage(message: error.debugDescription + ". Contact Apple or us for help")
                    }
                }
            }

        }

    }

    func displayErrorMessage(message:String) {

        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)

        let dismissAction = UIAlertAction(title: "Dismiss", style: .default, handler: nil)

        alert.addAction(dismissAction)

        self.present(alert, animated: true)

    }

}

When the code is run it returns me an error:

[LogFacilityCK] Got a connection error for operation 69CB31B15036D50D: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.cloudd" UserInfo={NSDebugDescription=connection to service named com.apple.cloudd}

Does anyone know how to fix this problem? I couln't find any solutiosn on the internet yet so far.


Solution

  • The very important thing that caused this problem was saving a record of a type other than CKRecord with cloudKit. In my case the function save() in class Post() tried to save itself which was a subclass of CKRecord rather than pure CKRecord.

    Another thing that, stopped it from working is something that is described and answered here.