MGLOfflineStorage

@interface MGLOfflineStorage : NSObject

MGLOfflineStorage implements a singleton (shared object) that manages offline packs and ambient caching. All of this class’s instance methods are asynchronous, reflecting the fact that offline resources are stored in a database. The shared object maintains a canonical collection of offline packs in its packs property.

Mapbox resources downloaded via this API are subject to separate Vector Tile and Raster Tile API pricing and are not included in the Maps SDK’s “unlimited” requests. See our pricing page for more information.

sharedOfflineStorage

Returns the shared offline storage object.

Declaration

Objective-C

@property (class, nonatomic, readonly)
MGLOfflineStorage *_Nonnull sharedOfflineStorage;

Swift

class var shared: MGLOfflineStorage { get }

Accessing the Delegate

delegate

The receiver’s delegate.

An offline storage object sends messages to its delegate to allow it to transform URLs before they are requested from the internet. This can be used add or remove custom parameters, or reroute certain requests to other servers or endpoints.

Declaration

Objective-C

@property (nonatomic, weak, readwrite, nullable) id<MGLOfflineStorageDelegate>
delegate;

Swift

@IBOutlet weak var delegate: MGLOfflineStorageDelegate? { get set }

Managing the Database of Offline Packs

databasePath

The file path at which offline packs and the ambient cache are stored.

To customize this path, specify the MGLOfflineStorageDatabasePath key in Info.plist.

Declaration

Objective-C

@property (nonatomic, copy, readonly) NSString *_Nonnull databasePath;

Swift

var databasePath: String { get }

databaseURL

The file URL at which offline packs and the ambient cache are stored.

To customize this path, specify the MGLOfflineStorageDatabasePath key in Info.plist.

Declaration

Objective-C

@property (nonatomic, copy, readonly) NSURL *_Nonnull databaseURL;

Swift

var databaseURL: URL { get }

-addContentsOfFile:withCompletionHandler:

Adds the offline packs located at the given file path to offline storage.

The file must be a valid offline pack database bundled with the application or downloaded separately.

The resulting packs are added or updated to the shared offline storage object’s packs property, then the completion block is executed.

Declaration

Objective-C

- (void)addContentsOfFile:(nonnull NSString *)filePath
withCompletionHandler:
    (nullable MGLBatchedOfflinePackAdditionCompletionHandler)completion;

Swift

func addContents(ofFile filePath: String, withCompletionHandler completion: MGLBatchedOfflinePackAdditionCompletionHandler? = nil)

Parameters

filePath

A string representation of the file path. The file path must be writable as schema updates may be perfomed.

completion

The completion handler to call once the contents of the given file has been added to offline storage. This handler is executed asynchronously on the main queue.

-addContentsOfURL:withCompletionHandler:

Adds the offline packs located at the given URL to offline storage.

The file must be a valid offline pack database bundled with the application or downloaded separately.

The resulting packs are added or updated to the shared offline storage object’s packs property, then the completion block is executed.

Declaration

Objective-C

- (void)addContentsOfURL:(nonnull NSURL *)fileURL
withCompletionHandler:
    (nullable MGLBatchedOfflinePackAdditionCompletionHandler)completion;

Swift

func addContents(of fileURL: URL, withCompletionHandler completion: MGLBatchedOfflinePackAdditionCompletionHandler? = nil)

Parameters

fileURL

A file URL specifying the file to add. The URL should be a valid system path. The URL must be writable as schema updates may be performed.

completion

The completion handler to call once the contents of the given file has been added to offline storage. This handler is executed asynchronously on the main queue.

Managing Offline Packs

packs

An array of all known offline packs, in the order in which they were created.

This property is set to nil, indicating that the receiver does not yet know the existing packs, for an undefined amount of time starting from the moment the shared offline storage object is initialized until the packs are fetched from the database. After that point, this property is always non-nil, but it may be empty to indicate that no packs are present.

To detect when the shared offline storage object has finished loading its packs property, observe KVO change notifications on the packs key path. The initial load results in an NSKeyValueChangeSetting change.

Declaration

Objective-C

@property (nonatomic, strong, readonly, nullable)
NSArray<MGLOfflinePack *> *packs;

Swift

var packs: [MGLOfflinePack]? { get }

-addPackForRegion:withContext:completionHandler:

Creates and registers an offline pack that downloads the resources needed to use the given region offline.

The resulting pack is added to the shared offline storage object’s packs property, then the completion block is executed with that pack passed in.

The pack has an initial state of MGLOfflinePackStateInactive. To begin downloading resources, call -[MGLOfflinePack resume] on the pack from within the completion handler. To monitor download progress, add an observer for MGLOfflinePackProgressChangedNotifications about that pack.

To detect when any call to this method results in a new pack, observe KVO change notifications on the shared offline storage object’s packs key path. Additions to that array result in an NSKeyValueChangeInsertion change.

Declaration

Objective-C

- (void)addPackForRegion:(nonnull id<MGLOfflineRegion>)region
         withContext:(nonnull NSData *)context
   completionHandler:
       (nullable MGLOfflinePackAdditionCompletionHandler)completion;

Parameters

region

A region to download.

context

Arbitrary data to store alongside the downloaded resources.

completion

The completion handler to call once the pack has been added. This handler is executed asynchronously on the main queue.

-removePack:withCompletionHandler:

Unregisters the given offline pack and allows resources that are no longer required by any remaining packs to be potentially freed.

As soon as this method is called on a pack, the pack becomes invalid; any attempt to send it a message will result in an exception being thrown. If an error occurs and the pack cannot be removed, do not attempt to reuse the pack object. Instead, if you need continued access to the pack, suspend all packs and use the -reloadPacks method to obtain valid pointers to all the packs.

To detect when any call to this method results in a pack being removed, observe KVO change notifications on the shared offline storage object’s packs key path. Removals from that array result in an NSKeyValueChangeRemoval change.

When you remove an offline pack, any resources that are required by that pack, but not other packs, become eligible for deletion from offline storage. Because the backing store used for offline storage is also used as a general purpose cache for map resources, such resources may not be immediately removed if the implementation determines that they remain useful for general performance of the map.

Declaration

Objective-C

- (void)removePack:(nonnull MGLOfflinePack *)pack
withCompletionHandler:
    (nullable MGLOfflinePackRemovalCompletionHandler)completion;

Swift

func removePack(_ pack: MGLOfflinePack, withCompletionHandler completion: MGLOfflinePackRemovalCompletionHandler? = nil)

Parameters

pack

The offline pack to remove.

completion

The completion handler to call once the pack has been removed. This handler is executed asynchronously on the main queue.

-invalidatePack:withCompletionHandler:

Invalidates the specified offline pack. This method checks that the tiles in the specified offline pack match those from the server. Local tiles that do not match the latest version on the server are updated.

This is more efficient than deleting the offline pack and downloading it again. If the data stored locally matches that on the server, new data will not be downloaded.

Declaration

Objective-C

- (void)invalidatePack:(nonnull MGLOfflinePack *)pack
withCompletionHandler:(nonnull void (^)(NSError *_Nullable))completion;

Swift

func invalidatePack(_ pack: MGLOfflinePack, withCompletionHandler completion: @escaping (Error?) -> Void)

Parameters

pack

The offline pack to be invalidated.

completion

The completion handler to call once the pack has been removed. This handler is executed asynchronously on the main queue.

-reloadPacks

Forcibly, asynchronously reloads the packs property. At some point after this method is called, the pointer values of the MGLOfflinePack objects in the packs property change, even if the underlying data for these packs has not changed. If this method is called while a pack is actively downloading, the behavior is undefined.

You typically do not need to call this method.

To detect when the shared offline storage object has finished reloading its packs property, observe KVO change notifications on the packs key path. A reload results in an NSKeyValueChangeSetting change.

Declaration

Objective-C

- (void)reloadPacks;

Swift

func reloadPacks()

-setMaximumAllowedMapboxTiles:

Sets the maximum number of Mapbox-hosted tiles that may be downloaded and stored on the current device.

Once this limit is reached, an MGLOfflinePackMaximumMapboxTilesReachedNotification is posted for every attempt to download additional tiles until already downloaded tiles are removed by calling the -removePack:withCompletionHandler: method.

Declaration

Objective-C

- (void)setMaximumAllowedMapboxTiles:(uint64_t)maximumCount;

Swift

func setMaximumAllowedMapboxTiles(_ maximumCount: UInt64)

Parameters

maximumCount

The maximum number of tiles allowed to be downloaded.

countOfBytesCompleted

The cumulative size, measured in bytes, of all downloaded resources on disk.

The returned value includes all resources, including tiles, whether downloaded as part of an offline pack or due to caching during normal use of MGLMapView.

Declaration

Objective-C

@property (nonatomic, readonly) unsigned long long countOfBytesCompleted;

Swift

var countOfBytesCompleted: UInt64 { get }

Managing the Ambient Cache

-setMaximumAmbientCacheSize:withCompletionHandler:

Sets the maximum ambient cache size in bytes. The default maximum cache size is 50 MB. To disable ambient caching, set the maximum ambient cache size to 0. Setting the maximum ambient cache size does not impact the maximum size of offline packs.

This method does not limit the space available to offline packs, and data in offline packs does not count towards this limit. If you set the maximum ambient cache size to 30 MB then download 20 MB of offline packs, 30 MB will remain available for the ambient cache.

This method should be called before the map and map style have been loaded.

This method is potentially expensive, as the database will trim cached data in order to prevent the ambient cache from being larger than the specified amount.

Declaration

Objective-C

- (void)setMaximumAmbientCacheSize:(NSUInteger)cacheSize
         withCompletionHandler:
             (nonnull void (^)(NSError *_Nullable))completion;

Swift

func setMaximumAmbientCacheSize(_ cacheSize: UInt, withCompletionHandler completion: @escaping (Error?) -> Void)

Parameters

cacheSize

The maximum size in bytes for the ambient cache.

completion

The completion handler to call once the maximum ambient cache size has been set. This handler is executed synchronously on the main queue.

-invalidateAmbientCacheWithCompletionHandler:

Invalidates the ambient cache. This method checks that the tiles in the ambient cache match those from the server. If the local tiles do not match those on the server, they are re-downloaded.

This is recommended over clearing the cache or resetting the database because valid local tiles will not be downloaded again.

Resources shared with offline packs will not be affected by this method.

Declaration

Objective-C

- (void)invalidateAmbientCacheWithCompletionHandler:
(nonnull void (^)(NSError *_Nullable))completion;

Swift

func invalidateAmbientCache(completionHandler completion: @escaping (Error?) -> Void)

Parameters

completion

The completion handler to call once the ambient cache has been revalidated. This handler is executed asynchronously on the main queue.

-clearAmbientCacheWithCompletionHandler:

Clears the ambient cache by deleting resources. This method does not affect resources shared with offline regions.

Declaration

Objective-C

- (void)clearAmbientCacheWithCompletionHandler:
(nonnull void (^)(NSError *_Nullable))completion;

Swift

func clearAmbientCache(completionHandler completion: @escaping (Error?) -> Void)

Parameters

completion

The completion handler to call once resources from the ambient cache have been cleared. This handler is executed asynchronously on the main queue.

-resetDatabaseWithCompletionHandler:

Deletes the existing database, which includes both the ambient cache and offline packs, then reinitializes it.

You typically do not need to call this method.

Declaration

Objective-C

- (void)resetDatabaseWithCompletionHandler:
(nonnull void (^)(NSError *_Nullable))completion;

Swift

func resetDatabase(completionHandler completion: @escaping (Error?) -> Void)

Parameters

completion

The completion handler to call once the pack has database has been reset. This handler is executed asynchronously on the main queue.

-preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:

Inserts the provided resource into the ambient cache.

This method mimics the caching that would take place if the equivalent resource were requested in the process of map rendering. Use this method to pre-warm the cache with resources you know will be requested.

This method is asynchronous; the data may not be immediately available for in-progress requests, though subsequent requests should have access to the cached data.

To find out when the resource is ready to retrieve from the cache, use the -preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:completionHandler: method.

Declaration

Objective-C

- (void)preloadData:(nonnull NSData *)data
          forURL:(nonnull NSURL *)url
modificationDate:(nullable NSDate *)modified
  expirationDate:(nullable NSDate *)expires
            eTag:(nullable NSString *)eTag
  mustRevalidate:(BOOL)mustRevalidate;

Swift

func preload(_ data: Data, for url: URL, modifiedOn modified: Date?, expiresOn expires: Date?, eTag: String?, mustRevalidate: Bool)

Parameters

data

Response data to store for this resource. The data is expected to be uncompressed; internally, the cache will compress data as necessary.

url

The URL at which the data can normally be found.

modified

The date the resource was last modified.

expires

The date after which the resource is no longer valid.

eTag

An HTTP entity tag.

mustRevalidate

A Boolean value indicating whether the data is still usable past the expiration date.

-preloadData:forURL:modificationDate:expirationDate:eTag:mustRevalidate:completionHandler:

Inserts the provided resource into the ambient cache, calling a completion handler when finished.

This method is asynchronous. The data is available for in-progress requests as soon as the completion handler is called.

This method is asynchronous; the data may not be immediately available for in-progress requests, though subsequent requests should have access to the cached data.

Declaration

Objective-C

- (void)preloadData:(nonnull NSData *)data
           forURL:(nonnull NSURL *)url
 modificationDate:(nullable NSDate *)modified
   expirationDate:(nullable NSDate *)expires
             eTag:(nullable NSString *)eTag
   mustRevalidate:(BOOL)mustRevalidate
completionHandler:
    (nullable MGLOfflinePreloadDataCompletionHandler)completion;

Swift

func preload(_ data: Data, for url: URL, modificationDate modified: Date?, expirationDate expires: Date?, eTag: String?, mustRevalidate: Bool, completionHandler completion: MGLOfflinePreloadDataCompletionHandler? = nil)

Parameters

data

Response data to store for this resource. The data is expected to be uncompressed; internally, the cache will compress data as necessary.

url

The URL at which the data can normally be found.

modified

The date the resource was last modified.

expires

The date after which the resource is no longer valid.

eTag

An HTTP entity tag.

mustRevalidate

A Boolean value indicating whether the data is still usable past the expiration date.

completion

The completion handler to call once the data has been preloaded. This handler is executed asynchronously on the main queue.

iOS SDK

SDK JS Reference

On this page