Check if PFObject is nil - ios

I want to check if a PFObject is nil
I retrieve the object
var userLibrary: PFObject?
func getUserLibrary(user: PFUser) {
self.libraryQuery = PFQuery(className: "Library")
self.libraryQuery?.whereKey("owner", equalTo: user)
self.libraryQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if objects!.count > 0 {
self.userLibrary = objects![0]
} else {
print(self.userLibrary)
}
}
})
}
The last line with the print statement prints out nil.
However when I check :
if userLibrary != nil {
}
Xcode tells me
Binary operator '!=' cannot be applied to operands of type 'PFObject' and 'NilLiteralConvertible'
How do I fix this ?

I'm not 100% sure that this will work, but did you try.
if let lib = userLibrary {
//do whatever
}
Let me know.
Also, if you are just using the first object of your query. It would better to use getFirstObjectInBackground

Related

Is it possible to query dictionary on parse.com?

i’m trying to search dictionary match result but no luck
my parse dictionary column look like this
columnName: Tag property: object
{"firstKey”:”David”,”secondKey”:”Guetta”}
columnName: name property: string
cool

when I try to search name column
here is my code snippet,
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("name", equalTo: "cool")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get result below
objects is Optional([ {
Tag = {
firstKey = David;
secondKey = Guetta;
};
name = cool;
tagArray = (
David,
Guetta
);
}])
i've try array column
columnName: tagArray property: array
["David","Guetta"]
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("tagArray", equalTo:"David")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get result
objects is Optional([ {
Tag = {
firstKey = David;
secondKey = Guetta;
};
name = cool;
tagArray = (
David,
Guetta
);
}])
but when i try to search dictionary column
columnName: Tag property: object
{"firstKey”:”David”,”secondKey”:”Guetta”}
like this
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("Tag", equalTo:"David")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get no result
objects is Optional([])

i’ve try google and parse official doc but can’t find this case, is it possible to do that?
i've try search string column, array column it's work but only dictionary column not work...
search in google with "findObjectsInBackgroundWithBlock" in swift.It will give you many results.
var query = PFQuery(className: parseClassName)
query.whereKey("Position", equalTo: "iOS Developer")//Here Position is column name and Sales Manager is value.
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
for object in objects {
}
}
else{
println("Error in retrieving \(error)")
}
})

How to check UserName taken in parse Xcode

I'm trying to check if username is already taken in parse or not, but seems don't work with my code, can you please what i'm doing wrong on it
Thanks
func usernameIsTaken(userName: String) -> Bool {
let userName = userNameTextField.text
let myUser: PFUser = PFUser.currentUser()!
//bool to see if username is taken
var isTaken : Bool = false
//access PFUsers
let query = PFUser.query()
query!.whereKey("username", equalTo: userName!)
query!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]? , error : NSError? ) in
if error == nil {
if (objects!.count > 0) {
isTaken = true
print("username is taken")
} else {
print("Username is available. ")
}
} else {
print("error")
}
}
return isTaken
}
For one, you can attempt to sign the user up and Parse will return an error code of 202 if the username has already been taken.
http://parse.com/docs/dotnet/api/html/T_Parse_ParseException_ErrorCode.htm
If this isn't your intended use, to query the User table, use PFUser.query to construct a query instead.
Try this :
query.findObjectsInBackgroundWithBlock({ (object: [PFObject]?,error: NSError?) -> Void in
if error == nil {
}
})
With that being said if your only Interested in the count parse introduced a new method similar to findObjectsInBackground but does exactly what you are looking for, the method is called countObjectsInBackground
You can call this method after you define your query.
like so
query.countObjectsInBackgroundWithBlock { (count: Int32,error: NSError?) -> Void in
if error == nil {
//code here
}
Hope this helps

Parse save pointer

This is my code that tries to save the table/Class inscricoes
view.showHUD(view)
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = self.eventObj.objectId
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else { errorAlert.show(); self.view.hideHUD() }
}
This is my class / table where sorteioId is a pointer to my table/class sorteios
when I try to save an error of warning that can not save as a string pointer.
[Error]: invalid type for key sorteioId, expected Sorteios, but got string (Code: 111, Version: 1.7.5)
How do I send a pointer to table / class using parse?
You first need an instance of PFObject of type Sorteios. Revise your code like so:
view.showHUD(view)
var query = PFQuery(className: "Sorteios")
query.getObjectInBackgroundWithId(self.eventObj.objectId) {
(object: PFObject?, error: NSError?) -> Void in
if error == nil && object != nil {
// after finding Sorteios, you can assign it to inscricaoClass
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = object
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else {
errorAlert.show(); self.view.hideHUD() }
}
}
}

Passing objectId from viewDidLoad to another function using Parse method getObjectInBackgroundWithId not working

I'm a beginner working with Parse and Swift. I need to update the object referred to in my viewDidLoad in another function within the same controller. How do I pass the currently loaded object's objectId without having to hardcode it like this:
query.getObjectInBackgroundWithId("8DkYgraEJq")
Here is my viewDidLoad function:
override func viewDidLoad() {
var query = PFQuery(className: "CheckedBaggage")
query.orderByAscending("createdAt")
query.whereKey("respondedTo", notEqualTo: true)
query.getFirstObjectInBackgroundWithBlock {
(CheckedBaggage: PFObject!, error: NSError!) -> Void in
if error != nil {
println("The getFirstObject request failed.")
} else {
// The find succeeded.
self.randomBaggageLabel.text = CheckedBaggage.objectForKey("message") as? NSString
CheckedBaggage.save()
println(CheckedBaggage.objectId)
let baggageId = CheckedBaggage.objectId
println("Successfully retrieved the object.")
}
}
I would like to try and pass the variable baggageId, which should be the object's ID as a string, as an argument to the getObjectInBackgroundWithId block in my carryIt function:
#IBAction func carryIt(sender: AnyObject!) {
println("CarryIt is being called")
var query = PFQuery(className: "CheckedBaggage")
query.getObjectInBackgroundWithId(baggageId) {
(CheckedBaggage: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
} else if let CheckedBaggage = CheckedBaggage {
println("object hello!")
CheckedBaggage["respondedTo"] = true
CheckedBaggage["response"] = self.kindnessMessage.text
CheckedBaggage.save()
}
}
}
But I'm getting an "unresolved identifier" error. It updates my Parse database perfectly fine if I hardcode the object ID, but I can't do it this way. Here's a screenshot of the error:
Thank you so much for your help!
You have to initialize baggageId. To use it in multiple functions, it must be scoped at class level as the comment said. To set it after it has been declared, it must be a "var", not a constant "let".
var baggageId = ""
func viewDidload() {
var query = ...
query.get... {
baggageId = CheckedBaggege.objectId
}
}
func shipIt() {
var query = ...
query.getObjectWithId(baggageId) ...
}

Retrieve values out of PFObject

I have a save button to save Score and Playername to GameScore in Parse. When I load the GameScore from Parse I want to set the value that i loaded to the variable "score". This don't work, can anyone please tell me what i am doing wrong?
Thanks
Exapmle: let score = gameScore["score"] as Int
// Load button tapped
#IBAction func loadButtonTapped(sender: UIButton) {
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("F1efANYzOE") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
let score = gameScore["score"] as Int
} else {
println(error)
}
}
}
}
Try this following code for retrieving specific data from specific columns. You have to enter your object name, Object ID and column name in the below code and run it. It will work.
let query = PFQuery(className:"Your Object name")
query.getObjectInBackgroundWithId("Your Object ID") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil {
print(gameScore!.objectForKey("your column name") as! String)
} else {
print(error)
}
}

Resources