JSQMessageAvatarImageFactory error

197 views Asked by At

For some reason I am getting an crash and I am not sure why. Everything is being pulled from FIRBase correctly. But when trying to load the user url I get a crash

printed(snapshot)

["MediaType": TEXT, "text": Test Message, "senderId": KG7b3tDTaoMwcAQAi2JI8vjj0OB2, "senderName": user1]
Optional({
email = "[email protected]";
id = KG7b3tDTaoMwcAQAi2JI8vjj0OB2;
profileImage = "gs://big-pen.appspot.com/profileImage/KG7b3tDTaoMwcAQAi2JI8vjj0OB2";
username = user1;})

My error

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

Here is my code.

func observeUsers(id: String){
       FIRDatabase.database().reference().child("people").child(id).observeEventType(.Value, withBlock: { snapshot in
        print(snapshot.value)
        if let dict = snapshot.value as? [String: AnyObject] {
            let avatarUrl = dict["profileImage"] as! String

            //call the setupAvatar function
            self.avatar(avatarUrl, messageId: id)

        }
    })
}


func avatar(url: String, messageId: String){

    if DataService.dataService.currentUser != nil{
        if url != "" {
        let fileURL = NSURL(string: url )
        let data  = NSData(contentsOfURL: fileURL!)
        let image = UIImage(data:data!)  //<-----I am getting an error at this line error code: "Thread1:EXC_BAD_INSTRUCTION(code=Exc_I386_INVOP, subcode=0x0)"
        let userImg = JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: 30)
            avatarDict[messageId] = userImg
        }else{    
        JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named: "cam_w.png"), diameter: 30)
    }
    collectionView.reloadData()
    }
}

override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
    let message = messages[indexPath.item]

    return avatarDict[message.senderId]
    //return JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named: "cam_w.png"), diameter: 30)
}

Thanks. I have been stuck on this for two days now.

1

There are 1 answers

3
Federico Malagoni On BEST ANSWER

Maybe it is not a valid URL so to check it change your avatar func to:

func avatar(url: String, messageId: String){

    if DataService.dataService.currentUser != nil{
        if let fileURL = NSURL(string: url ),
              data  = NSData(contentsOfURL: fileURL) {

        let image = UIImage(data:data!)  //<-----I am getting an error at this line error code: "Thread1:EXC_BAD_INSTRUCTION(code=Exc_I386_INVOP, subcode=0x0)"
        let userImg = JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: 30)
            avatarDict[messageId] = userImg
        }else{    
        JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(named: "cam_w.png"), diameter: 30)
    }
    collectionView.reloadData()
    }
}