Problems with saving data from parse.com in a String - ios

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
}

Related

Cloud Firestore Swift: How to display number field in label

I have a number field from Cloud Firestore that needs to be displayed as a string within a label.
Usually, if the field were a string, I can just execute this code
db.collection("users").document(uid ?? "UID not yet loaded in viewDidLoad()")
.addSnapshotListener { snapshot, error in
if error != nil {
print(error ?? "Couldn't update text field TextUser according to database")
} else {
if let dbUsername = snapshot?["username"] as? String {
self.textUser?.text = dbUsername
}
That works because "username" in the document is of a value string.
But this won't work because "cash" in the document is of a value number.
if let dbCash = snapshot? ["cash"] as? String {
self.labeCash?.text = dbCash
}
I might just have to convert the number, whatever type they use, into a string. But how would I do that? Thanks!
Can you try
if let dbCash = snapshot? ["cash"] as? NSNumber {
self.labeCash?.text = dbCash.stringValue
}

converting AnyObject to String in swift not working

I make POST request to the server from my app, and I get jsonString as the response. I have made function to convert string to dictionary which looks like this:
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
after getting the response from the server I convert the string to dictionary by function and then I want to check if user is logged in:
let result = convertStringToDictionary(jsonString as String)
if (result!["loggedIn"] == "1")
{
print("You are logged in!")
}
And then I get the error "Cannot convert value of type AnyObject? to expected argument String". I suppose I have to convert variable of type AnyObject to String if i want to compare it to string. I have tried every option which I have found on the Google but I havent got it to work.
Because result is a dictionary of type [String : AnyObject], the values you extract from it will be typed as AnyObject?, which has no valid operator overload for == with a String. You need to cast the extracted value to a String before you can compare it to "1".
What you probably want is something like:
if let result = convertStringToDictionary(jsonString as String),
loggedIn = result["loggedIn"] as? String
where loggedIn == "1" {
print("You are logged in")
}
Note that if your JSON has the "loggedIn" field as an Integer, like:
{
"loggedIn" : 1
}
You would want to cast loggedIn as Integer, not String.
You have to tell the compiler that the expected type is a String
if let loggedIn = result?["loggedIn"] as? String where loggedIn == "1" { ...

how to retrive data from a user pointer on Parse using swift

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.

AnyObject is not convertible to String using swift

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

Query Pointer in Parse (ios)

I am doing a query and I am checking to see if the value in the column "Parent", which is a pointer, is equal to a string, newLogObjectId. I obviously cannot do this since a pointer and a string are a different value type, (returns nil). How do I compare a string to a string in a pointer?
//A string, for example, "MCeKMyxRIt"
let newLogObjectId = objectIdArray[markerIndex]
let query1 = PFQuery(className: "ComparablePhotos")
//"Parent" is a pointer referencing an objectId in another class. "newLogObjectId" is a string How do I check to see if the String of Parent is equal to newLogObjectId, a string?
query1.whereKey("Parent", equalTo:newLogObjectId)
Pointers in Parse don't point to a value, they point to a class (a PFObject). So it looks like your pointer named Parent is pointing to the Parse class NewLog. I'm assuming then the string you are wanting to check is a field in the class NewLog. Also, to include the pointer in the query, use query1.includeKey("PointerName"). Try this:
let newLogObjectId = objectIdArray[markerIndex]
let query1 = PFQuery(className: "ComparablePhotos")
query1.includeKey("Parent")
query1.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
if (error == nil){
if let comparablePhotos = objects as? [PFObject]{
for photo in comparablePhotos {
if let parentPointer:PFObject = photo["Parent"] as? PFObject{
if(parentPointer["columnWithString"] as! String == newLogObjectID){
// Do something
}
}
}
}
}else{
println(error)
}
})

Resources