-1

I have a function that saves Data to iCloud

func save(data: Data) -> Bool {
    cloudRecord["example"] = data as CKRecordValue
    var success = false
    CKContainer.default().privateCloudDatabase.save(self.cloudRecord) { (record, error) in
        if let error = error {
            print(error.localizedDescription)
        } else {
            print(1)
            success = true
        }
    }

    print(2)
    return success
}

The problem is, that the print(2) is executed before the print(1) so the function always returns success which is false, because it is returned before having the chance of changing.

How do I get this code to return the value after the success has been set?

Is there an elegant way to achieve this?

swift-lynx
  • 3,219
  • 3
  • 26
  • 45

1 Answers1

2

Instead of returning bool from the method add an argument with a closure like this. When you receive a response from privateCloudDatabase.save call the closure with bool value.

func save(data: Data, completion:(Bool)->Void) {
    cloudRecord["notes"] = data as CKRecordValue
    var success = false
    CKContainer.default().privateCloudDatabase.save(self.cloudRecord) { (record, error) in
        if let error = error {
            print(error.localizedDescription)
            completion(false)
        } else {
            print(1)
            completion(true)
        }
    }
}

Change your function calling as follows

save(data: data) { result in
    print("result is \(result)")
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70