0

I am new in swift. Who can help? I have array with 3 links how can i take one link from this array and show in UIImageView then second link and then third? I make with one link but not understand how i can make with array. Thnx.

class ViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        var image = UIImage()
        var imageData: Data?
        let links = ["http://s.ill.in.ua/i/gallery/950x0/2694/146192.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146190.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146202.jpg"]
        let url = URL(string: links[0])
        do {
            imageData = try Data(contentsOf: url!)
        }
        catch {
            print("error")
        }
        if let value = imageData {
            image = UIImage(data:value)!
            imgView.image = image
        }
    }

}
Ivan Nesterenko
  • 939
  • 1
  • 12
  • 23
  • If you display all 3 links one after another in the image view you will see only the last one, the computer is too fast. Btw: **Never** use synchronous methods like `Data(contentsOf` to load data from a remote `URL` and never use data which can fail in a `do` block after the `do-catch` expression. Put all *good* code in the `do` scope and remove the optional binding. – vadian Jun 18 '17 at 17:37
  • i understand that but i can used maybe DispatchQueue for delay – Artem Boldyriev Jun 18 '17 at 17:47
  • Use this link to load image from server easily : https://stackoverflow.com/a/37019507/3400991 – Shobhakar Tiwari Jun 18 '17 at 17:51

2 Answers2

0

You can easily iterate through array like this:

for link in links {
    // This will iterate through array, so you can do something specific on each step
    let url = URL(string: link)
    do {
        imageData = try Data(contentsOf: url!)
    }
    catch {
        print("error")
    }
    if let value = imageData {
        image = UIImage(data:value)!
        imgView.image = image
        print("Updated imageView with \(link)!")
    }
}
Ivan Nesterenko
  • 939
  • 1
  • 12
  • 23
0

Just use this way :

 let links = ["http://s.ill.in.ua/i/gallery/950x0/2694/146192.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146190.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146202.jpg"]

Take three different ImageView ( for a while ) or u can use tableview to show image and use following link : https://stackoverflow.com/a/37019507/3400991

for linkValue in links {
   yourimageview.imageFromServerURL(urlString: linkValue as! String)
}

this is one of the way u can show image into your imageview.

Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71