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)
}
})
Related
I'm using swift(UI) with firebase and Google SignIn. So far sign in has been great but when I come to using a new user the code below fails - no fatal errors just doesn't add a new user document to Firestore because it seems to think it has retrieved a document which it couldn't because one with the specified ID don't exist.
My guess is the mistake is in the section:
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
the full function:
func fetchUser(documentId: String) {
let docRef = Firestore.firestore().collection("users").document(documentId)
print("User id: \(documentId) ( via fetchUser )")
docRef.getDocument { document, error in
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
else {
if let document = document {
do {
print("Working on coding to User.self")
self.appUser = try document.data(as: User.self)
self.fetchSites()
}
catch {
print("func - fetchUser() error: \(error)")
}
}
}
}
}
The argument 'documentId' is passed on from the google sign process
followup func to create the new Firestore document for this new user:
func setFirestoreUser() {
let googleUser = GIDSignIn.sharedInstance.currentUser
let db = Firestore.firestore()
self.appUser.emailAddress = googleUser?.profile?.email ?? "Unknown"
self.appUser.userGivenName = googleUser?.profile?.givenName ?? ""
self.appUser.userFirstName = googleUser?.profile?.name ?? ""
self.appUser.userProfileURL = googleUser?.profile!.imageURL(withDimension: 100)!.absoluteString ?? ""
do {
try db.collection("users").document(googleUser?.userID ?? "UnknownID").setData(from: self.appUser)
self.fetchUser(documentId: googleUser?.userID ?? "")
} catch {
print(error)
}
}
Calling getDocument on a reference to a non-existing document is not an error (as far as I know), and will return a DocumentSnapshot. To detect whether the document exists, check the exists property on the snapshot instead of (only) checking for errors.
if let document = document {
if !document.exists {
...
I maintain a locationId field of type String that is queryable in a CKRecord and when I query on it with valid locationId it gives error: 'An error that is returned when the specified request contains bad information."
let predicate = NSPredicate(format: "locationId == %#", locationID)
let query = CKQuery(recordType: Cloud.Entity.Infrastructure, predicate: predicate)
self.privateDB?.perform(query, inZoneWith: appDelegate.privateContactZoneID ) { (records, error) in
guard error == nil else {
if let ckerror = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckerror)
}
completionHandler(nil, error)
return
}
if let records = records {
completionHandler(records, nil)
}
}
I verify in CloudKit Dashboard the Infrastructure record exists with field locationId that is queryable and has correct value I a looking for.
How can I fix this?
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
}]
checking undefined value before retrieving from parse
I am making a simple app, and implementing the userInformation part. The user can edit his info, but I have trouble that if user doesn't put any info, it will crash when I try to retrieve data from an undefined column.
This is my code to retrieve the user data. If there is data to parse it won't crash, otherwise it will.
var query = PFQuery(className: "Note")
query.getObjectInBackgroundWithId("kg8KhAWCms", block: {
(obj, error)in
if let score = obj! as? PFObject {
print(score.objectForKey("title"))
var nickname = (score.objectForKey("title")) as! String
self.nickNameLabel.text = nickname
} else {
print(error)
}
})
I tried this code as well, but it has error which is binary operator '!=' cannot be applied to operands of type 'String' and 'NiLiteralConvertible'
var query = PFQuery(className: "Note")
query.getObjectInBackgroundWithId("kg8KhAWCms", block: {
(obj, error)in
if let obj = obj! as? PFObject {
print(obj.objectForKey("title"))
var nickname = (obj.objectForKey("title")) as! String
if (nickname != nil) {
self.nickNameLabel.text = nickname
}else{
self.nickNameLabel.text = "you don't have a nick name"
}
} else {
print(error)
}
})
So I am asking how can I handle retrieving undefined value before crash? (please write full code for me)
Is there a way I can check undefined value or specific value in column before I retrieve it?
///like this
if (value in parse == "ABC") {
print("yes")
}
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
})