I am retrieving the current user info from parse and saving it in data:NSMutableArray = NSMutableArray() and tring to get the "fullName" of the user to show it in label called userName I'm using this :
var name:String = self.data["fullName"] as! String // error here: AnyObject is not convertible String.
self.userName.text = name
I saw many question in here but they dint help me. Gave the same error.
println(self.data) gave me this :
(
"<PFUser: 0x7fa01bd7eed0, objectId: SiA72FwNi2, localId: (null)> {\n email = \"jhsbdfjhs#jhbs.com\";\n fullName = \"Khjdf Ujhdsf\";\n gender = male;\n profilePicture = \"<PFFile: 0x7fa01bd719b0>\";\n username = jhsfgj;\n}"
)
this is my function:
func loadData() {
if PFUser.currentUser() != nil {
PFUser.currentUser()!.fetchIfNeededInBackgroundWithBlock({ (user: PFObject?, error: NSError?) -> Void in
if user != nil {
var u = user as! PFUser
self.data.addObject(u)
}
})
println(self.data)
}
}
your self.data is NSMutableArray and you can not access fullName like this, first you need to get PFObject from self.data by giving index like this self.data[0] and then get fullName
var object:PFObject = self.data[0]
var st:String = object["fullName"] as! String
Related
On Parse I have users with Facebook profile and Email login profile. So I want to bury for users data in my twitter-like app.
In my "messages" class on Parse I have column "sender" that contains pointers to parse users.
I just want to retrive and show the name of users in class "messages" contained in the column "sender" wich contains pointers to PFUsers of which I need data for keys
"first_name"
"last_name"
"profile_picture"
How can I retrive their data like name and image in order to show them in a tableview?
these are the declarations of my arrays:
var sendersArray : [String] = []
var picturesArray : [NSData] = []
maybe I could use something like this tuple, but I can't understand how to grab data from pointers
for user in list {
let firstName = "fist_name"
let lastName = "last_name"
let oProfileImage = NSData() //"image_profile" as! NSData
otherUsers.append((oName: firstName, oLastName: lastName, oImageProfle: oProfileImage))
}
version - 1:
I started with printing the whole pf object
//******************************************************
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.sender!
print(object)
print(theName)
sendersArray.append(theName)
let profilePicture = object["profile_pic"] as! PFFile
picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
//*******************************************************
version - 2:
then, found this solution, but still, doesn't
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages" )
theSearchQuery.includeKey("sender")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.sender!["first_name"] as? String
print(object)
print(theName)
sendersArray.append(theName)
let profilePicture = object["profile_pic"] as! PFFile
picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
errors:
seems to be a problem with sender, maybe I shouldn't use it
thanks in advance
let theName = object.objectForKey("sender")!.objectForKey("first_name") as! String
Complete Code:
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages")
theSearchQuery.includeKey("sender")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.objectForKey("sender")!.objectForKey("first_name") as! String
print(object)
print(theName)
self.sendersArray.append(theName)
let profilePicture = object["profile_picture"] as! PFFile
self.picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
Also, your picturesArray should be of type PFFile, like this:
var picturesArray = [PFFile]()
NOT NSData. change that at the top of your class.
-----EDIT------:
If you want to retrieve an image from a parse query, do this:
1) at the top of your class, declare the following arrays to store the results:
// your images will be stored in the file array
var fileArray = [PFFile]()
// your first and last names will be stored in String Arrays:
var firstNameArray = [String]()
var lastNameArray = [String]()
2) perform the query:
let query1 = PFQuery(className: "_User")
query1.orderByDescending("createdAt")
query1.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
if error == nil {
for x in objects! {
let firstName = x.objectForKey("first_name") as! String
let lastName = x.objectForKey("last_name") as! String
self.firstNameArray.append(firstName)
self.lastNameArray.append(lastName)
if x.objectForKey("profile_picture") as? PFFile == nil {
print("do nothing cause it's nil")
}
else {
let file:PFFile = x.objectForKey("profile_image") as! PFFile
self.fileArray.append(file)
}
}
self.tableView.reloadData()
}
})
Note I am using Swift 2 and Xcode 7. Syntax is slightly different in Xcode 6.4 and Swift 1.2.
I am using the following code :
PFCloud.callFunctionInBackground("getFollowers", withParameters: ["userId":id!,"offset":0 ]) { (result , error) -> Void in
if let result = result as? [Follower] {
print(result)
for fl in result {
print(fl)
}
}
}
}
the print(result) shows the following:
[<Follower: 0x7f8f7253c2f0, objectId: 5h3pcK0GTK, localId: (null)> {
Likes = 2;
description = cggggg;
image = "<PFFile: 0x7f8f7253b220>";
isFollowing = 0;
pushed = 1;
user = "<Spoke.SPKUser: 0x7f8f72564690, objectId: ESczJnhc7c, localId: (null)>";
voice = "<PFFile: 0x7f8f7253e8e0>";}]
the weird thing is print(fl) shows :
fl myapp.Follower 0x00007fe0c1e6aa90 0x00007fe0c1e6aa90
Parse.PFObject PFObject
Likes Int! nil
image PFFile! nil
isFollowing Bool! nil
pushed Bool! nil
user Spoke.SPKUser! nil
voice PFFile! nil
My question is why I cannot get an array of mapped follower objects ?
I just added #NSManaged in front of every property of my PFObject subclass and it worked
I have cloud code to search for the users relations with other users when they go to their friends page.
Problem I am having is populating the array of PFObjects I have that stores the info of the users friends so it can be displayed in the tableview.
Here is my cloud code:
Parse.Cloud.define("getFriends", function(request, response) {
var userId = request.params.UserKey;
var query = new Parse.Query(Parse.User);
query.get(userId, {
success: function(foundCurrentUser) {
var currentUser = foundCurrentUser;
var relation = currentUser.relation("Friends");
var getRelationQuery = relation.query();
getRelationQuery.find().then(function(results){
response.success(results);
});
},
error: function(error) {
response.error(error);
}
});
});
I check my logs and get the correct response. It contains the correct data in JSON.
Now here is the problem. My cloud query in the iOS app is what is causing me grief.
let currentUser: PFUser = PFUser.currentUser()!
let params = NSMutableDictionary()
params.setObject(PFUser.currentUser()!.objectId!, forKey: "UserKey")
PFCloud.callFunctionInBackground("getFriends", withParameters: params as [NSObject : AnyObject], block: {
(object:AnyObject?, error: NSError?) -> Void in
if error == nil {
self.currentUserFriendList.append(object as! PFObject)
}
else
{
println("didnt retrieve the carpoolers")
}
})
On the line of code I get an issue is self.currentUserFriendList.append(object as!! PFObject) with the error Could not cast value of type '__NSArrayM' (0x111cd8448) to 'PFObject' (0x10fd8a818).
I want to use a
for object in objects {
self.currentUserFriendList.append(object as! PFObject)
}
But the block isn't an object:[AnyObject]
When I print the object I get the correct relations wrapped in an Optional like so
Optional((
"<PFUser: 0x7fa5db4a6de0, objectId: 1FLleawAQz, localId: (null)> {\n Friends = \"<PFRelation: 0x7fa5db47b1a0, 0x0.(null) -> _User>\";\n email = \"test#test.com\";\n fullName = \"Tester \";\n profilePicture = \"<PFFile: 0x7fa5db4a0140>\";\n username = \"test#test.com\";\n}",
"<PFUser: 0x7fa5db47d5f0, objectId: nqFBQYIVjD, localId: (null)> {\n Friends = \"<PFRelation: 0x7fa5db5c97b0, 0x0.(null) -> _User>\";\n email = \"test2#test.com\";\n fullName = test2;\n profilePicture = \"<PFFile: 0x7fa5db554400>\";\n username = \"test2#test.com\";\n}"
))
I was able to get the response to output exactly what I wanted and append it to my array of PFObjects like this.
if error == nil {
let objects = response as! [PFObject]
for object in objects as [PFObject] {
self.currentUserFriendList.append(object as PFObject)
println("\(object)")
}
I am retrieving all the user details this way..
var userIds = [String]()
var userNames = [String]()
var profilePics = [PFFile]()
var gender = [String]()
override func viewDidLoad() {
super.viewDidLoad()
var userQuery = PFUser.query()
userQuery?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
self.userIds.removeAll(keepCapacity: true)
self.userNames.removeAll(keepCapacity: true)
self.profilePics.removeAll(keepCapacity: true)
for object in objects {
if let user = object as? PFUser {
if user.objectId != PFUser.currentUser()?.objectId {
self.userIds.append(object.objectId as String!)
self.userNames.append(object["fullName"] as! String!)
self.profilePics.append(object["profilePicture"] as! PFFile!)
self.gender.append(object["gender"] as! String!)
}
}
}
}
self.tableView.reloadData()
})
}
now i have "follow" button in myCell.. saving this way..
#IBAction func followButtonTapped(sender: UIButton) {
var followers:PFObject = PFObject(className: "Followers")
followers["user"] = userIds[sender.tag] // Problem is here.. i want "user" column to be filled with userIds of users as Pointers not Strings. What should i do here??
followers["follower"] = PFUser.currentUser()
followers.saveInBackground()
}
Because i want to make relations with every object in "Followers" class that's why i want them to be in the form of Pointers.. Any suggestion please??
If you want to create a pointer to another PFObject (including PFUser) you will need to actually point to that object.
I see in your query that you are not adding any PFUsers to your array, but you are getting their object IDs.
Since a tag is only for an Int, you can not use it to pass a String (which a Parse objectID is).
You can subclass UIButton and create a new property to handle the objectID from parse and then use that to perform a query with the objectID and save the pointer to the result of that query. Or you can just add the object from your first query to your local array and use your button's tag to get the index of the object you want to point to.
Update
Since you have the objectId for the PFuser you want, you can get it and update your followers like so:
let getOjbectByIdQuery = PFQuery(className: "User")
getOjbectByIdQuery.whereKey("objectId", equalTo: userIds[sender.tag])
getOjbectByIdQuery.getFirstObjectInBackgroundWithBlock { (foundObject: PFObject?, error: NSError?) -> Void in
if let object = foundObject {
var followers:PFObject = PFObject(className: "Followers")
followers["user"] = object
followers["follower"] = PFUser.currentUser()
follwers.saveInBackground()
}
}
I want to get a record from my parse.com class called "Tags" by ID. I want to retrieve data from the object "username" and "tagtext". Afterwords I want to save "username" to the String "username" and "tagtext" to the String "tagtext". My code looks like this, but I'm getting an error called 'AnyObject?' is not convertible to 'String' in the commented section:
var query = PFQuery(className:"Tags")
query.getObjectInBackgroundWithId("IsRTwW1dHY") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
let username = gameScore["username"] as! String // Error here
let tagtext = gameScore["tagtext"] as! String // Error here
} else {
println(error)
}
}
In Swift String is not an object. You need to cast NSString instead of String. Once you do you can then assign your NSString to a variable of type String.
edit following comment
You can do something like this:
if let username = gameScore["username"] as? NSString {
// If we get here, we know "username" exists, and we know that we
// got the type right.
self.username = username
}