Mathieu
Mathieu

Reputation: 71

Swift fatal error: unexpectedly found nil while unwrapping an Optional value uiimage

I've got an error while assign an UIImage to the property image of UIImageView

func connectionDidFinishLoading(connection: NSURLConnection!) {
  var err: NSError
  var jsonResult : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
  println("\(jsonResult)")
  if jsonResult.count > 0 {
    let homepage = jsonResult.objectForKey("homepage") as NSMutableDictionary
    if homepage.count > 0 {
      let imageUrl = homepage.objectForKey("url_img") as NSString
      let backgroundImageUrl = NSURL.URLWithString(imageUrl)
      let backgroundImageData = NSData(contentsOfURL: backgroundImageUrl)
      var image :UIImage = UIImage(data: backgroundImageData)
      println("\(image)")
      self.backgroundImage.image = image
    }
  }
}

It's a delegate function from a get request. backgroundImageDataand image are not nil but it doesn't work, i don't understand.

I'm a newb with Swift :s

This code work with objective-C

NSString *imageUrl = [metaData objectForKey:@"url_img"];
NSURL *backgroundImageUrl = [NSURL URLWithString:imageUrl];
NSData *backgroundImageData = [NSData dataWithContentsOfURL:backgroundImageUrl];
self.backgroundImage.image = [UIImage imageWithData:backgroundImageData];

Upvotes: 3

Views: 1471

Answers (1)

Mathieu
Mathieu

Reputation: 71

The data are good, image is not nil. The mistake wasn't on code here but where the request is done. the request need a delegate object, i thought i give it the controller but it wasn't the controller instanced, HomeController() à la place de self My bad ^^"

Upvotes: 1

Related Questions