Why does this keep returning error "Object not found" from Heroku/Parse in swift? - swift

I am trying to delete the row where username = usernameSelected from the Heroku/Parse server. Username selected is not nil and does exist on the server. Nothing seem wrong at all, only the "Object not found" instead of deleting the whole row.
let query = PFQuery(className: "Requests")
query.whereKey("username", equalTo: usernameSelected)
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (objects, error) in
if error != nil {
}else {
if let objects = objects {
for obj in objects {
obj.deleteInBackgroundWithBlock({ (success, error) in
activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error != nil {
self.alertDisplay("Error", message: error?.userInfo["error"] as! String)
}else {
self.alertDisplay("", message: "Styles Submitted..! Please wait for your next Style")
}
})
}
}
}
})

make sure you have read and write permissions for your class
the deleting could be failing because the ACL for the rows created in your class only have the read permission. To allow both read and write permissions, in your AppDelegate under method "didFinishLaunchingWithOptions" you will see lines
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.getPublicReadAccess = true
add the line --- defaultACL.getPublicWriteAccess = true
this will help you create all rows with write permissions so that in future you can delete an object from the client side.

Related

How to get an array of CNGroup from a CNContainer using CNContactStore?

I'm looking for a way to get a list of groups (CNGroup) that relate to a contact container (CNContainer). When I use a predicate it fails.
The code I'm using is
func populateGroups(tableView:NSTableView,container:CNContainer){
print("populateGroups.start")
print(container.name)
print(container.identifier)
let contactStore = CNContactStore()
do {
let groupsPredicate = CNGroup.predicateForGroups(withIdentifiers: [container.identifier])
groups = try contactStore.groups(matching: groupsPredicate)
groupNames.removeAll();
for group:CNGroup in groups {
self.groupNames.append(group.name)
}
tableView.reloadData()
} catch {
print( "Unexpected error fetching groups")
}
print("populateGroups.finish")
}
I'm getting an error from that doesn't make sense to me.
The line groups = try contactStore.groups(matching: groupsPredicate) causes an error.
[Accounts] Failed to update account with identifier 47008233-A663-4A52-8487-9D7505847E29, error: Error Domain=ABAddressBookErrorDomain Code=1002 "(null)"
Which is confusing as I'm not updating any account.
If I change that line of code to groups = try contactStore.groups(matching: nil)
I get all the groups for all the containers.
How do you create a predicate that will return all the CNGroups that belong to a CNContactContainer?
I worked around this by checking that each group from all the groups belonged to the container in question using CNContainer.predicateForContainerOfGroup
func populateGroups(tableView:NSTableView,container:CNContainer){
let contactStore = CNContactStore()
do {
let groups:[CNGroup] = try contactStore.groups(matching: nil)
self.groups.removeAll();
groupNames.removeAll();
for group:CNGroup in groups {
let groupContainerPredicate:NSPredicate = CNContainer.predicateForContainerOfGroup(withIdentifier: group.identifier)
let groupContainer:[CNContainer] = try contactStore.containers(matching: groupContainerPredicate)
if( groupContainer[0].identifier == container.identifier) {
self.groupNames.append(group.name)
self.groups.append(group)
}
}
tableView.reloadData()
} catch {
print( "Unexpected error fetching groups")
}
}

Swift Parse Query Using A Pointer

I have to query for a class called "Commitment" it has a pointer called "need". I need to be able to access the data in the pointer of need while querying Commitment. I have to query for Commitment because I have to check the "committer" object against the current user. Essentially I want to be able to see the needs that the current user has committed to.
Commitment Class:
Need Class:
let query = PFQuery(className: "Commitment")
query.order(byDescending: "createdAt")
query.whereKey("committer", equalTo: PFUser.current()!)
query.includeKey("need")
query.findObjectsInBackground {
(objects: [PFObject]?, error: Error?) -> Void in
if let objects = objects as [PFObject]? {
self.committment = []
self.commitObject = []
for object in objects {
self.committment.append(Committment(id: object.objectId!, needName: object["needName"] as! String))
self.commitObject.append(object)
}
self.tableView.reloadData()
} else {
print("failure")
}
}
This is my current query. It returns nil on needName so obviously that isn't working. Any help is appreciated.
The reason that you get nil is because you are not accessing the need object but you are trying to get it from the Commitment object
just change your code to something like this:
let query = PFQuery(className: "Commitment")
query.order(byDescending: "createdAt")
query.whereKey("committer", equalTo: PFUser.current()!)
query.includeKey("need")
query.findObjectsInBackground {
(objects: [PFObject]?, error: Error?) -> Void in
if let objects = objects as [PFObject]? {
self.committment = []
self.commitObject = []
for object in objects {
let need = object["need"] as [PFObject]?
self.committment.append(Committment(id: object.objectId!, needName: need["needName"] as! String))
self.commitObject.append(object)
}
self.tableView.reloadData()
} else {
print("failure")
}
}
Notice that i first access the need object and from there extract the needName property.
BTW! i am not sure that the syntax is 100% accurate (i wrote it in freestyle) but i am sure that you got the idea..

Error saving CKRecord and CKShare in CKModifyRecordsOperation

I'm trying to save a CKRecord (already created and saved to the database) and a new CKShare to it but I keep getting this error: Optional("Failed to modify some records"). Here is my code:
let csc = UICloudSharingController { controller, preparationCompletionHandler in
let share = CKShare(rootRecord: user)
share[CKShareTitleKey] = "My Share" as CKRecordValue
share.publicPermission = .readWrite
let mro = CKModifyRecordsOperation(recordsToSave: [user, share], recordIDsToDelete: nil)
mro.timeoutIntervalForRequest = 10
mro.timeoutIntervalForResource = 10
mro.modifyRecordsCompletionBlock = { records, recordIDs, error in
if error != nil {
print("ERROR IN MODIFY RECORDS COMPLETION BLOCK\n")
print(error?.localizedDescription)
}
preparationCompletionHandler(share,CKContainer.default(), error)
}
privateData.add(mro)
}
csc.availablePermissions = [.allowPrivate,.allowReadWrite]
self.present(csc, animated:true)
}
The problem is in this method: modifyRecordsCompletionBlock. Can somebody explain me why this is happening?
Thanks in advance!
I got it
All you have to do is create a private custom CKZone and save your CKRecord and CKShare in it, you cannot use the default zone cloud kit gives to you!
To leave a shared record, you have to delete the CKShare record from the shared database otherwise you'll get errors.

query if the data is found - Parse & Swift 3

I'm trying to develop an app that provide User sign up and within the UI I want to query if the email is exists or not.
The problem is since I change from swift 2 to swift 3 I got these errors
var query = PFObject(className:"User")
query.whereKey("email", equalTo: email)
query.findObjectsInBackground {
(objects, error) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {
print(object.objectId)
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
/Users/**************/SignUpSenderViewController.swift:49:9:
Value of type 'PFObject' has no member 'whereKey'
/Users/i*************/SignUpSenderViewController.swift:50:9:
Value of type 'PFObject' has no member 'findObjectsInBackground'
any suggestion to solve this challenge ?
I dont know what documentation you checked but the query has to be done this way...
let query = PFQuery(className:"_User")

How do you store a dictionary on Parse using swift?

I am very new to swift and I don't know Obj C at all so many of the resources are hard to understand. Basically I'm trying to populate the dictionary with PFUsers from my query and then set PFUser["friends"] to this dictionary. Simply put I want a friends list in my PFUser class, where each friend is a PFUser and a string.
Thanks!
var user = PFUser()
var friendsPFUser:[PFUser] = []
var friendListDict: [PFUser:String] = Dictionary()
var query = PFUser.query()
query!.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(users!.count) users.")
// Do something with the found objects
if let users = users as? [PFUser] {
friendsPFUser = users
for user in friendsPFUser{
friendListDict[user] = "confirmed"
}
user["friends"] = friendListDict //this line breaks things
user.saveInBackground()
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
To be clear, this code compiles but when I add
user["friends"] = friendListDict
my app crashes.
For those who might have this issues with. "NSInternalInconsistencyException" with reason "PFObject contains container item that isn't cached."
Adding Objects to a user (such as arrays or dictionaries) for security reasons on Parse, the user for such field that will be modified must be the current user.
Try signing up and using addObject inside the block and don't forget do save it!
It helped for a similar problem I had.