您好我正在使用MKTileOverlay
在我的iOS7 App
中展示OpenStreetMap磁贴。现在我想实现缓存这些图块的功能。我在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];
}
当我启动我的应用程序时,没有加载任何图块。如果我不覆盖我的子类中的loadTileAtPath一切正常。我做错了什么?
非常感谢。
答案 0 :(得分:0)
根据您说过的评论,您已经解决了这个问题,但根据您的代码,您永远不会将磁贴添加到缓存中。没有它,我不会认为你会得到任何缓存,并且总是会请求瓷砖。因此,在您的completionHandler中,您应该将生成的图块添加到缓存中,如下所示:
....
} 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);
}];
}
答案 1 :(得分:0)
我在代码中看不到它,但请务必初始化缓存和操作队列。完全使用您的代码不起作用。当我初始化MKTileOverlay时,我设置了它的缓存和操作队列。一切都有效。