Last active
May 9, 2022 18:56
-
-
Save glennposadas/72b7a4f8a6a4c330f804789bf068581b to your computer and use it in GitHub Desktop.
semaphore-swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// semap | |
// | |
// Created by Glenn Posadas on 5/10/22. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
// Create 4 iamge views in the storyboard and connect them to this object. | |
@IBOutlet var imgs: [UIImageView]! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// imgs.forEach { i in | |
// i.removeFromSuperview() | |
// } | |
for index in 0...1000 { | |
queue.async { | |
semaphore.wait() | |
// defer { | |
// semaphore.signal() | |
// } | |
let t = "https://dummyimage.com/5120x1000/000000/fff&text=" + "\(index)" | |
let url = URL(string: t)! | |
URLSession.shared.dataTask(with: url) { [weak self] data, resp, err in | |
guard let self = self else { return } | |
if let data = data, | |
let image = UIImage(data: data) { | |
DispatchQueue.main.async { | |
semaphore.signal() | |
let i = self.imgs[Int.random(in: 0...3)] | |
i.image = image | |
} | |
} | |
}.resume() | |
} | |
} | |
} | |
} | |
let url = URL(string: "https://source.unsplash.com/random/5120x1000")! | |
let queue = DispatchQueue.global(qos: .background) | |
let semaphore = DispatchSemaphore(value: 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment