Detecting when MapView tiles are displayed - iphone

Since - (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView is not called when the tiles are loaded from cache, is there a way to know when all the tiles have been loaded (either from cache or from the mapping servers) and displayed?
Is there any delegation that intimates that tiles have been loaded ?

Here is some source code I wrote: https://github.com/jonathanlking/mapViewTest
Why don't you think about the problem like this;
When the map view will change, mapView:regionDidChangeAnimated: will be called.
From there mapViewWillStartLoadingMap: will be called.
Next mapViewDidFailLoadingMap:withError: or mapViewDidFinishLoadingMap: will be called if the tiles have been fetched from the server.
However if neither are called, you can assume the tiles are being loaded from the cache.

As mentioned, mapViewDidFinishLoadingMap is sometimes not called at all, especially if the map tiles are already cached, and sometimes it is called multiple times.
I notice that when it is called multiple times at the last call all of the tiles are rendered. So I think you can get this to work if you set up a 2 second timer after the map starts changing. Disable interactions so that the map does not continue to change, and enable user interactions when the timer goes off.
If mapViewDidFinishLoadingMap gets called reset the timer again for 2 seconds into the future. When the timer finally goes off, you should have a fully rendered map.
You will want to consider the other callbacks such as mapViewDidFailLoadingMap. Also test this on a noisy connection, since 2 seconds may not be long enough if it takes a long time to fetch the tiles.
- (void)restartTimer
{
[self.finishLoadingTimer invalidate];
self.finishLoadingTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(mapLoadingIsFinished)
userInfo:nil
repeats:NO];
}
- (void)mapLoadingIsFinished
{
self.finishLoadingTimer = nil;
self.mapChanging = NO;
self.view.userInteractionEnabled = YES;
}
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
if (self.mapChanging) {
[self restartTimer];
}
}
- (void)startLookingForMapChange
{
assert(self.mapChanging == NO);
if (self.mapChanging == NO) {
self.mapChanging = YES;
assert(self.finishLoadingTimer == nil);
self.view.userInteractionEnabled = NO;
[self restartTimer];
}
}

Related

Using Cocos2D scheduleUpdate to delay loading

I have an algorithm that takes a few seconds to load some stuff, and I want to first set the string on a label to say "loading" before the actual loading begins. This is all within the same layer, this is not switching between scenes.
I thought I could simply do this:
-(void)startLoading{
[self unscheduleAllSelectors];//just in case the update is already scheduled
[self.loadingLabel setString:#"Loading...."];
[self scheduleUpdate];
}
Then, I have this:
-(void)update:(ccTime)delta{
[self unscheduleUpdate];
[self beginLoading];//another method that loads all the stuff
}
My understanding is that my method beginLoading should not run until the next frame. Thus my label should get updated correctly. However this is not happening. There is a slight freeze while all my assets get loaded and my label never gets updated before the loading begins.
Am I missing a step?
Nope ure not missing anything. I stopped fighting this and now use this kind of 'delayed' task catapult. It should make certain you will get a draw in the transition from the first to the second tick:
-(void) startLoading{
_loadTicker=0; // an NSUInteger iVar declared in the .h
[self schedule:#selector(tickOffLoading:)];
}
-(void) tickOffLoading:(ccTime) dt{
_loadTicker++;
if(_loadTicker==1) {
[self.loadingLabel setString:#"Loading...."];
} else {
[self unschedule:#selector(tickOffLoading:)];
[self beginLoading];
}
}

Stop performing the animation in background thread and run loop

I run my animations in a UITAbleViewCell.
Each cell has its own animation and the cells are reusable.
I use [mView performSelectorInBackground:#selector(layoutSubview) withObject:nil];
There in the background thread I initiate the runLoop to perform tasks like this:
- (void)startAnimation
{
NSRunLoop *mLoop = [NSRunLoop currentRunLoop];
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:#selector(setNeedsDisplay) userInfo:nil repeats:YES];
mRunLoop = YES;
while (mRunLoop == YES && [mLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]);
}
and stop it:
- (void)stopAnimation
{
if (![NSThread isMainThread]) {
[[NSThread currentThread] cancel];
}
mRunLoop = NO;
self.animationTimer = nil;
CFRunLoopStop(CFRunLoopGetCurrent());
}
I run into problems when I fast scroll through table, because on the first cell initiation I begin the animation, so the first runLoop call occures which performs a setNeedDisplay and all the methods from it. But before finishing the first runLoop cycle the cell disappears from the view and is already available for reuse. So I begin clearing it, while the cycle is still performing operations and here I meet situations like
message sent to deallocated instance
So could you please give me some hints of how should I correctly stop performing the operations in that thread? I mean if I want to realese for example an object, which is performing some actions how to immediately stop'em?
Hope I gave enough info.
Thanks
UPDATE: No ideas at all?
I'll take a completely different stab on it:
Get rid of the cell's timers and background threads altogether!
Animation is not something where NSTimer is a good fit in the first place and having multiple timers won't help much, either.
UITableView has a method visibleCells and a method indexPathsForVisibleRows. I'd suggest to use a single CADisplayLink — which is suited for animation, as it calls you back with the actual refresh rate of the display or a fraction thereof — in your tableview-controller and in the callback of that display-link iterate over the visible cells.
If you want to schedule the display-link on the run-loop of a secondary thread, feel free to do so, but I'd check if you can get away without extra threading first.
Some code:
#interface AnimatedTableViewController ()
#property (strong, nonatomic) CADisplayLink *cellAnimator;
- (void)__cellAnimatorFired:(CADisplayLink *)animator;
#end
#implementation AnimatedTableViewController
#synthesize cellAnimator = cellAnimator_;
- (void)setCellAnimator:(CADisplayLink *)animator
{
if (animator == cellAnimator_)
return;
[cellAnimator_ invalidate];
cellAnimator_ = animator;
[cellAnimator_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSCommonRunLoopModes];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.cellAnimator = [CADisplayLink displayLinkWithTarget:self selector:#selector(__cellAnimatorFired:)];
...
}
- (void)viewWillDisappear:(BOOL)animated
{
self.cellAnimator = nil;
...
[super viewWillDisappear:animated];
}
- (void)__cellAnimatorFired:(CADisplayLink *)animator
{
NSArray *visibleCells = [self.tableView visibleCells];
[visibleCells enumerateObjectsUsingBlock:^(UITableViewCell *cell, NSUInteger unused, BOOL *stop){
[cell setNeedsDisplay];
}];
}
...
#end
NSTimer has a -cancel method that stops the timer from firing. Calling it in -prepareForReuse (and, for that matter, in -stopAnimation) may help.
However, this code looks rather dangerous. Nesting run loops like this is almost never a good idea—and moreover, as far as I can tell it's totally unnecessary. If you let -startAnimation return, your animation timer will still get run on the main run loop. And if you're doing it this way because there's some code after -startAnimation that you want to delay, you should restructure your code so this isn't needed.
(If you drop the runloop stuff in -startAnimation, don't stop the runloop in -stopAnimation either.)
Something like the approach danyowdee recommends would be even better, but at least get rid of this runloop stuff. It's just asking for trouble.
I think you can use this method for your problem
[NSObject cancelPreviousPerformRequestsWithTarget:yourTarget selector:aSelector object: anArgument];
I think that the best way to avoid that behavior is assigning the delegate that receives the cancel method in other class that won't be reused. For example, you can have a private array of instances that process all the cancel methods, each row mapped into an array element.
I recommend you the lazy tables example provided by Apple in Xcode documentation. It's a great example of how to load images asynchroniously in background with a table. I think that also it would be useful for you for the scrolling subjects (decelerating and paging).
Only one more consideration, i don't recommend messing up with several cfrunloopstop, test it hard!

UISearchDisplayController and images lazy loading

I am using a UITableView in combination with a UISearchDisplayController to do search on the table data array.
for each row shown an image is fetched from the network and cached locally.
the problem is when the user types a search term, each key triggers a call to shouldReloadTableForSearchString which I use to start the online image fetch. If the user types fast it will create several network requests, by the time the network fetch is completed, the row that triggered it might not exist anymore since the search was changed.
I figured I need to wait until the user stops typing before making the network request, but could not yet find a way to do so with UISearchBar and UITableView..
any ideas?
You need to setup a timer upon every key stroke. Lets say you assume that a user has stopped typing if the last key stroke was received 1 second ago. Instead of returning YES from shouldReloadTableForSearchString:, you should schedule a timer. If another key stroke is received before 1 second elapses, invalidate the timer and reset it.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
if(myTimer) //a timer is already scheduled. Invalidate it.
{
[myTimer invalidate]; //myTimer is an iVar
myTimer = nil;
}
myTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1] interval:0 target:self selector:#selector(search:) userInfo:searchString repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
return NO;
}
- (void)search:(NSTimer*)theTimer
{
//make network request here
}
Call [self.searchDisplayController.searchResultsTableView reloadData]; when the response from the network call is received.

How to use isAnimating in an iPhone app

I want to have a custom loading menu made from a series of stills, that loops 3 times and then reveals a picture. Currently the picture is visible from the start. I want to use isAnimating to find out when the loading animation has stopped, and either change myImage.hidden off, or have the UIImageView initially containing a white image, then being replaced with the picture when isAnimating returns NO.
Apple's website just says
- (BOOL)isAnimating
and that it returns a Boolean YES or NO.
but how do you use this?
I need things to happen depending on whether something is animating or not, so i do i put the result it returns in a variable and check that in the conditional of an if statement?
put it in an if statement itself?
or is it a while statement?
or is it like:
- (BOOL)isAnimating{
//stuff to do if it is
}
or am i just getting the whole concept entirely wrong?
I guess isAnimating method just tells you if an UIViewImage is actually performing an animation.
Since you just want to create a short loading before displaying your image, why don't you simply use a timer?
You can do something like this
- (void)startAnimation {
yourImageView.hidden = YES; // Keep you image hidden while loading
[yourLoadingAnimation startAnimating]; // Start you loading animation
NSInteger timeout = 2; // Duration in seconds of your loading animation
[NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:#selector(stopAnimation) userInfo:nil repeats:NO]; // Set the timer
}
- (void)stopAnimation {
[yourLoadingAnimation stopAnimating]; // Stop your loading animation
yourLoadingAnimation.hidden = YES; // Hide your laading animation
yourImageView.hidden = NO; // Display your image
}

connectionDidFinishLoading - how to force update UIView?

I am able to download a ZIP file from the internet. Post processing is done in connectionDidFinishLoading and works OK except no UIView elements are updated. For example, I set statusUpdate.text = #"Uncompressing file" but that change does not appear until after connectionDidFinishLoading has completed. Similarly, the UIProgressView and UIActivityIndicatorView objects are not updated until this method ends.
Is there any way to force an update of the UIView from within this method? I tried setting [self.view setNeedsDisplay] but that didn't work. It appears to be running in the main thread. All other commands here work just fine - the only problem is updating the UI.
Thanks!
Update: here is the code that is NOT updating the UIVIEW:
-(void)viewWillAppear:(BOOL)animated {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(processUpdate:) userInfo:nil repeats:YES];
downloadComplete = NO;
statusText.text = #"";
}
-(void)processUpdate:(NSTimer *)theTimer {
if (! downloadComplete) {
return;
}
[timer invalidate];
statusText.text = #"Processing update file.";
progress.progress = 0.0;
totalFiles = [newFiles count];
for (id fileName in newFiles) {
count++;
progress.progress = (float)count / (float)totalFiles;
// ... process code goes here ...
}
}
At then end of processUpdate, I set downloadComplete = YES. This builds & runs without errors and works as intended except nothing updates in the UIVIEW until after processUpdate completes, then everything updates at once.
Thanks for your help so far!
As Niels said, you must return control to the run loop if you want to see views update. But don't start detaching new threads unless you really need to. I recommend this approach:
- (void)connectionDidFinishLoading:(NSConnection *)connection {
statusUpdate.text = #"Uncompressing file";
[self performSelector:#selector(doUncompress) withObject:nil afterDelay:0];
}
- (void)doUncompress {
// Do work in 100 ms chunks
BOOL isFinished = NO;
NSDate *breakTime = [NSDate dateWithTimeIntervalSinceNow:100];
while (!isFinished && [breakTime timeIntervalSinceNow] > 0) {
// do some work
}
if (! isFinished) {
statusUpdate.text = // here you could update with % complete
// better yet, update a progress bar
[self performSelector:#selector(doUncompress) withObject:nil afterDelay:0];
} else {
statusUpdate.text = #"Done!";
// clean up
}
}
The basic idea is that you do work in small chunks. You return from your method to allow the run loop to execute periodically. The calls to performSelector: will ensure that control eventually comes back to your object.
Note that a risk of doing this is that a user could press a button or interact with the UI in some way that you might not expect. It may be helpful to call UIApplication's beginIgnoringInteractionEvents to ignore input while you're working... unless you want to be really nice and offer a cancel button that sets a flag that you check in your doUncompress method...
You could also try running the run loop yourself, calling [[NSRunLoop currentRunLoop] runUntilDate:...] every so often, but I've never tried that in my own code.
While you are in connectionDidFinishLoading nothing else happens in the application run loop. Control needs to be passed back to the run loop so it can orchestrate the UI updating.
Just flag the data transfer as complete and the views for updating. Defer any heavy processing of the downloaded data to it's own thread.
The application will call your views back letting them refresh their contents later in the run loop. Implement drawRect on your own custom views as appropriate.
If you're receiving connectionDidFinishLoading in the main thread, you're out of luck. Unless you return from this method, nothing will be refreshed in the UI.
On the other hand, if you run the connection in a separate thread, then you can safely update the UI using the following code:
UIProgressView *prog = ... <your progress view reference> ...
[prog performSelectorOnMainThread:#selector(setProgress:)
withObject:[NSNumber numberWithFloat:0.5f]
waitUntilDone:NO];
Be careful not to update the UI from a non-main thread - always use the performSelectorOnMainThread method!
Do exactly what you're doing with the timer, just dispatch your processing code to a new thread with ConnectionDidFinish:. Timers can update the UI since they're run from the main thread.
The problem turned out to that the UI isn't updated in a for() loop. See the answer in this thread for a simple solution!