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.

See the Download an offline map example to learn how to create and register an offline pack for a defined region.

  • Returns the shared offline storage object.

    Declaration

    Objective-C

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

    Swift

    class var shared: MGLOfflineStorage { get }
  • Adds the offline packs located at the given file path to offline storage.

    The file must be a valid offline region 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.

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

    The file must be a valid offline region 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. URL should be a valid system path. The file 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.

  • 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 (readwrite, nonatomic, nullable) id<MGLOfflineStorageDelegate>
        delegate;

    Swift

    @IBOutlet weak var delegate: MGLOfflineStorageDelegate? { get set }
  • 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 (readonly, strong, nonatomic, nullable)
        NSArray<MGLOfflinePack *> *packs;

    Swift

    var packs: [MGLOfflinePack]? { get }
  • Creates and registers an offline pack that downloads the resources needed to use the given region offline.

    As of version 5.3 of the Maps SDK for iOS, offline tile requests are no longer exempt from billing on mobile. Developers are subject to separate Vector Tile and Raster Tile API pricing for offline use. See our pricing page for more information.

    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.

  • 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.

  • 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.

  • 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()
  • Sets the maximum number of Mapbox-hosted tiles that may be downloaded and stored on the current device. By default, the limit is set to 6,000.

    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.

  • 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 (readonly, nonatomic) unsigned long long countOfBytesCompleted;

    Swift

    var countOfBytesCompleted: UInt64 { get }
  • 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.

    While this method does not limit the space available to offline packs, data in offline packs count towards this limit. If the maximum ambient cache size is set to 30 MB and 20 MB of offline packs are downloaded, there may be only 10 MB reserved 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.

  • 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.

  • 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.

  • 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.

  • 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.

    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.