NSCache in a MKTilelOverlay

458 Views Asked by At

I am trying to add a NSCache to my subclasse MKTileOverlay class:

@interface WMSTileOverlay ()

@property NSCache *cache;

@end

@implementation WMSTileOverlay

-(instancetype)initWithURLTemplate:(NSString *)URLTemplate {
    self = [super initWithURLTemplate:URLTemplate];

    if (self) {
        DLog(@"setting cache");
        self.cache = [[NSCache alloc] init];
        DLog(@"original self.cache: %@", self.cache);

    }

    return self;
}
-(void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *, NSError *))result {
if (!result) {
    return;
}

NSData *cachedData = [self.cache objectForKey:[self URLForTilePath:path]];
if (cachedData) {
    DLog(@"Cached tile found!!!!!!!");
    result(cachedData, nil);
} else {

    NSURLRequest *request = [NSURLRequest requestWithURL:[self URLForTilePath:path]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            result (nil, connectionError);
        }
        else {
            DLog(@"adding data to cache for tile %@", [self URLForTilePath:path]);
            DLog(@"cache: %@", self.cache);
            [self.cache setObject:data forKey:[self URLForTilePath:path]];

            if ([self.cache objectForKey:[self URLForTilePath:path]]) {
                DLog(@"found the data for url path");
            }
            result (data, nil);
        }
    }];
}

}

But I never see a tile be fetched from the cache (I never see the log message "Cache Tile Found!!!!!!").

What might I be doing wrong?

EDIT: I added in log info

I added in a bunch of logging. I check to see if the cache created and that it is the same cache that I reference to find the tile. I also check to see if the data was added to the cache and it is found right after adding it:

DEBUG | -[WMSTileOverlay initWithMapContext:andLayer:] | original self.cache: <NSCache: 0x1bf59e10>
DEBUG | __40-[WMSTileOverlay loadTileAtPath:result:]_block_invoke | adding data to cache for tile service=wms&version=1.1.1&request=GetMap&SRS=EPSG:4326&layers=displayimg&mode=tiled&tile=30295+46150+17&format=image/png&transparent=true
DEBUG | __40-[WMSTileOverlay loadTileAtPath:result:]_block_invoke | cache: <NSCache: 0x1bf59e10>
DEBUG | __40-[WMSTileOverlay loadTileAtPath:result:]_block_invoke | found the data for url path
1

There are 1 best solutions below

1
On

It's because once a tile for a specific path is loaded, MapKit won't call loadTileAtPath again for that path within the same session, I think MapKit already has cached loaded tiles internally in some way.