I am loading data from an API and am using a UIProgressView to display how much has loaded.
In my viewWillAppear I use Reachability to check that there is an internet connection. Then, if there is, the following line is called 10 times in a function.
[self performSelectorInBackground:@selector(updateProgress) withObject:nil];
This then runs this method
-(void)updateProgress {
float currentProgress = myProgressBar.progress;
NSLog(@"%0.2f", currentProgress);
[loadingProg setProgress:currentProgress+0.1 animated:YES];
}
The float increments by 0.1 and the loading view displays this.
When the view is dismissed (it is a modal view) and then recalled, the method runs and the NSLog shows that the currentProgress is incrementing as it should. However, the progress bar remains empty. Does anyone know what could cause this?
For reference, I am using ARC.
Update:
This is how I am calling the API
NSString *urlString = **url**;
NSURL *JSONURL = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:JSONURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
if(connectionInProgress) {
[connectionInProgress cancel];
}
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
//This is where I call the update to the progress view
And I have these functions:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
JSONData = [NSMutableData data];
[JSONData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[JSONData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//add data to mutable array and other things
}
When you are dealing with User Interface (UI) components, you must perform the methods in the main thread. As a rule when you program, you need to set UI operations in the main thread, and heavy, complex and more performance demanding operations in background threads - this is called multithreading (as a side suggestion, would be good to read about GCD - Grand Central Dispatch. If you need to do longer operations, check this good tutorial from Ray Wenderlich.)
To solve this, you should call [self performSelectorOnMainThread:@selector(updateProgress) withObject:nil];
and then, in the method, the following:
-(void)updateProgress {
float currentProgress = myProgressBar.progress;
NSLog(@"%0.2f", currentProgress);
dispatch_async(dispatch_get_main_queue(), ^{
[loadingProg setProgress:currentProgress+0.1 animated:YES];
});
}
UI refreshes need to happen on the main thread. Change
[self performSelectorInBackground:@selector(updateProgress) withObject:nil];
to
[self performSelectorOnMainThread:@selector(updateProgress) withObject:nil waitUntilDone:NO];
来源:https://stackoverflow.com/questions/12235365/ios-uiprogressview-only-updating-once