0

I want to display on "Profile" cell the image of the user. To do that I supposed to use the same snippet that solve the profile load.

First of all I declared an UIImageView! variable:

var accountimage: UIImageView!

Then, in my cellForRowAtIndexPath I downloaded by UserDefaults constructor the Avatar:

if indexPath.row == 1 {
    cell.backgroundColor? = UIColor(red: 236/255,green: 239/255,blue: 240/255,alpha: 1)
    let myFont: UIFont? = UIFont(name: "Avenir Next Condensed", size: 22.0)
    if let aFont = myFont {
        cell.textLabel?.font = aFont
        //load account image
        if UserDefaults.standard.object(forKey: "profile_avatar") != nil{
            let decoded  = UserDefaults.standard.object(forKey: "profile_avatar") as! Data
            let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded)
            accountimage.image = decodedTeams as? UIImage
            cell.imageView?.image = accountimage.image
        } else
        {
            accountimage.image = #imageLiteral(resourceName: "user.png")
            cell.imageView?.image = accountimage.image
        }
}
}

Debugger says this on accountimage.image = decodedTeams as? UIImage line:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value


Edit

Here a screen of my Main.Storyboard in case should be helpful:

Main.Storyboard

  • `let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data` are you **sure** this isn't `nil`? If that's not the case, you should use `as?` instead of `as!`. – Alejandro Iván May 25 '18 at 14:36
  • I maked a condiction.. In any case if I haven't an image setted, There's a default image to solve the nil. – Gianluca Caliendo May 25 '18 at 14:41

1 Answers1

0

Maybe you made a small mistake on this code let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data **as!**means forced conversion but may fail.

SolinLiu
  • 209
  • 1
  • 8
  • If I do this the debbugger says: "Value of optional type 'Data?' not unwrapped; did you mean to use '!' or '?'?" on 'decodedTeams' line. So I do as xcode tell me to do and use value '(decoded)' to (decoded!). In the end The result is the same: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" – Gianluca Caliendo May 25 '18 at 15:48
  • I also tryied to keep 'as!' on "accountimage.image = (decodedTeams as! UIImage)" but The result is the same: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" – Gianluca Caliendo May 25 '18 at 15:55
  • 1
    Just make a change and check where is the error,try this ```let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as? Data if let data = decoded { //first check let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: data) as? UIImage if let image = decodedTeams { // second check } }else { } ``` – SolinLiu May 25 '18 at 16:07