7ball
7ball

Reputation: 2315

Load local images into an array asynchronously on iOS

I need to load about 200 images in my bundle into an array in memory like this:

let arr = (0..<200).map({UIImage(named: "\($0).png")})

The only problem with this is it takes forever to do.. so I'd like to do it in the background and get a callback when the job finishes..

I suppose I can do it like this:

var arr = [] DispatchQueue.main.async({ arr = (0..<200).map({UIImage(named: "\($0).png")}) })

But then how would I know when the block completes? Thanks!

EDIT: I need to load of these into memory because I want animate a series of images in UIImageView like this:

let img: UIImageView()
img.animationImages = arr
img.duration = 1
img.startAnimating()

Upvotes: 1

Views: 1022

Answers (1)

Xavier Lowmiller
Xavier Lowmiller

Reputation: 1411

You can create a callback and call it after loading the images on the background thread, since the images will be loaded synchronously there.

I recommend doing something like this:

func loadImages(callback: @escaping ([UIImage]) -> Void) {
    DispatchQueue.global(qos: .background).async {
        let array = (0..<200).flatMap({ UIImage(named: "\($0).png") })
        callback(array)
    }
}

Which can be used like this (using swift trailing closure syntax):

loadImages { images in
    // do something with the images
}

You might have to dispatch the callback(array) back to the DispatchQueue.main.

Upvotes: 2

Related Questions