UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

3      

Post the code you have that is not working.

3      

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()
    }
}

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.