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
Related
This is my initialisation of the array:
var restaurantsArray = [String]()
Here is the query function:
func loadRestaurants(){
let fetchRestaurantsQuery = PFQuery(className: "Restaurants")
fetchRestaurantsQuery.findObjectsInBackgroundWithBlock{ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil{
//after successfull fetch
print("b")
if let fetchedRestaurants = objects{
print("c")
for fetchedRestaurant in fetchedRestaurants{
print("a")
self.restaurantsArray.append(fetchedRestaurant.objectForKey("Name") as! String)
print(fetchedRestaurant.objectForKey("Name") as! String)
}
}
}else{
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
For some reason, the code in the for-loop is never called. Any suggestions to fix this?
Since objects is declared as optional [PFObject]? the proper optional binding syntax is just
if let fetchedRestaurants = objects {
and fetchedRestaurant in fetchedRestaurant is pretty weird.
for fetchedRestaurant in fetchedRestaurants {
My Question is very simple,
I'm Learning iOS development and I'm stuck with tableviewcontroller
I can add Values to tableview with array, but when I try to append value from Parse, it's not working.
Here is the code:
var names: [String] = ["Name_one", "Name_two"]
let query: PFQuery! = PFUser.query()
override func viewDidLoad() {
super.viewDidLoad()
query.whereKey("objectId", notEqualTo: PFUser.currentUser()!.objectId!)
query.findObjectsInBackgroundWithBlock { objects, error in
if (error == nil) {
for user: PFUser in (objects as! [PFUser]) {
self.names.append(user.username as! String)
}
} else {
print("Error")
}
}
Screen Shot Attachment
You must to reload your tableview after get data finished
Code:
query.findObjectsInBackgroundWithBlock { objects, error in
if (error == nil) {
for user: PFUser in (objects as! [PFUser]) {
self.names.append(user.username as! String)
}
yourTableview.reloadData()
} else {
print("Error")
}
}
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 }
}
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 {
}
}
}
}
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()
}
}
}
}
}