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
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'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) ...
}
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")
}
})
}
Here is what I'm trying, basically to query the key "categories" of the class "event" for only the current user:
class AllEntriesTableViewController: UITableViewController {
var allEntries = [""]
override func viewDidLoad() {
super.viewDidLoad()
var user = PFUser.currentUser()
var query = PFQuery(className:"event")
query.whereKey("user", equalTo: user)
query.includeKey("category")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
self.allEntries.removeAll(keepCapacity: true)
// Do something with the found objects
for object in objects {
var allEnt:String = object as String
self.allEntries.append(allEnt.category)
}
} else {
// Log details of the failure
NSLog("Error: %# %#", error, error.userInfo!)
}
}
It looks like you're expecting allEnt to be a String and not an event.
var allEnt:String = object as String
self.allEntries.append(allEnt.category)
You should be creating allEnt as event vars instead if you are intending to access allEnt.category as a property on event. Perhaps you have forgotten a lookup of some kind? Something like:
convertToEvent(allEnt)
self.keyToEventDictionary[allEnt]
Or is it possible that your objects list is actually a list of category results and you should just be doing:
self.allEntries.append(allEnt)