Reputation: 569
I have a case like this: My app need to upload images to server, and i want to show the upload status to user. For example, i choose 4 images, and when app is uploading image one, the hud text lable should show "Uploading image 1/4" when upload image 2, show "Uploading image 2/4", etc. i do not want to place the upload process in the backend, so let's say the upload process is excuted in main thread. Due to this, the main thread will be blocked when upload images. So the hud thing will not work immediately. how to fix this, can anyone help? my code is like this:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[self uploadImage:i];//upload image, this would take long, will block main thread
}
Upvotes: 0
Views: 1040
Reputation: 108169
You should never perform heavy operations on the main thread, but if you really want to you can to something like
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0.001];
}
Inserting a delay will allow the NSRunLoop
to complete its cycle before you start uploading the images, so that the UI will be updated. This is because UIKit draws at the end of the current iteration of the NSRunLoop
.
An alternative would be to run the NSRunLoop
manually, for instance
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
[self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0];
}
Please not that in both examples your uploadImage:
method is now required to accept a NSNumber
instead of an int
.
Upvotes: 2