Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals - ios

I am saving a parse query to a array but i ket the following error on if let objects = objects as? [PFObject]
And the following error happens Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals.
any one know how to solve this?
func getArray(funcstring: String){
var userGeoPoint: PFGeoPoint
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if error == nil {
userGeoPoint = geoPoint!
}
}
var searchQuery: [String] = [String]()
var query = PFQuery(className:"User")
query.whereKey("geoLocation", nearGeoPoint:userGeoPoint)
query.limit = 100
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
} else {
print("\(error?.userInfo)")
}
}
}

objects is declared as [PFObject]?.
You're going to downcast the object to something the compiler already knows.
Just check for nil
if let unwrappedObjects = objects {
for object in unwrappedObjects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
or still "swiftier"
if let unwrappedObjects = objects {
self.searchQuery = unwrappedObjects.map{ $0["objectId"] as! String }
}

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

iOS and Parse throwing exception: "unexpectedly found nil"

I'm doing some iOS app on Xcode 6.4 where I'm using Parse as a back-end, and everything is going fine until I try to add the Parse gotten messages from objects to an staring array.
The error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The thing is I do not know what nil is it talking about as I have unwrapped all the values or at least I think so, help??
Code:
var mensajes:[String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
println("\(PFUser.currentUser()!.username!)")
menuLabel.text = "Bienvenido \(PFUser.currentUser()!.username!)"
/*
var query = PFQuery(className: "Alumnos")
query.whereKey("nombre", hasSuffix: "1")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error")
println("we have \(objects!.count)")
if let object = objects as? [PFObject] {
for obj in object {
println("\(obj.objectId) ----")
println(obj)
println(obj["nombre"] as! String + "*****")
}
}
} else {
println("a misterious error has appeared \(error!) \(error!.description)")
}
} */
var avisosQuery = PFQuery(className: "Alumnos")
if let papa = PFUser.currentUser() {
avisosQuery.whereKey("userId", equalTo: papa)
avisosQuery.findObjectsInBackgroundWithBlock {
(alumnos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No Error we have \(alumnos?.count) students")
var grupos: PFObject? = nil
if let obj = alumnos as? [PFObject] {
for alum in obj {
println(alum["nombre"])
//println(alum["grupoId"])
//println(alum)
grupos = alum["grupoId"] as? PFObject
println(grupos!)
var secondQuery = PFQuery(className: "Avisos")
secondQuery.whereKey("grupoId", equalTo: grupos!)
secondQuery.findObjectsInBackgroundWithBlock {
(avisos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error we are home free \(avisos?.count)")
if avisos?.count > 0 {
if let avisoArray = avisos as? [PFObject] {
for av in avisoArray {
println(av["texto"]!)
if let msg: AnyObject = av["texto"] {
println(msg)
self.mensajes.append(msg as! String)
}
}
}
}
} else {
println("something got busted, mate")
}
}
}
}
} else {
println("we screw something up")
}
}
}
}
And I'm in the learning stage with Parse, that why this is in the viewDidLoad() I'm just trying some things.
if let papa = PFUser.currentUser()
The problem is in that line we are not get the userid so technically you are looking for a null value
Right Code :
let papa = PFUser.currentUser().objectId
Try it

Retrieving data from parse in NSMutableArray

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

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