3

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];
Mathieu
  • 71
  • 5
  • You really need to start using swift to it's full potential. If you might not always have an image you should be using: `if let image = UIImage(data: backgroundImageData) { self.backgroundImage.image = image `} If image is definitely not nil then all I can suggest is to maybe try not calling the var image? In previous betas of Xcode I occasionally ran into problems with naming variables the same as properties. – simonthumper Oct 20 '14 at 17:17
  • 1
    This is an issue where prior to XCode 6.1, initializers cannot return optional values, and you're using two different initializers here, for both the data and the image. I would try to immediately cast these to optionals with `as Data?` and `as UIImage?` and see what you get. – cmyr Oct 20 '14 at 17:35
  • What does it print when you log image ? Have you added the image view correctly as a subview ? check the backgroundImage's frame. check it's superview. have you hooked it up correctly ? have you checked whether it is the correct Url ? color the backgroundview to make sure it is correctly added and has the correct size. And please show how you set up the backgroundImage property. – the_critic Oct 20 '14 at 17:37

1 Answers1

1

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 ^^"

Mathieu
  • 71
  • 5