i am trying to retrive a user's data to get the user info from the _User class using the object id. i used this :
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
}
})
println(userId) // this is the userId as String.
println(self.data) ********* // empty array.
}
i am getting an empty array data here.. I've tried this also but same thing's happening here too. :
var profileQuery:PFQuery = PFUser.query()!
profileQuery.whereKey("objectId", equalTo: userId)
profileQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.data.addObject(object)
}
}
}
Remember that "findObjectsInBackgroundWithBlock" happens async! You need to put any logic pertaining to the data inside of the block.
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
println(self.data) //shouldn't be empty.
}
})
Putting aside why you're using an NSMutableArray for a singular PFUser object—you're basically expecting to see self.data populated in the wrong location. The user would be added to it (assuming a successful retrieval), inside the closure. So do something like:
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
println(self.data) //...shouldn't be empty here
} else {
println("Error retrieving user: \(error.description")
}
})
}
Related
I am trying to create an array of strings for all the usernames using the following code and populate a TableViewController.
class TableViewController: UITableViewController {
var randomUser = [String]()
override func viewDidLoad() {
super.viewDidLoad()
var query: PFQuery = PFUser.query()!
query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil{
if let objects = (objects as? [PFObject]!){
for object in objects{
self.randomUser.append(object.objectForKey("username") as! String)
print(object.objectForKey("username") as! String)
print(self.randomUser.count)
}
}
}
}
print(self.randomUser.count)
}
the output in the console:
0
username
1
username
2
username
3
But UItableview does not populate.. What could be causing this?
My guess is that query is delayed and view is created before it can return data. Thank you for any help!
Yes, you are right. You need to call self.tableView.reloadData() after you get the results of the query. Below is an example of where to call it.
private var usersArray = [PFUser]()
func fetchUsers() {
let userQuery: PFQuery = PFUser.query()!
userQuery.orderByAscending("username")
userQuery.whereKey("username", notEqualTo: (currentUser?.username)!)
userQuery.findObjectsInBackgroundWithBlock({
(users, error) -> Void in
if error == nil {
self.usersArray = users as! [PFUser]
self.tableView.reloadData()
} else {
print(error)
}
})
}
In this example, you can then access the username property by doing usersArray[i].username
I have a table called Assesment
it has the name and send values of each task
what I needed to do is to retrieve all these tasks and store them in an array
and here is my code which gives me an error saying that PFObject doesn't have a member called send:
override func viewDidLoad() {
super.viewDidLoad()
//test
var taskQuery = PFQuery(className: "Assesment")
//run query
taskQuery.findObjectsInBackgroundWithBlock({
(success:[AnyObject]?, error: NSError?) -> Void in
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
ERROR>>>> taskMgr.addtask(object.name,send: object.name)
}
println(taskMgr)
}})
//test
// Do any additional setup after loading the view, typically from a nib.
}
even thought I tried to say instead
taskMgr.addtask(object)
AssesmentManager.swift class:
import UIKit
var taskMgr : AssesmentsManager = AssesmentsManager()
struct task {
var name = "Un-Named"
var send = false
}
class AssesmentsManager: NSObject {
var tasks = [task]()
func addtask(name: String, send: Bool) {
tasks.append(task(name: name, send: send))
}
}
UPDATE
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
if object["send"]=="true"{
taskMgr.addtask(object["name"], true )
}
else{
taskMgr.addtask(object["name"], false )}
}
I updated it to remove the string, boolean problem but I still have the same error of not having a member named subscript
UPDATE#2
This is what it looks like now, but still giving me an error that objects is unresolved:
var taskQuery = PFQuery(className: "Assesment")
//run query
taskQuery.findObjectsInBackgroundWithBlock({
(success:[AnyObject]?, error: NSError?) -> Void in
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
for object in objects {
taskMgr.addtask(object["name"], (object["send"] == "true"))
}
}
println(taskMgr)
}})
In Swift 2.0, findObjects returns optional array of PFObject instead of optional AnyObject. Try this
override func viewDidLoad() {
super.viewDidLoad()
var taskQuery = PFQuery(className: "Assesment")
taskQuery.findObjectsInBackgroundWithBlock {
(success:[PFObject]?, error: NSError?) -> Void in
if let objects = success {
for object in objects {
taskMgr.addtask(object["name"], (object["send"] == "true"))
//taskMgr.addtask(object["name"], (object["send"].isEqual("true")))
}
}
}
}
I am trying to make changes to the data already stored in the core data in Parse. But it is not making the necessary changes. And I looked at the documentation for parse regarding objects here: https://parse.com/docs/ios/guide#objects. And it seems that I am doing exactly what the document is telling me to do. Maybe I am missing something? Here is my code:
import UIKit
import Parse
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var products = PFObject(className:"Products")
products["name"] = "ice cream"
products["description"] = "Strawberry"
products["price"] = 4.99
products.saveInBackgroundWithBlock {
(success, error) -> Void in
if (success) {
println("Object saved with id \(products.objectId)")
} else {
println("Not successful!")
print(error)
}
}
//ignore the code below this line for now please :)
var query = PFQuery(className: "Products")
query.getObjectInBackgroundWithId("7lmnxHxibK", block: { (object: PFObject?, error) -> Void in
if error != nil {
print(error)
} else if let product = object {
print("YO")
product["description"] = "Rocky Road"
product["price"] = 5.99
products.saveInBackground()
}
})
}
}
So the code above created an object with the ID 7lmnxHxibK. The description being Strawberry, the name being ice cream, and the price being 4.99. Which worked as it should. So now as an attempt to change the attributes in the object with the ID 7lmnxHxibK, I wrote the following code:
var query = PFQuery(className: "Products")
query.getObjectInBackgroundWithId("7lmnxHxibK", block: { (object: PFObject?, error) -> Void in
if error != nil {
print(error)
} else if let product = object {
print("YO")
product["description"] = "Rocky Road"
product["price"] = 5.99
products.saveInBackground()
}
})
This code should make the necessary changes to the object with the id 7lmnxHxibK. But rather than making the necessary changes to the object's attributes, it is creating a new object with it's description, name, and price all being (undefined). Anybody have a solution to fix this?
You have to change products.saveInBackground() to product.saveInBackground(). Also by the time you call your second query parse may not be done saving the object for the first time.
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) ...
}
this how i am retrieving user info using the objectId :
func loadData() {
userId = toPass
data.removeAllObjects()
var profileQuery:PFQuery = PFUser.query()!
profileQuery.whereKey("objectId", equalTo: userId)
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
println(self.data) //...shouldn't be empty here
} else {
println("Error retrieving user: \(error) ")
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
fullName.text = self.data["fullName"] as! String! // ***** error here.. cannot assign a value of type 'String' to a value of type 'String?'
}
error is in viewDidLoad.. Any idea where am i wrong? Thanks for your time.
data is an array of parseobjects and you want to read parseobject property from it ... iterate through array or get specific index number from it and then load "fullname" property from it or use getFirstObject... method