PFQuery not running after Swift 3 conversion - ios

I migrated to Swift 3 and have updated all my Parse functions to the latest syntax. Now, none of the queries return anything. There is no no error but there are also no objects. Whats weird is that it doesn't look like its even making a call, as it instantly returns no objects and there is no activity indicator spinning in the status bar like usual. Here's the query code:
let profileQuery:PFQuery = PFQuery(className: "_User")
profileQuery.whereKey("emailLowercase", equalTo: emailField.text!.lowercased() as String)
profileQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
print(objects?.count)
})
Thanks!

Try it as such:
let Query = PFQuery(className: "_User")
Query.whereKey("emailLowercase", equalTo: emailField.text!.lowercased() as String)
Query.findObjectsInBackground(block: { (objects, error) -> Void in
if (error == nil) {
print("Success")
print(objects?.count)
} else {
print("Error")
}
})

Your query code should be like this;
let query = PFUser.query()

The only thing wrong with your as Baris has suggest is that you are querying the class wrong. You can't query with ("_User")
let profileQuery = PFUser.query()
profileQuery.whereKey("emailLowercase", equalTo: emailField.text!.lowercased() as String)
profileQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil{
print(objects?.count)
}
})

Related

Why is the for loop being skipped over?

I am trying to get an array of a certain row which is equal to the name, but for some reason the for loop is getting skipped over. I put a breakpoint, but the breakpoint never gets called.
let query = PFQuery(className: "Tutors")
query.whereKey("name", equalTo: self.name.text!)
query.findObjectsInBackgroundWithBlock ({
(objects: [PFObject]?, error: NSError?) -> Void in
if(error == nil){
for object in objects!{
//placed break point on line below, program does not stop on breakpoint.
let arr = object["Subject"] as? [String]
self.subject = arr!
print("subjects\(self.subject)")
}
}else{
print(error)
}
})
In your parse dashboard your column is named Name, while you are using name in query.whereKey("name", equalTo: self.name.text!). Capitalize the key and you should be good.

Why am I getting the pointer error?

In the user class I have a pointer "Friendship" to the user class, but when I run the program I get the error -
EDIT: I have figured out why I get the error. "Frinendship is not a pointer, it is a PFRelation, but I still want to access the ProPic and username. How would I do this?
Below is the user class
Below is the Pointer to the user class.
func getFriendPic(){
let imagequery = PFQuery(className: "_User")
imagequery.whereKey("username", equalTo: PFUser.currentUser()!)
imagequery.includeKey("Friendship")
imagequery.findObjectsInBackgroundWithBlock {( objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects!{
let userPic = object["ProPic"] as! PFFile
userPic.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
if(error == nil){
let image = UIImage(data: imageData!)
self.arrayOfFriends.append(image!)
print(self.arrayOfFriends)
}
// dispatch_async(dispatch_get_main_queue()) {
// self.collectionView.reloadData()
// }
})
}
}
}
func getFriendName(){
var query = PFQuery(className: "_User")
query.whereKey("username", equalTo: PFUser.currentUser()!)
query.includeKey("Friendship")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.arrayOfFriendsNames.append(objectIDs[i].valueForKey("username") as! String)
print(self.arrayOfFriendsNames)
}
})
}
The include query parameter doesn't work with Relation. Once you retrieved your user, you need to execute a second query to get the Friendship.
Here's an example to retrieve a PFRelation:
var relation = user.relationForKey("Friendship")
relation.query().findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if let error = error {
// There was an error
} else {
// objects contains the friendships of the user
}
}

Is this error a bug in Xcode 7 or swift 2?

I've been getting this Command failed due to signal: Segmentation fault: 11 error for 2 days now, and I cannot wrap my head around why its doing so. The error pointed at a specific query I made to parse.. However to test if it was my code or just a bug, I copied this EXACT block from Parse's query doc into my project as a function:
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
And it threw the error once again to that block.. Xcode is has also been throwing this message to my compiler :
Why is this happening ?
UPDATE
so it seems Kevin's answer below cleared the compiler bug by letting the compiler tell me the type rather than specifying it in the query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in line , by correcting it to :
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
}
however this other block is a little more complex, how do i adjust it to rid the error? :
func loadBooks() {
var query = PFQuery(className: "Books")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
self.books.removeAll()
let bookObjects = objects as! [PFObject]
for (index, object) in enumerate(bookObjects) {
self.books.append(Book(pfBook: object))
}
}else if let secondMessage = error?.userInfo?["error"] as? String
where secondMessage == "The Internet connection appears to be offline." {
self.failedMessage(secondMessage)
self.activityIndicator.hidden = true
self.activityIndicator.stopAnimating()
}
dispatch_async(dispatch_get_main_queue()){
self.collectionView!.reloadData()
self.refreshControl.endRefreshing()
self.activityIndicator.stopAnimating()
}
}
}
objects is actually of type [PFObject]? not [AnyObject]?. A wild guess would say the root cause trying to downcast.
Anyway, just use the correct type to fix this
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
}
or just let the compiler tell you the type
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
}
let query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
print(objects)
if let objects = objects {
for object in objects {
print(object.objectId)
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
Try this! It works!

How to delete an object from Parse?

I would like to delete an object from Parse when I un-check the table row.
The issue occurs when trying to delete objects from Parse after having queried them.
this is my code:
if cell.accessoryType == UITableViewCellAccessoryType.Checkmark {
cell.accessoryType = UITableViewCellAccessoryType.None
var query = PFQuery(className:"Followers")
query.whereKey("follower", equalTo: "\(PFUser.currentUser()?.username)")
query.whereKey("following", equalTo: "\(cell.textLabel?.text)")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects as! [PFUser] {
object.deleteInBackground()
}
} else {
println(error)
}
}
}
I think the issue is in your query.findObjectsInBackgroundWithBlock
i think its because you are defining objects as! [PFUser] instead of a [PFObject]
try this it should do the trick
query.findObjectsInBackground { (objects, error) in
if error == nil,
let objects = objects {
for object in objects {
object.deleteInBackground()
}
}
I want to delete objects from parse
Yes in the Parse iOS SDK to delete multiple objects in background at once on Parse server, you can use deleteAllInBackground
You can use it with 2 different ways:
PFObject.deleteAll(inBackground: [PFObject]?)
PFObject.deleteAll(inBackground: [PFObject]?, block: PFBooleanResultBlock?)
For example:
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error: NSError?) -> Void in
PFObject.deleteAll(inBackground: objects)
})
You can also see this post
I hope my answer was helpful 😊

query with two key get one object in parse using swift

I am using parse in my app and I want to satisfy the two query and return object without using orQueryWithSubqueries. Here my query to parse code:
func queryToParse(){
var queryForBlood = PFQuery(className: "Donors")
queryForBlood.whereKey("BloodGroup", equalTo: bloodGroupTextField.text)
var queryForCity = PFQuery(className: "Donors")
queryForCity.whereKey("City", equalTo: citySearchTextField.text)
var query = PFQuery.orQueryWithSubqueries([queryForCity,])
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
self.tableData = objects as NSArray
println(self.tableData)
self.tableView.reloadData()
}
else
{
println(error)
}
}
}
Instead of creating two separate PFQuery, then you just have to create one. You only need to create several PFQuery when you want to make an OR query.
Your code should look something like this:
func queryToParse(){
let query = PFQuery(className: "Donors").whereKey("BloodGroup", equalTo: bloodGroupTextField.text).whereKey("City", equalTo: citySearchTextField.text)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
...
}
}

Resources