I've a table 'preferences' where user preferences are saved along with username. I created this method to update current user's preference' but somehow it doesn't seem to work. I am not sure if the portion "prefQuery.getObjectInBackgroundWithId(object.objectId)" is required at all.
I am new to Parse, could somebody please help me point what could be the issue.
func userPreferences(){
var currUser = PFUser.currentUser()
var prefQuery = PFQuery(className: "preferences")
var prefObj = PFObject(className: "preferences")
if let currUserName = PFUser.currentUser()?.username {
prefQuery.whereKey("username", equalTo: currUserName)
}
prefQuery.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
prefQuery.getObjectInBackgroundWithId(object.objectId){
(object: PFObject?, error: NSError?) -> Void in
if error == nil || object != nil {
prefObj["agestart"] = self.fromAge.text
prefObj["ageend"] = self.toAge.text
prefObj["location"] = self.location.text
ProgressHUD.showSuccess("Update successful")
} else {
ProgressHUD.showError("Update failed")
}
}
}
}
}
}
}
I found the issue and have updated my codes. The working codes are below; the issue was with the "prefObj["agestart"]" block of codes where I was using the wrong Query instance. You can compare the two snippets:
func userPreferences(){
var currUser = PFUser.currentUser()
var prefQuery = PFQuery(className: "preferences")
var prefObj = PFObject(className: "preferences")
if let currUserName = PFUser.currentUser()?.username {
prefQuery.whereKey("username", equalTo: currUserName)
}
prefQuery.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
prefQuery.getObjectInBackgroundWithId(object.objectId){
(prefObj: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
ProgressHUD.showSuccess("Error while updating")
} else if let prefObj = prefObj {
prefObj["agestart"] = self.fromAge.text
prefObj["ageend"] = self.toAge.text
prefObj["location"] = self.location.text
ProgressHUD.showSuccess("Update successful")
prefObj.saveInBackgroundWithBlock({ (Bool, error: NSError!) -> Void in })
}
}
}
}
}
}
}
The best way to cut your code to the maximum, you can see below:
func userPreferences() {
let prefQuery = PFQuery(className: "preferences")
if let currUserName = PFUser.current()?.username {
prefQuery.whereKey("username", equalTo: currUserName)
}
prefQuery.findObjectsInBackground {
(objects, error) in
if error == nil {
if let objects = objects {
for object in objects {
object["agestart"] = "ur value"
object["ageend"] = "ur value"
object["location"] = "ur value"
print("Update successful")
object.saveInBackground()
}
}
}
}
}
Related
How can I query after a specific row where the objectId is equal to a objectId I have stored?
This is my query code:
func queryStory(){
let query = PFQuery(className: "myClassStory")
query.whereKey("isPending", equalTo: false)
query.limit = 1000
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
for post in posts! {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
print("Done!")
}
else{
print(error)
}
}
}
This is my Parse database class:
What I want, is to only query the items that was createdAt after the objectId: woaVSFn89t. How can I do this?
Try filtering the objects once you have found them:
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
var thePostTime = NSDate()
for post in posts! {
if post.objectId == "The Object Id You Were Trying To Find" {
thePostTime = post.createdAt!
}
}
for post in posts! {
if post.createdAt!.isGreaterThan(thePostTime) == true {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
}
print("Done!")
}
else{
print(error)
}
}
You will notice that I compared the dates using this: NSDate Comparison using Swift
Before the for-loop make a variable:
var havePassedObjectId = false
Then inside the for-loop check if the current post is equal to the object id you want:
if post.objectid == "woaVSFn89t" {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
havePassedObjectId = true
} else if havePassedObjectId == true {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
}
This will check if you have already passed the object and append all the objects after.
I'm trying to make a relational query with just some keys but its return all keys.
What am I doing wrong ?
query.getObjectInBackgroundWithId(objectId) { (object:PFObject?, error:NSError?) -> Void in
if error == nil {
var relation: PFRelation = object!.relationForKey("MenuDetails")
relation.query()!.selectKeys(["Receipe_Lvl1"])
var testArray = NSMutableArray()
relation.query()!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
testArray.addObject(object)
}
}
} else {
}
}
}
}
Thank you for your help
I had never use Parse but i think that you should chain methods.
query.getObjectInBackgroundWithId(objectId) { (object:PFObject?, error:NSError?) -> Void in
if error == nil {
var relation: PFRelation = object!.relationForKey("MenuDetails")
var testArray = NSMutableArray()
relation.query()!.selectKeys(["Receipe_Lvl1"]).findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
testArray.addObject(object)
}
}
} else {
}
}
}
}
I'm doing some iOS app on Xcode 6.4 where I'm using Parse as a back-end, and everything is going fine until I try to add the Parse gotten messages from objects to an staring array.
The error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The thing is I do not know what nil is it talking about as I have unwrapped all the values or at least I think so, help??
Code:
var mensajes:[String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
println("\(PFUser.currentUser()!.username!)")
menuLabel.text = "Bienvenido \(PFUser.currentUser()!.username!)"
/*
var query = PFQuery(className: "Alumnos")
query.whereKey("nombre", hasSuffix: "1")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error")
println("we have \(objects!.count)")
if let object = objects as? [PFObject] {
for obj in object {
println("\(obj.objectId) ----")
println(obj)
println(obj["nombre"] as! String + "*****")
}
}
} else {
println("a misterious error has appeared \(error!) \(error!.description)")
}
} */
var avisosQuery = PFQuery(className: "Alumnos")
if let papa = PFUser.currentUser() {
avisosQuery.whereKey("userId", equalTo: papa)
avisosQuery.findObjectsInBackgroundWithBlock {
(alumnos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No Error we have \(alumnos?.count) students")
var grupos: PFObject? = nil
if let obj = alumnos as? [PFObject] {
for alum in obj {
println(alum["nombre"])
//println(alum["grupoId"])
//println(alum)
grupos = alum["grupoId"] as? PFObject
println(grupos!)
var secondQuery = PFQuery(className: "Avisos")
secondQuery.whereKey("grupoId", equalTo: grupos!)
secondQuery.findObjectsInBackgroundWithBlock {
(avisos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error we are home free \(avisos?.count)")
if avisos?.count > 0 {
if let avisoArray = avisos as? [PFObject] {
for av in avisoArray {
println(av["texto"]!)
if let msg: AnyObject = av["texto"] {
println(msg)
self.mensajes.append(msg as! String)
}
}
}
}
} else {
println("something got busted, mate")
}
}
}
}
} else {
println("we screw something up")
}
}
}
}
And I'm in the learning stage with Parse, that why this is in the viewDidLoad() I'm just trying some things.
if let papa = PFUser.currentUser()
The problem is in that line we are not get the userid so technically you are looking for a null value
Right Code :
let papa = PFUser.currentUser().objectId
Try it
I tried this:
var data:NSMutableArray = NSMutableArray()
func loadData() {
var userQuery = PFUser.query()!
userQuery.whereKey("objectId", equalTo: PFUser.currentUser()!.objectId!)
userQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.data.addObject(object)
}
}
}
println(data) // this gives an empty NSMutableArray.
}
Is there any other way to get the data of current user? , I am doing this to make the profile Screen of the current user..Thanks for your time..
Use this to access the current user
if PFUser.currentUser() != nil {
PFUser.currentUser()!.fetchIfNeededInBackgroundWithBlock({ (user: PFObject?, error: NSError?) -> Void in
if user != nil {
var u = user as! PFUser
//Access the fetched user HERE
}
})
//NOT here, it will be nil here
}
func queryForPhotosFromLocalDatastore()
{
var xquery = PFQuery(className: "Follows")
xquery.fromLocalDatastore()
//xquery.whereKey("Follower", equalTo: PFUser.currentUser()!.objectId!)
xquery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let xobjects = objects
{
if xobjects.count > 0
{
for yobject in xobjects
{
println("Done")
}
}
else
{
println("number of objects is \(xobjects.count)")
}
}
else
{
println(error?.userInfo)
}
}
}
func queryForPhotosFromParse()
{
PFObject.unpinAllObjectsInBackgroundWithBlock(nil)
var xquery = PFQuery(className: "Follows")
xquery.whereKey("Follower", equalTo: PFUser.currentUser()!.objectId!)
xquery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let xobjects = objects
{
println("xobjects are \(xobjects.count)")
println("querying from parse")
for yobject in xobjects
{
var followedUser = yobject["Following"] as! String
var query = PFQuery(className: "Images")
query.whereKey("userID", equalTo: followedUser)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (xobjects, error) -> Void in
if let objects = xobjects
{
PFObject.pinAllInBackground(objects, block: { (success, error) -> Void in
if error == nil
{
println("Pinned \(objects.count) objects")
self.queryForPhotosFromLocalDatastore()
}
})
}
else
{
println(error?.userInfo)
}
}
}
}
}
}
// The number of objects its returning (xobjects.count) is 0. Why is that so ?
I tried to have query localdatastore in my app but The number of objects its returning (xobjects.count) is 0. Why is that so ?
i have tried to query before with the previous versions but same thing happened. The latest version on parse says that they have fixed the error but I'm still getting the number of objects retrieved from localdatastore as "0". Please Help.