Search code examples
swifttabsimageviewviewdidload

Image appears at second time I`m openig tab (Swift)


I'm getting an image from the web, then I want to add it into ImageView which is on the form. Everything working but I can see an image on the form only on the second time I'm opening it's tab. So I must open tab I need, then open other one (random) and then back to tab I need.

I've recorded a short video to show what am I telling about http://youtu.be/h8iDzNqSXV4

Here is my code

override func viewDidAppear(animated: Bool) {

    var imageViewObject :UIImageView

    imageViewObject = UIImageView(frame:CGRectMake(50, 100, 100, 100)) //x,y,width,height
    let link=NSURL(string: "http://ipic.su/img/img7/fs/ProdukciyaApple.1438079721.png")
    getDataFromUrl(link!){result in
        imageViewObject.image = UIImage(data: result!)
    }
     self.imageView.addSubview(imageViewObject)
     self.imageView.sendSubviewToBack(imageViewObject)

}



 func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {

    NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in

        completion(data: data)

        }.resume()

}

How should I fix it? Apperciate any help


Solution

  • Typically, the code you have in your viewDidAppear should go in the viewDidLoad function as you want it to occur before the view is visible. I'm not able to test atm, but this should fix the issue.