您好,我正在使用 MKTileOverlay
在我的 iOS7 应用程序
中呈现 OpenStreetMap 图 block 。现在我想实现缓存这些图 block 的功能。我在 NSHipster ( http://nshipster.com/mktileoverlay-mkmapsnapshotter-mkdirections/ ) 上看到了一篇帖子,并做了相应的操作。
这是我的 MKTileOverlay 子类:
#import "DETileOverlay.h"
@implementation DETileOverlay
- (void)loadTileAtPath:(MKTileOverlayPath)path
result:(void (^)(NSData *data, NSError *error))result
{
if (!result)
{
return;
}
NSData *cachedData = [self.cache objectForKey:[self URLForTilePath:path]];
if (cachedData)
{
result(cachedData, nil);
}
else
{
NSURLRequest *request = [NSURLRequest requestWithURL:[self URLForTilePath:path]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
result(data, connectionError);
}];
}
}
@end
然后我像这样使用它:
#import "DETileOverlay.h"
@interface DEMapViewController : UIViewController <MKMapViewDelegate> {
}
@property (nonatomic, retain) DETileOverlay *overlay;
-(void)viewDidLoad {
[super viewDidLoad];
self.overlay = [[DETileOverlay alloc] initWithURLTemplate:@"http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg"];
self.overlay.canReplaceMapContent = YES;
self.overlay.mapView = map;
[map addOverlay:self.overlay level:MKOverlayLevelAboveLabels];
}
// iOS 7
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)ovl
{
MKTileOverlayRenderer *renderer = [[MKTileOverlayRenderer alloc]initWithOverlay:ovl];
return renderer;
}
- (void) mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 300, 300);
[map setRegion:region animated:YES];
}
当我启动我的应用程序时,没有加载图 block 。如果我不重写子类中的 loadTileAtPath ,一切都会正常工作。我做错了什么?
非常感谢。
最佳答案
根据您所说的评论,您已经解决了这个问题,但根据您的代码,您从未将图 block 添加到缓存中。如果没有它,我认为您不会获得任何缓存,并且无论如何都会请求图 block 。因此,在您的completionHandler 中,您应该将生成的图 block 添加到缓存中,如下所示:
....
} else {
NSURLRequest *request = [NSURLRequest requestWithURL:[self URLForTilePath:path]];
[NSURLConnection sendAsynchronousRequest:request queue:self.operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// Should inspect the response to see if the request completed successfully!!
[self.cache setObject:data forKey:[self URLForTilePath:path]];
result(data, connectionError);
}];
}
关于ios - 缓存图 block 的 MKTileOverlay 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428118/