8

In my app I am checking to see whether a post has a picture or not.

For this I am using:

if pictures[string]? != nil {
    if var image: NSData? = pictures[string]? {
        imageView.image = UIImage(data: image!)
    }
}

However, it still comes up with the error:

fatal error: unexpectedly found nil while unwrapping an Optional value.

I'm sure it is something easy to fix but I am quite new to this - what am I doing wrong?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Ben Gray
  • 150
  • 1
  • 2
  • 8

4 Answers4

14

Try doing it this way:

if let imageData = pictures[string] {
    if let image = UIImage(data: imageData) {
        imageView.image = image
    }
}

Assuming that string is a valid key.

You are dealing with optionals, so conditionally unwrap each return object before using it.

Forced unwrapping is dangerous and should only be used when you are absolutely sure that an optional contains a value. Your imageData may not be in the correct format to create an image, but you are forcibly unwrapping it anyway. This is okay to do in Objective-C as it just means nil objects get passed around. Swift is not so tolerant.

Anorak
  • 3,096
  • 1
  • 14
  • 11
1

It is the issue of swift when you forget to wrap optional values

Replace line imageView.image = UIImage(data: image!) with imageView?.image = UIImage(data: image!)

Yogesh Solanki
  • 487
  • 5
  • 12
0

I faced the same problem with this code

if(!placeholderColor.isEqual(nil))
 {
   self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : placeholderColor])
 }

and solved by this

if let placeColor = placeholderColor
 {
   self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : placeColor])
 }
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84
0

First Double check the format of the base64 string. My string had the following format: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAZDElEQVR42u1daWATZRp+JkfT+76g90ELtKUX5wICshREgYKCKAiCC4iCu+Iq6q6CoKuLF4Igl6jLDaKgiJwiN5SjQAulpTe97zY90qRJ9sc but everthing before the the comma is not required. I got the code working by changing the format to:
iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAZDElEQVR42u1daWATZRp+JkfT+76g90ELtKUX5wICshREgYKCKAiCC4iCu+Iq6q6CoKuLF4Igl6jLDaKgiJwiN5SjQAulpTe97zY90qRJ9sc

Lone Ronin
  • 2,530
  • 1
  • 19
  • 31