Tarvo Mäesepp Tarvo Mäesepp - 29 days ago 17
Swift Question

Can not cast value of type NSTaggedPointerString to NSDictionary

I am trying to assign Firebase values to my struct:

var productsArray = [Product]()
however I have a little error:


Could not cast value of type 'NSTaggedPointerString' to
'NSDictionary'.


I know that I can't assign them directly so that is why I am casting like this:

self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String


And converting:

func toAnyObject() -> [String: Any] {

return ["Products": snusProductTitle as Any]
}


Like this I append:

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
ref.observeSingleEvent(of: .childAdded, with: { (posts) in
self.productsArray.removeAll()
var newPostsArray = [Product]()
for post in posts.children {
print(posts.value)//Look below image
let newPost = Product(snapshot: post as! FIRDataSnapshot)
newPostsArray.insert(newPost, at: 0)
}

self.productsArray = newPostsArray
self.tableView.reloadData()

}) { (error) in
print(error.localizedDescription)
}


And this is minimal Product structure:

class Product: NSObject {
var snusProductTitle: String!


var ref: FIRDatabaseReference?

init(snusProductTitle: String) {
self.snusProductTitle = snusProductTitle
self.ref = FIRDatabase.database().reference()
}



init(snapshot: FIRDataSnapshot){
self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String
}

func toAnyObject() -> [String: Any] {
return ["Products": snusProductTitle as Any]
}
}


enter image description here

While googling, I couldn't find any solution.

Answer

.childAdded gives FIRDataSnapshot at a time ... so no need to loop for this .. you just need to pass the current child in your structure.

 self.productsArray.removeAll()
 var newPostsArray = [Product]()  

 let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
    ref.observe(FIRDataEventType.childAdded, with: { (posts) in

        let newPost = Product(snapshot: posts as! FIRDataSnapshot)
        newPostsArray.insert(newPost, at: 0)

        self.productsArray = newPostsArray
        self.tableView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
    }
Comments