Here is my code:
-(IBAction)saveDownloadedImage
{
NSLog(#"Test"); EXECUTED
indicatorView.hidden = NO; NOT EXECUTED
[indicatorView startAnimating]; NOT EXECUTED
[statusLabel setText:#"WHY?"]; NOT EXECUTED
[currentPicture setImage:[imageView image]]; EXECUTED
ImageFileManager *fileManager = [[ImageFileManager alloc] init]; EXECUTED
[fileManager saveImageToDisk:currentPicture]; EXECUTED
indicatorView.hidden = YES;
[statusLabel setText:#"Image saved successfully."]; EXECUTED
saveButton.enabled = NO; EXECUTED
}
The proccess of saving takes about 5 seconds. So it would be normal to see the indicator in the UI. But nothing happens! Any idea?
Everything is executed. Your problem is that the saveImageToDisk call is synchronous and you are calling it from the UI thread. When you are blocking the UI thread, nothing is ever repainted. The indicator is shown but it cannot be drawn to the screen until the IBAction returns when it will have been hidden again.
You have to call the saving method asynchronously.
Blocking UI thread is never a good idea.
Edit: see the answer for the following question for the correct solution: asynchronous calls to database in ios
Edit2: One of the possible solutions (not tested)
-(IBAction)saveDownloadedImage {
indicatorView.hidden = NO; //Note you can use hidesWhenStopped property for this
[indicatorView startAnimating];
[statusLabel setText:#"BECAUSE..."];
[currentPicture setImage:[imageView image]];
[NSThread detachNewThreadSelector:#selector(save) toTarget:self withObject:nil]
}
- (void)save {
#autoreleasepool {
ImageFileManager *fileManager = [[ImageFileManager alloc] init];
[fileManager saveImageToDisk:currentPicture];
[self performSelectorOnMainThread:#selector(updateUI) withObject:nil waitUntilDone:NO];
}
}
- (void)updateUI {
indicatorView.hidden = YES;
[statusLabel setText:#"Image saved successfully."];
saveButton.enabled = NO;
}
Are you sure that
1) indicatorView and statusLabel are not null, and
2) indicatorView and statusLabel are added as subviews to self.view?
In My Perception your are starting the Activity Indicator main Thread.
Instead Showing the Indicator on main thread
you should call Indicator on seperate Thread as Below.
-(IBAction)saveDownloadedImage
{
NSLog(#"Test"); EXECUTED
commented below code
//indicatorView.hidden = NO; NOT EXECUTED
// [indicatorView startAnimating]; NOT EXECUTED
//instead of main thread create new Thread as Below
[NSThread detachNewThreadSelector:#selector(showloader) toTarget:self withObject:nil];
[statusLabel setText:#"WHY?"]; NOT EXECUTED
[currentPicture setImage:[imageView image]]; EXECUTED
ImageFileManager *fileManager = [[ImageFileManager alloc] init]; EXECUTED
[fileManager saveImageToDisk:currentPicture]; EXECUTED
[statusLabel setText:#"Image saved successfully."]; EXECUTED
saveButton.enabled = NO;
[indicatorView stopAnimating:YES];
indicatorView.hidden = YES;
}
//Custome method For shoing the Indicator.
-(void)showloader{
//call below method here indicatorView object created already.
[indicatorView startAnimating]
}
It'll definitely work
You need to declare your method with a sender like this
-(IBAction)saveDownloadedImage:(id)sender
Related
I use ZXing for an app, this is mainly the same code than the ZXing original code except that I allow to scan several time in a row (ie., the ZXingWidgetController is not necesseraly dismissed as soon as something is detected).
I experience a long long freeze (sometimes it never ends) when I press the dismiss button that call
- (void)cancelled {
// if (!self.isStatusBarHidden) {
// [[UIApplication sharedApplication] setStatusBarHidden:NO];
// }
[self stopCapture];
wasCancelled = YES;
if (delegate != nil) {
[delegate zxingControllerDidCancel:self];
}
}
with
- (void)stopCapture {
decoding = NO;
#if HAS_AVFF
if([captureSession isRunning])[captureSession stopRunning];
AVCaptureInput* input = [captureSession.inputs objectAtIndex:0];
[captureSession removeInput:input];
AVCaptureVideoDataOutput* output = (AVCaptureVideoDataOutput*)[captureSession.outputs objectAtIndex:0];
[captureSession removeOutput:output];
[self.prevLayer removeFromSuperlayer];
/*
// heebee jeebees here ... is iOS still writing into the layer?
if (self.prevLayer) {
layer.session = nil;
AVCaptureVideoPreviewLayer* layer = prevLayer;
[self.prevLayer retain];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 12000000000), dispatch_get_main_queue(), ^{
[layer release];
});
}
*/
self.prevLayer = nil;
self.captureSession = nil;
#endif
}
(please notice that the dismissModalViewController that remove the view is within the delegate method)
I experience the freeze only while dismissing only if I made several scans in a row, and only with an iPhone 4 (no freeze with a 4S)
Any idea ?
Cheers
Rom
According to the AV Cam View Controller Example calling startRunning or stopRunning does not return until the session completes the requested operation. Since you are sending these messages to the session on the main thread, it freezes all the UI until the requested operation completes. What I would recommend is that you wrap your calls in an Asynchronous dispatch so that the view does not lock-up.
- (void)cancelled
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self stopCapture];
});
//You might want to think about putting the following in another method
//and calling it when the stop capture method finishes
wasCancelled = YES;
if (delegate != nil) {
[delegate zxingControllerDidCancel:self];
}
}
I am accessing the photo library on the iphone and it takes a long time to import the pictures i select in my application, how do i run the process on a secondary thread , or what solution do i use to not block the user interface?
I did a full explanation with sample code using performSelectOnBackground or GCD here:
GCD, Threads, Program Flow and UI Updating
Here's the sample code portion of that post (minus his specific problems:
performSelectorInBackground Sample:
In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
[self performSelectorInBackground:#selector(performLongRunningWork:) withObject:nil];
}
- (void)performLongRunningWork:(id)obj
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
[self performSelectorOnMainThread:#selector(workDone:) withObject:nil waitUntilDone:YES];
}
- (void)workDone:(id)obj
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
GCD Sample:
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
Use an asynchronous connection. It won't block the UI while it does the fetching behind.
THIS helped me a lot when I had to do download images, lot of them.
One option is use performSelectorInBackground:withObject:
[progressind startAnimating];
[self performSelectorOnMainThread:#selector(methodgoeshere:) withObject:[NSDictionary dictionaryWithObjectsAndKeys: aURL, #"aURL", aURL2, #"aURL2", nil]
waitUntilDone:YES ];
[progressind stopAnimating];
[navigationController pushViewController:vFullscreen animated:YES];
In the methodgoeshere, i have a UIImageview which i fill with the image once its downloaded but the problem is, the activityprogress is not working as i thought, it doesnt spin.
You need to do your image loading in a new background thread. performSelectorOnMainThread calls the method on the main thread, not a background thread so that's why it's blocking.
To call your image loading method in a background thread:
[progressind startAnimating];
[NSThread detachNewThreadSelector:#selector(methodgoeshere:) toTarget:self withObject:[NSDictionary dictionaryWithObjectsAndKeys: aURL, #"aURL", aURL2, #"aURL2", nil]];
Then in methodgoeshere you load your image. Once the image is done loading then you call a method on the main thread to let it know you're done and to stop the activity progress indicator.
- (void) methodgoeshere:(...)... {
// <Load your image here>
// Then tell the main thread that you're done
[self performSelectorOnMainThread:#selector(imageDoneLoading) withObject:nil waitUntilDone:YES ];
}
- (void)imageDoneLoading {
[progressind stopAnimating];
// Do other stuff now that the image is loaded...
}
I'm trying to add a progress meter, or other "I'm busy right now" notification to my view hierarchy right before doing some intense computation that will block the UI. My code looks some thing like:
//create view
[currentTopView addSubView:imBusyView];
//some initialization for the intense computation
[computation startComputing];
Unfortunately, my progress meter doesn't display until after the computation completes. It appears like the views aren't re-drawn until the run loop completes. I'm pretty sure that setNeedsDisplay and setNeedsLayout will also wait until the run loop completes.
How do I get the view to display immediately?
Redrawing only occurs when your code returns control to the run loop. So the easiest way would be for you to schedule the startComputing call with a zero delay. That way, it will be executed during the next run loop iteration (right after redrawing):
[computation performSelector:#selector(startComputing) withObject:nil afterDelay:0.0];
Be aware, though, that unless you do your computation in another thread you will not be able to update the UI during the computation.
If you are doing heavy calculations maybe spawning a new thread is a good idea.
Here I have an activityIndicator displayed and starts a large XMLParse operation in a background thread:
- (void) setSearchParser {
activityIndicator = [[ActivityIndicatorView alloc] initWithActivity];
[self.view addSubview:activityIndicator];
[NSThread detachNewThreadSelector:#selector(getSearchResults:) toTarget:self withObject:[searchParser retain]];
}
then the getSearchResults method:
- (void) getSearchResults: (SearchResultParser *) parser {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[parser startParser];
[self performSelectorOnMainThread:#selector(searchResultsReady:) withObject:[parser data] waitUntilDone:NO];
[pool release];
}
So firstly make a new thread:
[NSThread detachNewThreadSelector:#selector(getSearchResults:) toTarget:self withObject:[searchParser retain]];
this means that all code inside the getSearchResults will be executed on a different thread. getSearchResults also get's passed a parameter of "searchParser" thats a large object that just needs startParse called on it to begin.
This is done in getSearchResults. When the [parser startParser] is done, the results is passed back to the main thread method called "searchResultsReady" and the threads autorelease pool is released.
All the time it took from my parser began to it had finished, a gray view covered the screen an an activityIndicator ran.
You can have the small activityIndicator class I wrote:
-(id) initWithActivity {
[self initWithFrame:[self bounds]];
[self setBackgroundColor:[UIColor blackColor]];
[self setAlpha:0.8];
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center = CGPointMake(160, 240);
[self addSubview:activityView ];
[activityView startAnimating];
return self;
}
- (void) dealloc {
[activityView release];
[super dealloc];
}
Hope it helps you out, even though threads seems a bit confusing, they can help to make the UI not freeze up, which is especially important on the iPhone.
all! I want to create multiple threads in my application. I' using following code for creating a thread.
This' buttonPress method where I'm creating a thread:
- (void) threadButtonPressed:(UIButton *)sender {
threadStartButton.hidden = YES;
threadValueLabel.text = #"0";
threadProgressView.progress = 0.0;
[NSThread detachNewThreadSelector:#selector(startMethod) toTarget:self withObject:nil];
}
This' where I'm calling the method for the thread:
- (void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(threadMethod) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)threadMethod {
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:#"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else
threadStartButton.hidden = NO;
}
This thread works properly.
But when I try to create another thread in the same class using the same method, it gets created properly, but at the method "performSelectorOnMainThread", it doesn't execute that method. Can anybody please help me?
It seems that you are trying to queue up methods to be executed on the main thread. You might want to look into an NSOperationQueue and NSOperation objects. If you want to proceed on this path, you might consider changing the repeats parameter to YES. The problem seems to be that the main thread is busy when it's being passed this message. This will cause the main thread to block. You may also consider not using a second threadMethod and calling back to the main thread, but instead wrapping the contents of threadMethod in an #synchronized(self) block. This way, you get the benefits of multi-threading (multiple pieces of code executing at the same time and thus a reactive user interface) without doing some weird stuff with the main thread.
I'm missing the context here. I see a call that creates a new thread, and then I see a call that performs a selector (calls a method) on the main thread..
As I understand, you are calling a function in a new thread (entryMethod), in which you call a method to perform on the main thread (myMethod). I do not understand the point of this, without some background info and possibly some code.
Is it possible that the main thread is busy performing the 'myMethod' function, and thus does not respond to other calls?
Why cant you do it with the same call, by replacing
-(void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(threadMethod) withObject:nil waitUntilDone:NO];
[pool release];
}
with
-(void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:#"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else
threadStartButton.hidden = NO;
}
[pool release];
}