Skip to content

Added a LoadMode property to tell MapCache how to load the tiles #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Example/Pods/Pods.xcodeproj/project.pbxproj

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions MapCache/Classes/LoadTileMode.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//
// LoadTileMode.swift
// MapCache
//
// Created by merlos on 09/05/2020.
//

import Foundation

public enum LoadTileMode {

/// Default. If the tile exists in the cache, return it, otherwise, fetch it from server (and cache the result)
case cacheThenServer

/// Always return the tile from the server unless there is some problem with the network
/// Cache is updated everytime the tile is received.
/// Basically uses the cache as internet connection fallback
case serverThenCache

/// Only return data from cache
/// Useful for fully offline preloaded maps.
case cacheOnly

/// Always return the tile from the server, as well as updating the cache
/// This mode may be useful for donwloading a whole map region
/// If a tile was not downloaded fron the server error is returned.
case serverOnly



}
63 changes: 43 additions & 20 deletions MapCache/Classes/MapCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,51 +27,74 @@ public class MapCache : MapCacheProtocol {
urlString = urlString.replacingOccurrences(of: "{x}", with: String(path.x))
urlString = urlString.replacingOccurrences(of: "{y}", with: String(path.y))
urlString = urlString.replacingOccurrences(of: "{s}", with: config.roundRobinSubdomain() ?? "")
print("MapCache::url() urlString: \(urlString)")
Log.debug(message: "MapCache::url() urlString: \(urlString)")
return URL(string: urlString)!
}

public func cacheKey(forPath path: MKTileOverlayPath) -> String {
return "\(config.urlTemplate)-\(path.x)-\(path.y)-\(path.z)"
}


public func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -> Void) {
// Use cache
// is the file alread in the system?

let key = cacheKey(forPath: path)

let loadTileFromOrigin = { () -> () in
// Feches tile from server. If it is found updates the cache
func fetchTileFromServer(failure fail: ((Error?) -> ())? = nil,
success succeed: @escaping (Data) -> ()) {
let url = self.url(forTilePath: path)
print ("MapCache::loadTile() url=\(url)")
print ("MapCache::fetchTileFromServer() url=\(url)")
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
if error != nil {
print("!!! MapCache::loadTile Error for key= \(key)")
result(nil, error)
print("!!! MapCache::fetchTileFromServer Error for url= \(url)")
fail!(error)
return
}
guard let data = data else {
result(nil, nil)
fail!(nil)
return
}
self.diskCache.setData(data, forKey: key)
print ("CachedTileOverlay:: Data received saved cacheKey=\(key)" )
result(data,nil)
print ("MapCache::fetchTileFromServer:: Data received saved cacheKey=\(key)" )
succeed(data)
}
task.resume()
}

// If fetching data from cache is successfull => return the data
let fetchSuccess = {(data: Data) -> () in
print ("MapCache::loadTile() found! cacheKey=\(key)" )
result (data, nil)
// Tries to load the tile from the server.
// If it fails returns error to the caller.
let tileFromServerFallback = { () -> () in
print ("MapCache::tileFromServerFallback:: key=\(key)" )
fetchTileFromServer(failure: {error in result(nil, error)},
success: {data in result(data, nil)})
}
// Closure to run if error found while fetching data from cache
let fetchFailure = { (error: Error?) -> () in
print ("MapCache::loadTile() Not found! cacheKey=\(key)" )
loadTileFromOrigin()

// Tries to load the tile from the cache.
// If it fails returns error to the caller.
let tileFromCacheFallback = { () -> () in
self.diskCache.fetchDataSync(forKey: key,
failure: {error in result(nil, error)},
success: {data in result(data, nil)})

}

switch config.loadTileMode {
case .cacheThenServer:
diskCache.fetchDataSync(forKey: key,
failure: {error in tileFromServerFallback()},
success: {data in result(data, nil) })
case .serverThenCache:
fetchTileFromServer(failure: {error in tileFromCacheFallback()},
success: {data in result(data, nil) })
case .serverOnly:
fetchTileFromServer(failure: {error in result(nil, error)},
success: {data in result(data, nil)})
case .cacheOnly:
diskCache.fetchDataSync(forKey: key,
failure: {error in result(nil, error)},
success: {data in result(data, nil)})
}
// Fetch the data. Current thread is not main thread.
diskCache.fetchDataSync(forKey: key, failure: fetchFailure, success: fetchSuccess)
}

public var diskSize: UInt64 {
Expand Down
7 changes: 7 additions & 0 deletions MapCache/Classes/MapCacheConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import Foundation
import CoreGraphics


///
Expand Down Expand Up @@ -54,6 +55,12 @@ public struct MapCacheConfig {
///
public var tileSize: CGSize = CGSize(width: 256, height: 256)

///
/// Load tile mode.
/// Sets the strategy when loading a tile. By default loads from the cache and if it fails loads from the server
///
public var loadTileMode: LoadTileMode = .cacheThenServer

public init() {
}

Expand Down