NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to load(read) images from an online array (folder) in SwiftUI?

Forums > SwiftUI

👋 good people.

I am pretty new in app development (SwiftUI).

I am working on a project where I would like to randomly show an image in the app but that image should be loaded from a folder that I have in Dropbox. In that folder I have 10 images and I would like the app to randomly show 1 out of 10 images that are stored in a folder on Dropbox.

Currently I can only show one image from URL.

Any ideas, hints how to do this?

Thank you!

   

Post the code you have that is not working.

   

Thank you for your reply. Here is my code so far:

This is Swift "model":

import UIKit
import Firebase
import FirebaseStorage
import FirebaseFirestore

struct Database {

    // 3. Random image from Firebase storage and download photo from Firebase Storage
    func randomImage(completion: @escaping (UIImage?) -> Void) {
        // 1. Dobi listo vseh fotk v Firebase folderju
        listAllFiles { (list) in
            if list.isEmpty {
                // Error
                print("List is empty!")
                completion(nil)
            } else {
                let radnomElement = list.randomElement()!
                downloadImage(fromURL: radnomElement) { (image) in
                    completion(image)
                }
            }

        }
    }

    // 1. Get list of all photos from Firebase storage

    func listAllFiles(completion: @escaping ([String]) -> Void) {

        let storage = Storage.storage()

        let storageReference = storage.reference()
        storageReference.listAll { (result, error ) in
            var list: [String] = [] // ["BillGates.jpg"]
            if let error = error {
                print("An error has occurred - \(error.localizedDescription)")
            } else {
                for item in result.items {
                    let downloadURL = item.name
                    list.append(downloadURL)
                }
            }
            completion(list)
        }
    }

    // 2. Download photo from Firebase storage

    private func downloadImage(fromURL: String, completion: @escaping (UIImage?) -> Void) {
        Storage.storage().reference().child(fromURL).getData(maxSize: 1 * 1024 * 1024) {
            (imageData, error) in
            if let error = error {
                print("An error has occurred - \(error.localizedDescription)")
                completion(nil)
            } else if let imageData = imageData {
                let downloadedImage = UIImage(data: imageData)
                completion(downloadedImage)
            } else {
                print("Could not unwrap image data")
                completion(nil)
            }
        }
    }

    // Download quote from Firebase folder

}

And this is a "Quote view":

import SwiftUI

struct QuoteView: View {
    let quote: Quote

    var body: some View {
        ZStack {
            Image(uiImage: quote.image)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(height: 280, alignment: .center)
                .clipped()
                .blur(radius: 2.0)

            Text(quote.text)
                .foregroundColor(.white)
                .minimumScaleFactor(0.2)
        }

    }
}

And this is a "Content view":

import SwiftUI
import FirebaseStorage
import FirebaseFirestore
import Firebase

struct ContentView: View {

    @State private var quoteView = QuoteView(quote: Quote.loading)
    @ObservedObject private var quotesViewModel = QuotesViewModel()

    func loadQuote() {
        let randomText = quotesViewModel.quotes.randomElement()?.text ?? "Loading..."
        self.quotesViewModel.fetchData()

        Database().randomImage { image in
            let downloadedQuote = Quote(text: randomText, image: image ?? UIImage(named: "businessMan")!)
            quoteView = QuoteView(quote: downloadedQuote)
        }
    }

    var body: some View {
        NavigationView {
            VStack {

                quoteView.onAppear() {
                    loadQuote()
                }

                Button("Refresh") {
                    loadQuote()
                }
            }
            .navigationBarTitle("Business")
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

   

Getting The Same Issue With Me I Am Also Looking For The Solution About This Youtube

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.