I'd like to retrieve only certain columns from Parse. But it downloads the whole objects instead:
let usersQuery = PFQuery(className: "_User")
usersQuery.whereKey("userId", containedIn: self.memberIds!) // Array of Strings containing the userIds
usersQuery.selectKeys(["email"])
usersQuery.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let users = objects as? [PFUser] {
print("objects: \(users)")
// prints whole object, not only "email" field
}
})
The output:
objects: [<PFUser: 0x7fb1095a7270, objectId: 9Ld9vRPoLZ, localId: (null)> {
email = "iphone5s#mail.com";
fullname = "iPhone 5S";
// ... other fields
}]
Related
I'm trying to get a String array I have inside a document in my Firestore Database.
I added (Manually) one item to this array, but when I'm trying to get the items in that array, I always get an empty array instead.
This is my code so far:
func getUserFollowingList(id userId: String, completion: #escaping(Array<String>)->()) {
let followingArray = [String]()
db.collection(USERS_COLLECTION).document(userId).getDocument { (doc, error) in
if let err = error {
print(err.localizedDescription)
completion(followingArray)
}
guard let following = doc?.get(USER_FOLLOWING) else { return }
let followingList = following as! [String]
completion(followingList)
}
}
I'm trying to get the firends list of the current user.
This is my Firestore database:
following
0 "9RtM0wgiKee6I5Lo8EugTFihyXE3"
profile_image: "IMAGE_URL"
useremail: "user#test.com"
username: "Testuser"
Code
let number=UserDefaults.standard.object(forKey: "phone")
let s=PFQuery(className: "Customer")
s.whereKey("phonenumber", equalTo:number!)
s.getFirstObjectInBackground(block: { (gameScore: PFObject?, error: Error?) in
if let error = error {
//The query returned an error
print(error.localizedDescription)
} else {
//The object has been retrieved
print(gameScore?.objectId)
}
})
I need to fetch object id in a row where it matches my phone number, How do I do that?
I made mistake while calling the query , query needs only Int but iam sending Any data type
let number=UserDefaults.standard.object(forKey: "phone") as? String
let Stringtonumber=Int(number!)
let s=PFQuery(className: "Customer")
s.whereKey("phonenumber", equalTo:Stringtonumber)
s.getFirstObjectInBackground(block: { (gameScore: PFObject?, error: Error?) in
if let error = error {
//The query returned an error
print(error.localizedDescription)
} else {
//The object has been retrieved
print(gameScore?.objectId)
}
})
I have a column "checkInTime" in my Parse class that is of type Date.
I am trying to query any checkInTimes after a certain time
Here is the code I am using
func reloadCheckInView() {
checkIns.removeAll(keepCapacity: true)
let friendsListQuery = PFQuery(className: "Friends")
friendsListQuery.includeKey("friendId")
friendsListQuery.includeKey("user")
friendsListQuery.whereKey("friendId", equalTo: PFUser.currentUser()!)
friendsListQuery.whereKey("approved", equalTo: true)
friendsListQuery.findObjectsInBackgroundWithBlock {(objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
let user = object["user"] as! PFObject
let now = NSDate()
print(now)
let BeforeNow = NSDate().dateByAddingTimeInterval(self.hourWindow * -3600)
print(self.hourWindow)
print(BeforeNow)
let checkInQuery = PFQuery(className: "LocationCheckIn")
checkInQuery.includeKey("user")
checkInQuery.whereKey("CheckInTime", greaterThan: BeforeNow)
checkInQuery.whereKey("user", equalTo: user)
//let subQuery = PFQuery.orQueryWithSubqueries([friendsListQuery, checkInQuery])
checkInQuery.findObjectsInBackgroundWithBlock {(results: [PFObject]?, error: NSError?) -> Void in
if error == nil {
//print(results)
for result in results! {
self.checkIns.append(result)
}
print(self.checkIns)
}
else {
}
}
}
}
else {
print(error)
}
}
}
and my prints which shows the calculations are working as expected..in this case 1 hr before now.
2015-10-17 15:23:49 +0000
1.0
2015-10-17 14:23:49 +0000
[]
and no records found in my query.
If I comment out
checkInQuery.whereKey("CheckInTime", greaterThan: BeforeNow)
the record is printed and you can see the checkIn time should pass my query but doesn't. Any ideas?
[<LocationCheckIn: 0x12903edb0, objectId: M7zTD3qiCL, localId: (null)> {
checkInPlaceId = "ChIJfc7vF8upVogRk20hK-LzaAM";
checkInPlaceName = "12434 Willingdon Rd";
checkInTime = "2015-10-17 14:26:00 +0000";
location = "<PFGeoPoint: 0x127ed52f0, latitude: 35.436804, longitude: -80.828736>";
user = "<PFUser: 0x127ed76d0, objectId: WCMmKTvNUC, localId: (null)>";
}]
And as I just read through my own question I see my error.. a typo
checkInQuery.whereKey("CheckInTime", greaterThan: BeforeNow)
should be
checkInQuery.whereKey("checkInTime", greaterThan: BeforeNow)
I am querying the database like below. However, orderbyAscending does not work properly, the accented letters are all sorted at the bottom. Is there any way Parse sorts it by locale? Or do I have to sort in the code? The string array is not long, about 40 words.
var query = PFQuery(className: RFIstanbulDistrictsClassKey)
query.whereKey(RFIstanbulDistrictsDistrictKey, notEqualTo: "")
query.orderByAscending(RFIstanbulDistrictsDistrictKey)
// constants are defined as follows:
// let RFIstanbulDistrictsClassKey = "IstanbulDistricts"
// let RFIstanbulDistrictsDistrictKey = "district"
It turns out I need to sort the array after loading it from Parse:
districts.removeAll(keepCapacity: true)
let query = PFQuery(className: RFIstanbulDistrictsClassKey)
query.whereKey(RFIstanbulDistrictsDistrictKey, notEqualTo: "")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
districts = objects.map { String($0[RFIstanbulDistrictsDistrictKey] as! String) }
districts.sort { return $0 < $1 } // sort ascending
}
}
I've been able to save successfully to Parse via Swift, but am having trouble retrieving data (and all of the tutorials on retrieving seem to be for Obj-C).
Here's my code (with Id's redacted).
Parse.setApplicationId("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", clientKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
var query = PFQuery(className: "EventObject")
query.getObjectInBackgroundWithId(objectId: String!) {
(event: PFObject!, error: NSError!) -> Void in
if error == nil {
println(event)
} else {
println(error)
}
}
I have 4 records in this class right now, but if I want to pull the data for all of them, how do I get the Object using the ID if I'm not sure what the IDs are? I'm assuming I can access them sequentially as an array, but I'm not quite clear how to do that, and am confused, as the only command I know to retrieve appears to require knowing the ID.
Thanks for any help!
The official parse documentation explains how to make queries - there is sample code in swift.
In your case you have to use findObjectsInBackgroundWithBlock:
var query = PFQuery(className:"EventObject")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
// Do something
}
} else {
println(error)
}
}
which, if successful, provides to the closure an array of objects matching the query - since there's no filter set in the query, it just returns all records.
Swift 2.1 Update
func fetchFromParse() {
let query = PFQuery(className:"Your_Class_Name")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
for object in objects! {
// Do something
}
} else {
print(error)
}
}
}
Here is the code for fetch objects in Swift3.0.
let query = PFQuery(className: "Your_Class_Name")
query.findObjectsInBackground { (objects, error) in
if error == nil {
}
else {
}
}
Retrive Data from parse: swift 3
let adventureObject = PFQuery(className: "ClassName")
adventureObject.addAscendingOrder("objectId")
var objectID: String = String()
adventureObject.findObjectsInBackground(block: { (Success, error) in
})