saveInBackground (Parse) throwing an error - ios

I am having an issue in the following swift code, using Parse-Server to save data online.
let xxDico = ["N8": "Eight", "N5": "Five"],
upLoadParseUnit = PFObject(className: "numberClass",
dictionary: xxDico)
print("xxDico : \(xxDico.count)")
upLoadParseUnit.saveInBackground {
(succeeded:Bool, error:Error?) in
if succeeded {
print("\(#function) succeeded!!")
} else {
if error?.localizedDescription == "NAME-USED" {
// A record previously existed with the same name.
print("\(#function) did not succeeded!!\nError: \(error?.localizedDescription)")
return
}
print("Error(1) in \(#function)\n" + (error?.localizedDescription)!)
}
}
And this is what I get in the debugging console:
xxDico : 2
Error(1) in executeUpLoad(_:)
The data couldn’t be read because it isn’t in the correct format.
This seems simple, but what am I doing wrong to get this error?
And what am I supposed to do?

Related

How to update a document in firebase firestore using swift?

when i run the following code i get this error.
['FIRESTORE INTERNAL ASSERTION FAILED: Invalid document reference. Document references must have an even number of segments, but User has 1']
func saveLabel(uid: String, label: String){
let userRef = db.collection("User").document(uid)
userRef.updateData(["label": label]) { (error) in
if error == nil {
print("updated")
}else{
print("not updated")
}
}
}
This error almost certainly means that uid is empty. You should log it to make sure.

Errors using PFUser.getCurrentUserInBackground()

I am using Parse and PFUser in a Swift iOS app, and find myself in a case where PFUser.current() does not do exactly what I want, due to synchronisation issues.
For that reason I am trying to use: PFUser.getCurrentUserInBackground().
I got started with the code below, inspired from what can be found here: https://github.com/BoltsFramework/Bolts-ObjC.
But this document probably being a bit outdated, it does not quite work.
let userCheckTask = PFUser.getCurrentUserInBackground()
userCheckTask.continueWith {
(task: BFTask!) -> BFTask<AnyObject> in
if task.isCancelled() { // Error-1.
// the save was cancelled.
} else if task.error != nil {
// the save failed.
} else {
// the object was saved successfully.
var object = task.result() as PFObject // Error-2.
}
}
The compiler gives me two errors, this one on the line marked "Error-1"
Cannot invoke 'isCancelled' with no arguments
And this other one on the line marked "Error-2"
Expression type 'PFUser?' is ambiguous without more context
I have no idea what kind of argument 'isCancelled' is expecting.
Does anyone know how to fix those?
let userCheckTask = PFUser.getCurrentUserInBackground()
userCheckTask.continueWith {
(task: BFTask) -> BFTask<AnyObject> in
if let e = task.error {
return BFTask(error: e)
} else {
return BFTask(result: task.result)
}
}

nested asynchronous fetches with Cloudkit?

I am relatively new to coding for iOS. In the past week, I've been incorporating CloudKit into my project. One thing I want to do is get the current User recordID. Then, using that recordID, I want to fetch that user's actual record. Currently I am using the following code, which seems to work:
self.container.fetchUserRecordID() { recordID, error in
if error == nil {
self.userRecordID = recordID
DispatchQueue.main.async(execute: {
self.db.fetch(withRecordID: self.userRecordID) { record, error in
if error == nil {
self.userRecord = record
} else {
if let error = error as? CKError {
print(error)
}
}
}
})
}
else {
if let error = error as? CKError {
print(error)
}
}
}
This, however, feels messy to me. My question is two-fold: 1) In general, is it acceptable to nest asynchronous calls? 2) If not, is there a better way to accomplish what I want to do in this situation?
Thanks!

Firebase: How To Access error object in iOS callback [duplicate]

I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Use automatic error variable, and you can cast it to NSError if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
You can now throw any object inheriting ErrorType, and provide custom handling in the catch sentence. You can also cast the error to NSError to access localizedDescription for handling third party errors.
Casting an enum ErrorType will produce a NSError with domain equal to the enum name, code equal to the enum value and an auto-generated localizedDescription with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType {
case Bad
case Worse
case Terrible
}
func throwingFunction() throws {
throw AwfulError.Worse
}
do {
try throwingFunction()
}
catch AwfulError.Bad {
print("Bad error")
}
catch let error as NSError {
print(error.localizedDescription)
}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As #redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output.
static func printCaughtError(_ unknownError : Error) {
let objectDescription = String(describing: unknownError)
let localizedDescription = unknownError.localizedDescription
if localizedDescription != "" {
if localizedDescription.contains(objectDescription) {
print(localizedDescription)
return
}
if !objectDescription.contains(localizedDescription) {
print(objectDescription + ": " + localizedDescription)
return
}
}
print(objectDescription)
}
Then you can call it like this:
catch {
printCaughtError(error)
}
How to get the error message that is inside userInfo:
let errorMessage = (error as NSError).userInfo["message"] as? String

How do I get user record in CloudKit?

I can fetch the userRecordID, but I get an error whenever I try to fetch the record associated with that ID. Any suggestions? Code and error below:
myContainer.fetchUserRecordID { (thisID, thisError) in
if let userError = thisError {
print("DEBUG: error getting user id; \(userError)")
} else {
if let userID = thisID {
self.publicDatabase.fetch(withRecordID: userID, completionHandler: { (fetchedUser, fetchedError) in
if let thisError = fetchedError {
print("DEBUG: error getting user record; \(thisError)")
}
DEBUG: error getting user record; <CKError 0x174045010: "Internal Error" (1/5001); "Couldn't get a PCS object to unwrap encrypted data for field encryptedPublicSharingKey: (null)">
Error in the code, or my fault for trying beta software (iOS 10, Swift 3 & xCode-beta 8.0 beta 2 (8S162m)
From your example it is not clear if self.publicDatabase is equal to myContainer.publicCloudDatabase.
Make sure you fetch it from the same container's database, otherwise it will obviously not work.
myContainer.fetchUserRecordID { userID, error in
guard error == nil else {
print("DEBUG: error getting user id; \(userError)")
return
}
guard let userRecID = userID else {
print("DEBUG: Can't unwrap userID")
return
}
myContainer.publicCloudDatabase.fetch(withRecordID: userRecID, completionHandler: { (fetchedUser, fetchedError) in
//handle the error and the user
print("DEBUG: User fetch FINISHED!", fetchedUser)
})
}
I needed to change from publicDatabase to privateDatabase.
self.publicDatabase.fetch(withRecordID: userID, completionHandler: { (fetchedUser, fetchedError) in
to
self.privateDatabase.fetch(withRecordID: userID, completionHandler: { (fetchedUser, fetchedError) in

Resources