你好,我正在使用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,一切都很好。我做错什么了?
非常感谢。
发布于 2014-07-22 17:29:42
根据您说已经解决的注释,但是根据您的代码,您从未将这些块添加到缓存中。否则,我不认为您将得到任何缓存,并将始终请求瓷砖无论如何。因此,在您的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);
}];
}发布于 2014-10-29 14:04:29
我在您的代码中没有看到它,但是一定要初始化缓存和操作队列。使用代码完全不起作用。当我初始化MKTileOverlay时,我会设置它的缓存和操作队列。那一切都成功了。
https://stackoverflow.com/questions/22428118
复制相似问题