Reputation: 25
I have a iOS Swift app that uses the camera and photo library functionalities with UIImagePicker. The user can select photos from the library or take a photo, which then will be appended into my image array. However, when the user selects the photo they want to use in the picker or presses the Use Photo button, my app takes around 2 seconds to process that picture and the picker does not dismiss until then. So I want to add an activity indicator to let the user know that the image already been selected and is undergoing processing. But I don't know how to do that. I know how to make activity indicators show and hide with UIButtons, but how do I hide the activity indicator after the processing time is done?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//Adds photo to image array
//Takes a very long time to process.
self.dismiss(animated: true, completion: nil)
}
Upvotes: 0
Views: 1421
Reputation: 47876
For users, 2 seconds is a little bit long, and for the iOS system, 2 seconds is tooooooooooooo long to occupy the main thread.
Whether you want to show an activity indicator or not, you should not call such a time-consuming task in the main thread. And doing it in a background thread is also needed to update UI elements (including show/hide/animate UIActivityIndicatorView
) properly.
Your code would become something like this:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
//UI updates needs to be done in the main thread
self.activityIndicator.startAnimating()
//Other UI updates & setups needed for mutual exclusion
}
//### In a background thread...
//Adds photo to image array
//Takes a very long time to process.
DispatchQueue.main.async {
//Reset mutual exclusion & restore UI state
self.activityIndicator.stopAnimating()
}
}
picker.dismiss(animated: true, completion: nil)
}
(Assuming UIActivityIndicatorView
is setup in the storyboard with its hidesWhenStopped
set and connected to an @IBOutlet
activityIndicator
.)
Upvotes: 1