0

(note: I'm a beginner to programming) I just have a semantic question regarding Combine. I was under the impression that Combine was always required for serial HTTP requests but while experimenting I found that the following worked just fine:

// this function works even though it depends on the output of the first HTTP request
    @available(iOS 15.0, *)
    func displayPictures(completion: @escaping ([(AsyncImage<Image>, UUID)]) -> Void) throws {
        do {
            try getPictures { urls in
                var tempImageArr = [(AsyncImage<Image>, UUID)]()
                for url in urls {
                    guard let url = URL(string: url) else {
                        print("Invalid URL")
                        return
                    }
                    let image = AsyncImage(url: url)
                    let id = UUID()
                    tempImageArr.append((image, id))
                }
                completion(tempImageArr)
            }
        } catch {
        throw NetworkError.failedToGetPictures
    }
}
    
    func getPictures(completion: @escaping ([String]) -> Void) throws {
        guard let url = URL(string: "https://randomuser.me/api/?results=10&inc=picture") else {
            print("Invalid URL")
            return
        }
        URLSession.shared.dataTask(with: url) { data, response, error in
            let decoder = JSONDecoder()
            let decodedResponse = try! decoder.decode(RandomUserModel.self, from: data!)
            completion(decodedResponse.pictures)
        }.resume()
    }

I'm hoping someone can clear up my confusion.

Thanks everyone.

pakobongbong
  • 123
  • 1
  • 9
  • 1
    You aren't really making serial HTTP requests here (I guess you are in the sense that `AsyncImage` makes a request on your behalf), but even if you were, Combine is not *required*. If this were my app, I'd store just URLs in a `@State` variable and *not* store the `AsyncImage` views -- instead, use them in the view hierarchy based on a `ForEach` with the `URL`s that you've stored. – jnpdx Oct 28 '21 at 03:52
  • 1
    Combine is a fairly new framework and Mac OS X has supported network communication long before it was named Mac OS X. `URLSession` (or `NSURLSession` depending on the language) itself is fairly recent but before combine it allowed creating data tasks using completion handlers. The older system NSURLConnection used delegates to handle networking... so you have lots of options besides Combine. – Scott Thompson Oct 28 '21 at 14:26

0 Answers0