|
| 1 | +// |
| 2 | +// CachedTileOverlay.swift |
| 3 | +// |
| 4 | +// Base source code comes from Open GPX Tracker http://github.com/iOS-Open-GPX-Tracker |
| 5 | +// |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import MapKit |
| 10 | + |
| 11 | + |
| 12 | +/// |
| 13 | +/// Overwrites the default overlay to store downloaded images |
| 14 | +/// |
| 15 | +public class CachedTileOverlay : MKTileOverlay { |
| 16 | + |
| 17 | + /// Tells loadTile method if the tile shall be loaded rom the app cache. |
| 18 | + public var useCache: Bool = true |
| 19 | + |
| 20 | + |
| 21 | + public var config: MapCacheConfig? |
| 22 | + |
| 23 | + public init(mapCacheConfig: MapCacheConfig) { |
| 24 | + super.init(urlTemplate: mapCacheConfig.tileUrlTemplate) |
| 25 | + self.config = mapCacheConfig |
| 26 | + } |
| 27 | + |
| 28 | + /// |
| 29 | + /// Generates the URL for the tile to be requested. |
| 30 | + /// It replaces the values of {z},{x} and {y} in the urlTemplate defined in GPXTileServer |
| 31 | + /// |
| 32 | + /// -SeeAlso: GPXTileServer |
| 33 | + /// |
| 34 | + override public func url(forTilePath path: MKTileOverlayPath) -> URL { |
| 35 | + //print("CachedTileOverlay:: url() urlTemplate: \(urlTemplate)") |
| 36 | + var urlString = urlTemplate?.replacingOccurrences(of: "{z}", with: String(path.z)) |
| 37 | + urlString = urlString?.replacingOccurrences(of: "{x}", with: String(path.x)) |
| 38 | + urlString = urlString?.replacingOccurrences(of: "{y}", with: String(path.y)) |
| 39 | + |
| 40 | + //get random subdomain |
| 41 | + let subdomains = "abc" |
| 42 | + let rand = arc4random_uniform(UInt32(subdomains.count)) |
| 43 | + let randIndex = subdomains.index(subdomains.startIndex, offsetBy: String.IndexDistance(rand)); |
| 44 | + urlString = urlString?.replacingOccurrences(of: "{s}", with:String(subdomains[randIndex])) |
| 45 | + print("CachedTileOverlay:: url() urlString: \(urlString ?? "no url")") |
| 46 | + return URL(string: urlString!)! |
| 47 | + } |
| 48 | + |
| 49 | + /// |
| 50 | + /// Loads the tile from the network or from cache |
| 51 | + /// |
| 52 | + /// If the internal app cache is activated,it tries to get the tile from it. |
| 53 | + /// If not, it uses the default system cache (managed by the OS). |
| 54 | + /// |
| 55 | + override public func loadTile(at path: MKTileOverlayPath, |
| 56 | + result: @escaping (Data?, Error?) -> Void) { |
| 57 | + let url = self.url(forTilePath: path) |
| 58 | + print ("CachedTileOverlay::loadTile() url=\(url) useCache: \(useCache)") |
| 59 | + |
| 60 | + if !self.useCache { |
| 61 | + print("lay:: not using cache") |
| 62 | + return super.loadTile(at: path, result: result) |
| 63 | + } |
| 64 | + // Use cache |
| 65 | + |
| 66 | + return super.loadTile(at: path, result: result) |
| 67 | + } |
| 68 | +} |
0 commit comments