Retrieving data from parse in NSMutableArray - ios

I am retrieving data in data. This is my code..
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSArray = self.data.reverseObjectEnumerator().allObjects
self.data = array as! NSMutableArray // Getting error here.. Could not cast value of type '__NSArrayI' (0x10391c420) to 'NSMutableArray' (0x10391c4e8).
self.tableView.reloadData()
}
}
}
please somebody help me.. i m stuck here and i am beginner .

Do casting in proper way like as follows :
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSMutableArray = NSMutableArray(array: self.data.reverseObjectEnumerator().allObjects)
self.data = array as NSMutableArray
self.tableView.reloadData()
}
}

Related

Conditional cast from PFFile toPFFile always succeed

I get a warming of "Conditional cast from PFFile toPFFile always succeed" which highlighted if let tempProductPicture = self.askProductImageArray[0] as? PFFile. What is the best way to solve it? Thanks
var askProductImageArray = [PFFile]()
override func viewDidLoad() {
let query = PFQuery(className: "products")
query.whereKey("title", equalTo: labelTitleText)
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error:NSError?) -> Void in
if error != nil {
}
for object in objects! {
self.askProductImageArray.append(object.objectForKey("detailsImage") as! PFFile)
self.askTable.reloadData()
}
if let tempProductPicture = self.askProductImageArray[0] as? PFFile {
tempProductPicture.getDataInBackgroundWithBlock { data, error in
if data == nil {
} else if error != nil {
} else {
self.productPicture.image = UIImage(data: data!)
}
}
}
}
Your self.askProductImageArray is an array of type PFFIle so there is no need to do as? PFFile because swift is strongly typed language and it will hold only PFFile so remover as? PFFile at the end.
In your case you don't need to do if let at all, you just need to check if item already exist.
you can do something like this
if self.askProductImageArray.count > 0 {
let tempProduct = self.askProductImageArray[0]
// and do rest
}

Parse.com relation query with selected keys

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 {
}
}
}
}

GetDataInBackgroundWithBlock | imageData is returning a nil value

So I am saving some objects to the localDatastore using parse.
//Pin the objects here!!
var imageObject = PFObject(className: "img")
imageObject["theFile"] = imageFile
imageObject.pinInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
imageObject.saveEventually()
println("object pinned in background")
} else {
println(error)
}
})
Then in the viewDidLoad I am querying the objects and appending them into an array of PFFile's
var query = PFQuery(className: "img")
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil{
var objects : AnyObject = objects as! AnyObject
for object in objects as! [AnyObject]{
self.testImages.append(object["theFile"] as! PFFile)
}
} else {
println(error)
}
}
With this array now containing data. I am trying to insert the images into the tableView
if testImages.count >= 1{
testImages[indexPath.row].getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil{
//The app crashes here ~ fatal error: unexpectedly found nil while unwrapping an Optional value
cell.theImage.image = UIImage(data: imageData!)
} else {
println(error)
}
})
}
Because you are using a tableview, I think the best way is to download all the images from Parse and save it to an array. Then in the cellForRowAtPath method then you assign each index of that array to the cell.imageView.image
var query = PFQuery(className:"img")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let objects = objects as? [PFObject]
{
for one in objects
{
var pictureImage = one["theFile"] as! PFFile
pictureImage.getDataInBackgroundWithBlock({ (dataToget:NSData?, error:NSError?) -> Void in
if error == nil
{
if let Image = UIImage(data: dataToget)
{
// save the image to array
// reload the tableview
}
}
})
}
}
}
}

Converting PFObject (Parse) into JSON in Swift?

Is there a way to convert a PFObject from Parse into JSON? I saved as JSON, but when I try to load I'm getting [AnyObject] back. Casting to JSON won't work:
class func loadPeople() -> [String : Person] {
var peopleDictionary: [String : Person] = [:]
let query = PFQuery(className: "userPeeps")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
//this only returns the first entry, how do I get them all?
if let peopleFromParse = objects?.first?.objectForKey("userPeeps") as? JSON {
for name in peopleFromParse.keys {
if let personJSON = peopleFromParse[name] as? JSON,
let person = Person(json: personJSON) {
peopleDictionary[name] = person
}
}
}
below is my save function, which works and saves the JSON into Parse like I want:
class DataManager {
typealias JSON = [String: AnyObject]
class func savePeople(people: [String : Person]) {
var peopleDictionary = people
var peopleJSON: JSON = [:]
for name in peopleDictionary.keys {
peopleJSON[name] = peopleDictionary[name]!.toJSON()
}
let userPeeps = PFObject(className: "userPeeps")
userPeeps.setObject(peopleJSON, forKey: "userPeeps")
userPeeps.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
println("Object Uploaded")
} else {
println("Error: \(error) \(error!.userInfo!)")
}
}
}
So the answer (as Paulw11 points out above) is that "objects" is sort of a wrapper for the real data, so it was necessary to iterate through the array and store each value as JSON:
var peopleDictionary: [String : Person] = [:]
//1 load the dictionary of JSON for key people from Parse
let query = PFQuery(className: "userPeeps")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if let unwrappedObjects = objects {
for object in unwrappedObjects {
if let peopleFromParse = object as? JSON {
for name in peopleFromParse.keys {
if let personJSON = peopleFromParse[name] as? JSON,
let person = Person(json: personJSON) {
peopleDictionary[name] = person
}
}
}
}
}

Updating Objects in iOS Swift with Parse

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()
}
}
}
}
}

Resources