CloudSyncProvider

open class CloudSyncProvider : ObjectBase, DataSyncProvider, ClientRegistrationProvider

A data service provider that synchronizes data between a local SQL database on a mobile client device and a remote OData service. Occasional download and upload calls may be used to synchronize data changes when the mobile client device is online. The local SQL database will subsequently be queried and updated via the associated SQLDatabaseProvider when the mobile client device is offline. The remote OData service can be cloud-based or on-premise, but will typically be accessed via a cloud-based intermediary which enables connectivity between the mobile client device and the remote OData service. Connectivity between the mobile client device and the remote OData service can be achieved by the associated OnlineODataProvider via SAP Mobile Services and/or SAP BTP Connectivity. The OData service should be enabled for OData change tracking, so that download calls can efficiently obtain only the changed data. If the OData service does not support change tracking, then Mobile Back-End Tools can be used to enable change tracking, either by using a delta-enabled cache database, or by using a delta-enabled existing database. Mobile Back-end Tools can also be used to provide an OData service with a delta-enabled cache database, wrapping a non-OData backend system which is accessible using HTTPS (for REST APIs or SOAP services), JDBC (for SQL databases), or SAP Java Connector (for ABAP systems). The EntitySet.downloadWithoutDeltaLinks property can be set to true to enable client-side change tracking, however this is only appropriate for application prototyping or for production scenarios with a limited amount of data to be downloaded. Client applications should wrap this provider with a DataService (or OfflineDataService) for convenient consumption, including the use of async methods and proxy classes.

See also

open, client-side download queries, server-side download queries, downloadWithoutDeltaLinks, downloadQueriesCanOverlap, noDefaultEntityDownload, noDefaultStreamDownload.

Example using proxy classes

open func setupService() throws -> Void {
    let online = OnlineODataProvider(serviceName: "HealthService", serviceRoot: "http://health.example.com:8080")
    let database = SQLDatabaseProvider(serviceName: "HealthDB", databaseURL: "sqlite:~/health.db")
    let offline = CloudSyncProvider(onlineProvider: online,
        offlineStore: database)
    offline.encryptionKey = self.dbEncryptionKey()
    offline.createIndex(HealthService.patients, Patient.dateOfBirth,
        Patient.lastName)
    let service = HealthService(provider: offline)
    service.downloadInGroup("PatientGroup", HealthService.patients,
        HealthService.appointments)
    service.downloadInGroup("StaffGroup", HealthService.doctors,
        HealthService.nurses)
    self.healthService = service
}

Example using dynamic API

open func setupService() throws -> Void {
    let onlineProvider = OnlineODataProvider(serviceName: "HealthService",
        serviceRoot: "http://health.example.com:8080")
    let localDatabase = SQLDatabaseProvider(serviceName: "HealthDB",
        databaseURL: "sqlite:~/health.db")
    let offlineProvider = CloudSyncProvider(onlineProvider: onlineProvider,
        offlineStore: localDatabase)
    offlineProvider.encryptionKey = self.dbEncryptionKey()
    offlineProvider.createDynamicIndex("Patients", "dateOfBirth")
    self.healthService = OfflineDataService(provider: offlineProvider)
    try self.healthService.open()
}
  • For internal use by proxy services.

    Declaration

    Swift

    final public var onlineSetup: Bool
  • Construct an offline OData provider.

    Declaration

    Swift

    public init(onlineProvider: OnlineODataProvider, offlineStore: SQLDatabaseProvider? = nil)

    Parameters

    onlineProvider

    For backend system interactions.

    offlineStore

    For local database interactions.

  • Enable automatic download as part of initial open call. Defaults to false. Automatic initial download will only occur if this property is enabled and hasInitialData would return false.

    Declaration

    Swift

    @inline(__always)
    public final var autoInitialDownload: Bool { get set }
  • If autoRefreshMetadata results in detection of changed metadata for entity sets, should those entity sets be automatically refreshed on the next download, even if not included in the download groups parameter? Defaults to true.

    See also

    autoRefreshInterval, autoRefreshMetadata, metadataListener, hasMetadataChanges, changedEntitySets.

    Declaration

    Swift

    @inline(__always)
    public final var autoRefreshEntities: Bool { get set }
  • Frequency of automatic metadata fetches (if enabled). Defaults to one day.

    See also

    autoRefreshMetadata, autoRefreshEntities, metadataListener, hasMetadataChanges.

    Declaration

    Swift

    @inline(__always)
    public final var autoRefreshInterval: DayTimeDuration { get set }
  • Should the latest metadata be occasionally fetched from the backend service (during download), in case it has changed. Defaults to true.

    See also

    autoRefreshInterval, autoRefreshEntities, metadataListener, hasMetadataChanges.

    Declaration

    Swift

    @inline(__always)
    public final var autoRefreshMetadata: Bool { get set }
  • If the backend requires client registration, should this provider automate it. Defaults to true.

    See also

    OnlineDataService.registerClient.

    Declaration

    Swift

    @inline(__always)
    public final var autoRegisterClient: Bool { get set }
  • Should loadTimeEstimates be called on the first call to download after application startup, and saveTimeEstimates be called after each download? Defaults to true.

    See also

    timeEstimatesFile.

    Declaration

    Swift

    @inline(__always)
    public final var autoSaveEstimates: Bool { get set }
  • Maximum amount of time that waitForCompletion should wait for background request completion. Defaults to 20 seconds.

    Declaration

    Swift

    @inline(__always)
    public final var backgroundWaitSeconds: Int { get set }
  • If the backend supports entity download for offline operation, should it be done with batch requests? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var batchEntityDownloads: Bool { get set }
  • If the backend supports entity upload for offline operation, should it be done with batch requests? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var batchEntityUploads: Bool { get set }
  • If the backend supports stream download for offline operation, should it be done with batch requests? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var batchStreamDownloads: Bool { get set }
  • If the backend supports stream upload for offline operation, should it be done with batch requests? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var batchStreamUploads: Bool { get set }
  • Cancel any download(s) that are currently in progress.

    See also

    download.

    Declaration

    Swift

    open func cancelDownload() throws
  • Cancel the specifed pending requests. The requests should be cancelled as a batch, which might perform better than calling PendingRequest.cancel one request at a time.

    See also

    getQueuedRequests, getFailedRequests.

    Declaration

    Swift

    open func cancelPendingRequests(_ requests: PendingRequestList?) throws

    Parameters

    requests

    Pending requests to be cancelled. If null, then all pending requests will be cancelled. If empty, then no pending requests will be cancelled.

  • Cancel any upload(s) that are currently in progress.

    See also

    upload.

    Declaration

    Swift

    open func cancelUpload() throws
  • If hasMetadataChanges would return true, then return a list of the entity sets that need to be re-downloaded.

    Declaration

    Swift

    open func changedEntitySets() throws -> EntitySetList

    Return Value

    List of entity sets that have metadata changes.

  • Clear this provider. This will close the local database, and then delete the database file(s). If the application has other active threads which may try to use the database while it is being cleared, the deletion of the database file(s) may fail.

    Declaration

    Swift

    open func clear() throws
  • When using the dynamic API, you can set this (before calling open) to the name of a client-side file with supplementary metadata. Client-only types (e.g. TypeDefinition, ComplexType, EnumType, EntityType, EntitySet) can be annotated using the “Offline.ClientOnly” annotation. Local draft entity sets (for backend-defined entity types) can be annotated using the “Offline.LocalDraft” annotation. When using proxy classes, rather than setting this property, use the “-X:definitions ” option for proxy generation.

    Declaration

    Swift

    @inline(__always)
    public final var clientMetadataFile: String? { get set }
  • Close this provider. This will close any connection to the local database held by the current thread. If the application has other active threads which may try to use the database while it is being closed, it might remain open after this call has completed.

    Declaration

    Swift

    open func close() throws
  • Can pending delete requests be combined with prior create / update requests (that have not yet been uploaded) by cancelling the prior pending requests? Defaults to true. For example, if an entity is created and then deleted locally, the combining of delete requests would result in no requests being uploaded to the server.

    Declaration

    Swift

    @inline(__always)
    public final var combineLocalDeletes: Bool { get set }
  • Can pending update requests be combined with prior create / update requests (that have not yet been uploaded) by altering the prior pending requests? Defaults to true. For example, if an entity is created and then updated locally, the combining of update requests would result in a single create request being uploaded to the server.

    Declaration

    Swift

    @inline(__always)
    public final var combineLocalUpdates: Bool { get set }
  • Create a persistent query to specify criteria for downloading entities for an entity set. This query is persisted across application restarts. Multiple download queries can be defined for the same entity set (e.g. with different filters).

    See also

    DataQuery.entitySet, deleteDownloadQuery, getDownloadQuery, getDownloadQueries.

    Declaration

    Swift

    open func createDownloadQuery(name: String, query: DataQuery, streams: Bool) throws

    Parameters

    name

    Query name. Must be unique.

    query

    Data query. Use DataQuery.from to specify the query’s entity set.

    streams

    If true, then enable downloading of associated streams.

  • Define a database index for an entity set. Must not be called after the local database has been opened. Actual creation of the index is deferred until the local database is opened. This function differs from createIndex by accepting string-typed parameters. It is applicable even when metadata is not yet available.

    See also

    open, EntitySet.indexes, createIndex.

    Example using proxy classes

    open func setupService() throws -> Void {
        let online = OnlineODataProvider(serviceName: "HealthService", serviceRoot: "http://health.example.com:8080")
        let database = SQLDatabaseProvider(serviceName: "HealthDB", databaseURL: "sqlite:~/health.db")
        let offline = CloudSyncProvider(onlineProvider: online,
            offlineStore: database)
        offline.encryptionKey = self.dbEncryptionKey()
        offline.createIndex(HealthService.patients, Patient.dateOfBirth,
            Patient.lastName)
        let service = HealthService(provider: offline)
        service.downloadInGroup("PatientGroup", HealthService.patients,
            HealthService.appointments)
        service.downloadInGroup("StaffGroup", HealthService.doctors,
            HealthService.nurses)
        self.healthService = service
    }
    

    Declaration

    Swift

    open func createDynamicIndex(_ entitySet: String, _ item: String, _ items: String...)

    Parameters

    entitySet

    Name of entity set for which index will be created.

    item

    First item to be indexed. This is a property name (e.g. “Quantity”) or property path (e.g. “Address/City”).

    rest_items

    Optional additional items for a composite index.

  • Create an entity in the target system. Automatically calls CsdlDocument.resolveEntity to ensure that EntityValue.entitySet is available.

    Throws

    DataServiceException if the entity set hasn’t been explicitly provided before calling createEntity and there isn’t a unique entity set for the entity type.

    See also

    EntityValue.ofType, EntityValue.inSet.

    Declaration

    Swift

    open func createEntity(_ entity: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity to be created.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Define a database index for an entity set. Must not be called after the local database has been opened (explicitly or implicitly). Actual creation of the index is deferred until the local database is opened (explicitly or implicitly).

    See also

    open, EntitySet.indexes, createDynamicIndex.

    Example using proxy classes

    open func setupService() throws -> Void {
        let online = OnlineODataProvider(serviceName: "HealthService", serviceRoot: "http://health.example.com:8080")
        let database = SQLDatabaseProvider(serviceName: "HealthDB", databaseURL: "sqlite:~/health.db")
        let offline = CloudSyncProvider(onlineProvider: online,
            offlineStore: database)
        offline.encryptionKey = self.dbEncryptionKey()
        offline.createIndex(HealthService.patients, Patient.dateOfBirth,
            Patient.lastName)
        let service = HealthService(provider: offline)
        service.downloadInGroup("PatientGroup", HealthService.patients,
            HealthService.appointments)
        service.downloadInGroup("StaffGroup", HealthService.doctors,
            HealthService.nurses)
        self.healthService = service
    }
    

    Declaration

    Swift

    open func createIndex(_ entitySet: EntitySet, _ item: PropertyPath, _ items: PropertyPath...)

    Parameters

    entitySet

    Entity set for which index will be created.

    item

    First item to be indexed (Property or DataPath).

    rest_items

    Optional additional items for a composite index.

  • Create a link from a source entity to a target entity.

    Declaration

    Swift

    open func createLink(from: EntityValue, property: Property, to: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    from

    Source entity for the link to be created.

    property

    Source navigation property for the link to be created.

    to

    Target entity for the link to be created.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Create a media entity with the specified content in the target system. If the entity has non-stream structural properties in addition to the key properties and media content, such as label in the examples below, then this function will send two requests to the server: a first request to upload (POST) the media stream, and a second request (PATCH/PUT) to update the non-stream properties. It is not currently supported to make these two calls atomic. Caution: Having too many threads simultaneously creating streams may result in out-of-memory conditions on memory-constrained devices.

    Declaration

    Swift

    open func createMedia(entity: EntityValue, content: StreamBase, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity to be created.

    content

    Initial content. Must be a ByteStream or CharStream. Will be closed before this function returns.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Current user name for open. Set this before calling open. Note: setting this property does not have any affect on authentication of HTTP requests issued by upload and download. The associated onlineProvider needs to be appropriately configured for authentication.

    Declaration

    Swift

    @inline(__always)
    public final var currentUser: String? { get set }
  • Execute query to delete data from the target system.

    Declaration

    Swift

    open func deleteByQuery(_ query: DataQuery, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    query

    Data query specifying the information to be deleted.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Delete a persistent query previously created by createDownloadQuery, along with any previously downloaded associated entities. Note: if there is a large number of previously downloaded associated entities, deletion of the download query might be time-consuming.

    Declaration

    Swift

    open func deleteDownloadQuery(name: String) throws

    Parameters

    name

    Query name.

  • Delete an entity from the target system.

    Declaration

    Swift

    open func deleteEntity(_ entity: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity to be deleted.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Delete a link from a source entity to a target entity.

    Declaration

    Swift

    open func deleteLink(from: EntityValue, property: Property, to: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    from

    Source entity for the link to be deleted.

    property

    Source navigation property for the link to be deleted.

    to

    Target entity for the link to be deleted.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Delete the content of a stream property from the target system.

    Declaration

    Swift

    open func deleteStream(entity: EntityValue, link: StreamLink, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity containing the stream property whose content is to be deleted.

    headers

    Request-specific headers.

    options

    Request-specific options.

    link

    Stream link for the stream to be deleted.

  • Download backend data changes into the local database.

    Declaration

    Swift

    open func download(groups: StringList, options: SyncOptions) throws

    Parameters

    groups

    If null or empty, then data will be downloaded from all entity sets. If non-empty, then it specifies groups to be downloaded.

    options

    Download options, including cancellation token and progress listener.

  • Return a named download group; the group is created if it doesn’t exist already. Download groups are not remembered across application restart. Download groups should be configured before calling open.

    Declaration

    Swift

    open func downloadGroup(_ group: String) -> DownloadGroup

    Parameters

    group

    Name of download group.

    Return Value

    A download group.

  • Enable background download (for execution environments where it is applicable, otherwise ignored). Defaults to false. When using background downloads, it is preferable to also enable batchEntityDownloads and batchStreamDownloads (where supported by the backend service). Using DownloadMode.parallel or DownloadMode.sequence might result in many separate background download requests, and the operating system might then apply rate limiting which would reduce overall download performance as compared to not using background downloads. For the same reason, it is preferable if the backend system can be configured avoid returning next links by returning entire (possibly large) query results. The best case for background downloads (from the client’s perspective) is a single batch request from the client, with a corresponding single (possibly large) response streamed from server to client. This might entail extra memory utilization at the server, or recoding the server to more efficiently support streaming of responses.

    See also

    uploadInBackground.

    Declaration

    Swift

    @inline(__always)
    public final var downloadInBackground: Bool { get set }
  • Configure one or more entity sets to be downloaded in a named group, equivalent to calling getDownloadGroup(group).add(...). Download groups are used to limit the entity sets to be downloaded. This function is helpful when using generated proxy classes which provide convenient access to entity set objects (e.g. MyService.customers, MyService.orders). If you need to configure a group using entity set names (e.g. with the dynamic API), nested group names, or download query names, then call getDownloadGroup and use the returned object for configuration. Note: this function does not actually perform the download. It simply configures entity sets for later download calls.

    See also

    download, getDownloadGroup.

    Declaration

    Swift

    open func downloadInGroup(_ group: String, _ entitySets: EntitySet...)

    Parameters

    group

    Download group name.

    rest_entitySets

    A list of entity sets to be associated with the download group.

  • Configure one or more entity sets to be downloaded in a numbered phase, equivalent to calling getDownloadPhase(phase).add(entitySets). Download phases are used to order the entity sets to be downloaded. This method is helpful when using generated proxy classes which provide convenient access to entity set objects (e.g. MyService.customers, MyService.orders). If you need to configure a phase using entity set names (e.g. with the dynamic API), nested group names, or download query names, then call getDownloadPhase and use the returned object for configuration. Note: this function does not actually perform the download. It simply configures entity sets for later download calls.

    See also

    download, getDownloadPhase, setDownloadMode.

    Declaration

    Swift

    open func downloadInPhase(_ phase: Int, _ entitySets: EntitySet...)

    Parameters

    phase

    Download phase number, which should be greater than zero. If a zero or negative value is provided, then download will be disabled for the specified entity sets.

    rest_entitySets

    A list of entity sets to be associated with the download phase.

  • Obtain a stream for downloading the content of a media entity from the target system. Caution: streams are often used for large content that may not fit (all at once) in available application memory. Having too many threads simultaneously downloading streams, or using ByteStream.readAndClose, may result in out-of-memory conditions on memory-constrained devices.

    Declaration

    Swift

    open func downloadMedia(entity: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws -> ByteStream

    Parameters

    entity

    Entity whose content is to be downloaded.

    headers

    Request-specific headers.

    options

    Request-specific options.

    Return Value

    A stream for downloading the content of a media entity. This must be closed by the caller, or else a resource leak may occur.

  • Return a numbered download phase; the phase is created if it doesn’t exist already. Download phases are not remembered across application restart. Download phases should be configured before calling open.

    Declaration

    Swift

    open func downloadPhase(_ phase: Int) -> DownloadPhase

    Parameters

    phase

    Number of download phase.

    Return Value

    A download phase.

  • Retrieve all of the persistent queries previously created by createDownloadQuery for a specified entity set.

    Declaration

    Swift

    open func downloadQueries(from: EntitySet? = nil) throws -> DownloadQueryList

    Parameters

    from

    Entity set. If not specified, then download queries for all entity sets are returned.

    Return Value

    List of matching queries.

  • Configure one or more entity sets to allow overlapping results when multiple download queries are used per entity set. By default (for optimal performance), it is assumed that multiple download queries for the same entity set will have non-overlapping query results, e.g. by the appropriate use of DataQuery.filter for each download query. Allowing for overlapping results requires the provider to track downloaded keys, but ensures that deleting a download query will result in deletion of downloaded entities only when they are not related to one or more other download queries.

    See also

    EntitySet.downloadQueriesCanOverlap, createDownloadQuery, deleteDownloadQuery.

    Declaration

    Swift

    open func downloadQueriesCanOverlap(_ entitySets: EntitySet...)

    Parameters

    rest_entitySets

    A list of entity sets whose downloadQueriesCanOverlap property will be set to true. If this list is empty, all entity sets will be configured to allow overlapping download query results.

  • Retrieve a persistent query previously created by createDownloadQuery.

    Declaration

    Swift

    open func downloadQuery(name: String) throws -> DownloadQuery?

    Parameters

    name

    Query name.

    Return Value

    The download query, or nil if no query exists with the specified name.

  • The maximum number of download batches that are waiting to be persisted. Defaults to 100.

    Declaration

    Swift

    @inline(__always)
    public final var downloadQueueCapacity: Int { get set }
  • Obtain a stream for downloading the content of a stream property from the target system. Caution: streams are often used for large content that may not fit (all at once) in available application memory. Having too many threads simultaneously downloading streams, or using ByteStream.readAndClose, may result in out-of-memory conditions on memory-constrained devices.

    See also

    Property.getStreamLink.

    Declaration

    Swift

    open func downloadStream(entity: EntityValue, link: StreamLink, headers: HTTPHeaders, options: RequestOptions) throws -> ByteStream

    Parameters

    entity

    Entity containing the stream property whose content is to be downloaded.

    link

    Stream link for the stream to be downloaded.

    headers

    Request-specific headers.

    options

    Request-specific options.

    Return Value

    A stream for downloading the content of a stream property. This must be closed by the caller, or else a resource leak may occur.

  • Configure one or more entity sets to enable downloads without delta links. If this property is set to true, then download requests to the backend service are expected to return all relevant data (as opposed to returning just changed data), in which case the effective changes will be determined on the client side, and applied to the local database as needed. For large data sets, client-side change determination can result in high client-side CPU, memory, and network utilization. It is recommended to use delta-enabled backend services when working with large data sets, instead of setting this property to true. If you are considering setting this property to true, please evaluate the client-side resource utilization, and consider the alternative option of delta-enabling the backend system.

    Declaration

    Swift

    open func downloadWithoutDeltaLinks(_ entitySets: EntitySet...)

    Parameters

    rest_entitySets

    A list of entity sets whose downloadWithoutDeltaLinks property will be set to true. If this list is empty, all entity sets will be configured to enable downloads without delta links.

  • Should bind operations be emulated by setting foreign keys? Defaults to false. This may be useful for estalishing relationships when the backend system does not support bind operations. Requires the metadata to have appropriate ReferentialConstraint elements.

    See also

    EntityValue.bindEntity, EntityValue.unbindEntity.

    Declaration

    Swift

    @inline(__always)
    public final var emulateBindOperations: Bool { get set }
  • Should link operations be emulated by setting foreign keys? Defaults to false. This may be useful for estalishing relationships when the backend system does not support link operations. Requires the metadata to have appropriate ReferentialConstraint elements.

    See also

    DataService.createLink, DataService.updateLink, DataService.deleteLink.

    Declaration

    Swift

    @inline(__always)
    public final var emulateLinkOperations: Bool { get set }
  • Enable database-level statement batching during download. Defaults to false. This might result in fallbacks (with warning messages) when duplicates are detected, but should result in better download performance when there is a large amount of data to be downloaded.

    Declaration

    Swift

    @inline(__always)
    public final var enableStatementBatching: Bool { get set }
  • Encryption key for offlineStore. If an encryption key is required for the offline store, this property must be set before calling open.

    Declaration

    Swift

    open var encryptionKey: String? { get set }
  • If the backend supports entity download for offline operation, should it be done with multiple threads in parallel? Defaults to 10 threads. Configure a lower number to reduce memory utilization of clients and servers (such a change may also reduce entity download performance). Configure a higher number to improve entity download performance by reducing network latency (such a change may also increase memory utilization).

    Declaration

    Swift

    @inline(__always)
    public final var entityDownloadThreads: Int { get set }
  • Declaration

    Swift

    open func eventHistory(matching query: DataQuery?) throws -> SyncEventList

    Parameters

    query

    If specified, then DataQuery.queryFilter will be used for event filtering and DataQuery.sortItems will be used for result ordering. If not specified (or null), all synchronization events will be returned.

    Return Value

    a list of the synchronization events since the local database was created.

  • Execute a data method (action or function) in the target system. Actions may have backend side-effects. Functions should not have backend side-effects.

    Throws

    DataServiceException or DataNetworkException if an error occurs during action invocation.

    Declaration

    Swift

    open func executeMethod(_ method: DataMethod, parameters: ParameterList, headers: HTTPHeaders, options: RequestOptions) throws -> DataValue?

    Parameters

    method

    Data method.

    parameters

    Method parameters.

    headers

    Request-specific headers.

    options

    Request-specific options.

    Return Value

    The method result, or nil if the method has no result.

  • Execute a data query to get data from the target system.

    Declaration

    Swift

    open func executeQuery(_ query: DataQuery, headers: HTTPHeaders, options: RequestOptions) throws -> QueryResult

    Parameters

    query

    Data query specifying the information to be returned.

    headers

    Request-specific headers.

    options

    Request-specific options.

    Return Value

    The query result.

  • Declaration

    Swift

    open func failedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> PendingRequestList

    Parameters

    query

    If specified, then DataQuery.entitySet and DataQuery.queryFilter will be used for request filtering and DataQuery.sortItems will be used for result ordering. If not specified (or null), all failed requests will be returned.

    headers

    If specified, then the returned pending requests will be further filtered to include only those with matching headers.

    options

    If specified, then the returned pending requests will be further filtered to include only those with matching options (RequestOptions.changeSet, RequestOptions.customTag, RequestOptions.uploadGroup).

    Return Value

    List of failed requests.

  • Fetch latest service metadata and return it, but don’t change the metadata property.

    See also

    loadMetadata.

    Declaration

    Swift

    open func fetchMetadata(headers: HTTPHeaders, options: RequestOptions) throws -> CSDLDocument

    Parameters

    headers

    Optional request-specific headers.

    options

    Optional request-specific options.

    Return Value

    Latest service metadata.

  • If currentUser doesn’t match getPreviousUser when open is called, should open implicitly call download? Defaults to false. If this flag is true and forceUploadOnUserSwitch is also true, then upload will be called before download.

    Declaration

    Swift

    @inline(__always)
    public final var forceDownloadOnUserSwitch: Bool { get set }
  • If currentUser doesn’t match getPreviousUser when open is called, should open implicitly call upload? Defaults to false. If this flag is true and forceDownloadOnUserSwitch is also true, then upload will be called before download.

    Declaration

    Swift

    @inline(__always)
    public final var forceUploadOnUserSwitch: Bool { get set }
  • Declaration

    Swift

    open func hasFailedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> Bool

    Parameters

    query

    If specified, then DataQuery.entitySet and DataQuery.queryFilter will be used for request filtering.

    headers

    If specified, then the returned pending requests will be further filtered to include only those with matching headers.

    options

    If specified, then the returned pending requests will be further filtered to include only those with matching options (RequestOptions.changeSet, RequestOptions.customTag, RequestOptions.uploadGroup).

    Return Value

    true if there are any failed requests in the local database (matching the query, if specified).

  • Declaration

    Swift

    open func hasInitialData() throws -> Bool

    Return Value

    true if a download has previously been successfully executed to obtain initial data for the local database.

  • Has service metadata been loaded.

    See also

    loadMetadata.

    Declaration

    Swift

    open var hasMetadata: Bool { get }
  • Determine if this provider has detected metadata changes (during a previous download) that require re-downloading of previously downloaded entity sets. For example, if an additional property has been added to an entity type, and the relevent data needs to be re-downloaded to obtain values for the added property. Note: When metadata changes, the changes might not take full effect until an application restart.

    See also

    changedEntitySets, download, metadataListener.

    Declaration

    Swift

    open func hasMetadataChanges() throws -> Bool

    Return Value

    true if this provider has detected metadata changes.

  • Declaration

    Swift

    open func hasPendingDownload() throws -> Bool

    Return Value

    true if a download is currently in progress or if the previous download did not terminate normally (i.e. it failed or was cancelled).

  • Declaration

    Swift

    open func hasPendingUpload() throws -> Bool

    Return Value

    true if an upload is currently in progress or if the previous upload did not terminate normally (i.e. it failed or was cancelled).

  • Declaration

    Swift

    open func hasQueuedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> Bool

    Parameters

    query

    If specified, then DataQuery.entitySet and DataQuery.queryFilter will be used for request filtering.

    headers

    If specified, then the returned pending requests will be further filtered to include only those with matching headers.

    options

    If specified, then the returned pending requests will be further filtered to include only those with matching options (RequestOptions.changeSet, RequestOptions.customTag, RequestOptions.uploadGroup).

    Return Value

    true if there are any queued requests in the local database (matching the query, if specified).

  • Checks locally whether a previous registerClient call successfuly created a client registration for the remote OData service.

    Declaration

    Swift

    open func isClientRegistered() throws -> Bool

    Return Value

    true if a registration was already established.

  • Declaration

    Swift

    open func lastDownloadTime() throws -> GlobalDateTime?

    Return Value

    Date and time for the last download request.

  • Declaration

    Swift

    open func lastUploadTime() throws -> GlobalDateTime?

    Return Value

    Date and time for the last upload request.

  • Reload an existing entity from the target system.

    Example using proxy classes

    open func loadEntityExample() throws -> Void {
        let service = self.service
        let customer = Customer()
        customer.customerID = "ALFKI"
        try service.loadEntity(customer)
        self.showCustomer(customer)
    }
    

    Example using dynamic API

    open func loadEntityExample() throws -> Void {
        let service = self.service
        let customersEntitySet = service.entitySet(withName: "Customers")
        let customerEntityType = customersEntitySet.entityType
        let customerIDProperty = customerEntityType.property(withName: "CustomerID")
        let customer = EntityValue.ofType(customerEntityType)
        customerIDProperty.setStringValue(in: customer, to: "ALFKI")
        try service.loadEntity(customer)
        self.showCustomer(customer)
    }
    

    Declaration

    Swift

    open func loadEntity(_ entity: EntityValue, query: DataQuery? = nil, headers: HTTPHeaders = HTTPHeaders.empty, options: RequestOptions = RequestOptions.none) throws

    Parameters

    entity

    Previously loaded entity, whose properties will be modified to reflect the loaded state.

    query

    Optional data query, to specify loading criteria (especially for navigation properties).

    headers

    Optional request-specific headers.

    options

    Optional request-specific options.

  • Load service metadata (if not already loaded).

    See also

    metadata, hasMetadata.

    Declaration

    Swift

    open func loadMetadata(headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    headers

    Optional request-specific headers.

    options

    Optional request-specific options.

  • Declaration

    Swift

    open func loadTimeEstimates(file: String, mustExist: Bool = false) throws

    Parameters

    file

    Time estimates file.

    mustExist

    Specify true if the file must exist. Existing in-memory time estimates remain unchanged if this parameter is false and the file does not exist.

  • Service metadata.

    See also

    loadMetadata.

    Declaration

    Swift

    open var metadata: CSDLDocument { get set }
  • Metadata change listener. When metadata changes, the changes might not take full effect until an application restart. It is therefore advisable to restart the application process when the metadata has changed.

    Declaration

    Swift

    @inline(__always)
    public final var metadataListener: MetadataListener? { get set }
  • Disable download-by-default for the entities of an entity set. This indicates that entity data should only be downloaded if explicitly enabled by use of createDownloadQuery.

    Declaration

    Swift

    open func noDefaultEntityDownload(_ entitySets: EntitySet...)

    Parameters

    rest_entitySets

    A list of entity sets whose downloadEntitiesByDefault property will be set to false. If this list is empty, all entity sets will be configured to disable default entity download.

  • Disable download-by-default for the streams of an entity set.

    Declaration

    Swift

    open func noDefaultStreamDownload(_ entitySets: EntitySet...)

    Parameters

    rest_entitySets

    A list of entity sets whose downloadStreamsByDefault property will be set to false. If this list is empty, all entity sets will be configured to disable default stream download.

  • Provider for acessing the local database.

    Declaration

    Swift

    open var offlineStore: SQLDatabaseProvider { get }
  • Provider for accessing the backend system.

    Declaration

    Swift

    open var onlineProvider: OnlineODataProvider { get }
  • Open this provider. This will create the local database if it doesn’t exist already. This might also communicate with the backend system (but only the first time it is called, if metadata is not available locally or if forceUploadOnUserSwitch and/or forceDownloadOnUserSwitch is enabled).

    Declaration

    Swift

    open func open() throws
  • Set this to false to disable persistence of downloaded entities. Defaults to true. Useful in benchmarking, to separate downloading/parsing from local persistence.

    Declaration

    Swift

    @inline(__always)
    public final var persistDownloadedEntities: Bool { get set }
  • Set this to false to disable persistence of downloaded streams. Defaults to true. Useful in benchmarking, to separate downloading/parsing from local persistence.

    Declaration

    Swift

    @inline(__always)
    public final var persistDownloadedStreams: Bool { get set }
  • Ping the server.

    Declaration

    Swift

    open func pingServer(headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    headers

    Optional request-specific headers.

    options

    Optional request-specific options.

  • Should download prefer compact responses such as Compact JSON encoding? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var preferCompactResponses: Bool { get set }
  • Should traceWithData show pretty-printed JSON/XML content? Defaults to false.

    Declaration

    Swift

    open var prettyTracing: Bool { get set }
  • Declaration

    Swift

    open func previousUser() throws -> String?

    Return Value

    The currentUser after open was last called.

  • Execute a request batch in the target system.

    Declaration

    Swift

    open func processBatch(_ batch: RequestBatch, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    batch

    The request batch.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Progress listener for download and upload.

    See also

    loadTimeEstimates, saveTimeEstimates.

    Declaration

    Swift

    @inline(__always)
    public final var progressListener: ProgressListener? { get set }
  • Declaration

    Swift

    open func queuedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> PendingRequestList

    Parameters

    query

    If specified, then DataQuery.entitySet and DataQuery.queryFilter will be used for request filtering and DataQuery.sortItems will be used for result ordering. If not specified (or null), all queued requests will be returned.

    headers

    If specified, then the returned pending requests will be further filtered to include only those with matching headers.

    options

    If specified, then the returned pending requests will be further filtered to include only those with matching options (RequestOptions.changeSet, RequestOptions.customTag, RequestOptions.uploadGroup).

    Return Value

    List of queued requests.

  • If isClientRegistered would return false, create a new client registration and record its key (ClientID property of type GUID) in local file ~/ClientRegistration/<ServiceName>.json. Otherwise just load the previously locally-saved registration ID into the ServiceOptions.clientInstanceID. The server’s metadata is expected to include a ClientRegistrationSet entity set with entity type ClientRegistration, a key property named ClientID of type long (Edm.Int64), and a property named ClientGUID of type guid (Edm.Guid). If a new registration is successfully created, ServiceOptions.clientInstanceID is set, and will subsequently be used to populate the Client-Instance-ID HTTP header for all OData calls. The purpose of creating such a client registration is to enable the server to associate various resources with the current instance of the current client application. A “current instance” can survive multiple restarts of the client application so long as the same Client-Instance-ID header value is provided for each OData call to the remote service. This is particularly useful for offline applications which rely on server-side OData change tracking implementations that store per-client server-side state to facilitate change tracking.

    Declaration

    Swift

    open func registerClient(_ client: EntityValue?) throws

    Parameters

    client

    Instance of ClientRegistration entity type. If omitted, a default instance will be created.

  • Save download time estimates to file. Should be called after a download operation.

    Declaration

    Swift

    open func saveTimeEstimates(file: String) throws

    Parameters

    file

    Time estimates file.

  • Should upload send Repeatable Requests? Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var sendRepeatableRequests: Bool { get set }
  • Service name.

    Declaration

    Swift

    open var serviceName: String { get }
  • Configure the mode (any, batch, parallel or sequence) for a specified download phase. Selecting mode any means that the effective mode is determined by other configuration settings (e.g. for batches or threads).

    See also

    getDownloadPhase.

    Declaration

    Swift

    open func setDownloadMode(phase: Int, mode: DownloadMode)

    Parameters

    phase

    Download phase.

    mode

    Download mode.

  • If the backend supports stream download for offline operation, should it be done with multiple threads in parallel? Defaults to 10 threads. Configure a lower number to reduce memory utilization of clients and servers (such a change may also reduce stream download performance). Configure a higher number to improve stream download performance by reducing network latency (such a change may also increase memory utilization).

    Declaration

    Swift

    @inline(__always)
    public final var streamDownloadThreads: Int { get set }
  • Should upload throw an exception if one or more requests has a service failure due to an HTTP response with a non-successful HTTP status code? Note: if a request fails due to any condition where an HTTP response status code cannot be obtained (e.g. a network failure), an upload call should always throw an exception. Defaults to true.

    Declaration

    Swift

    @inline(__always)
    public final var throwUploadFailures: Bool { get set }
  • Name to be used for time estimates file if autoSaveEstimates is true.

    Declaration

    Swift

    @inline(__always)
    public final var timeEstimatesFile: String? { get set }
  • Should all requests for this data service be traced? Defaults to false.

    Declaration

    Swift

    open var traceRequests: Bool { get set }
  • Should upload trace upload failures if one or more requests has a service failure due to an HTTP response with a non-successful HTTP status code? Note: if a request fails due to any condition where an HTTP response status code cannot be obtained (e.g. a network failure), an upload call should always log an error (but without request details). Enabling tracing of upload failures can result in sensitive data being included in the log. Defaults to false.

    Declaration

    Swift

    @inline(__always)
    public final var traceUploadFailures: Bool { get set }
  • If traceRequests is also true, should all requests for this data service be traced with data? Defaults to false. Note that care must be taken when enabling tracing with data, as the resulting log files may contain sensitive information. On the other hand, tracing with data may sometimes be invaluable for troubleshooting purposes.

    Declaration

    Swift

    open var traceWithData: Bool { get set }
  • Undo all pending (local) changes for entities, so they will not be subsequently uploaded.

    Declaration

    Swift

    open func undoPendingChanges(for entities: EntityValueList) throws

    Parameters

    entities

    A list of entities whose pending changes will be undone.

  • Unload service metadata (if previously loaded).

    See also

    metadata, hasMetadata.0

    Declaration

    Swift

    open func unloadMetadata() throws
  • Forget any client registration previously established by registerClient. Also attempts to make a call to the server to delete the associated entity, if the deleteFromServer parameter is true.

    Declaration

    Swift

    open func unregisterClient(deleteFromServer: Bool) throws

    Parameters

    deleteFromServer

    Specify a value of true to request the server to also delete the corresponding entity.

  • Update an entity in the target system.

    Declaration

    Swift

    open func updateEntity(_ entity: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity to be updated.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Update a link from a source entity to a target entity.

    Declaration

    Swift

    open func updateLink(from: EntityValue, property: Property, to: EntityValue, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    from

    Source entity for the link to be updated.

    property

    Source navigation property for the link to be updated. This must be a one-to-one navigation property.

    to

    Target entity for the link to be updated.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Upload data changes for all uploadable entity sets.

    Declaration

    Swift

    open func upload(groups: StringList, options: SyncOptions) throws

    Parameters

    groups

    If empty, then data will be uploaded from all entity sets. If non-empty, then it specifies groups to be included.

    options

    Upload options, including cancellation token and progress listener.

  • Upload a copy of the local database file (or files) to the backend server (or an intermediary server) for diagnostic purposes. Note: if the local database is encrypted, and encryptionKey is null, this operation might fail (depending on the provider). Note: if the local database is not encrypted, and encryptionKey is non-null, this operation might fail (depending on the provider).

    Declaration

    Swift

    open func uploadDatabaseFile(encryptionKey: String?, note: String?, options: SyncOptions) throws

    Parameters

    encryptionKey

    Encryption key for the uploaded database, which may differ from the encryption key of the local database (if any).

    note

    Associated note for trusted users who have access to uploaded databases for diagnostic purposes.

    options

    Upload options, including cancellation token and progress listener.

  • Enable background upload (for execution environments where it is applicable, otherwise ignored). Defaults to false. When using background uploads, it is preferable to also enable batchEntityUploads and batchStreamUploads (where supported by the backend service).

    Declaration

    Swift

    @inline(__always)
    public final var uploadInBackground: Bool { get set }
  • If the backend supports request upload for offline operation, how many bytes (maximum) should be uploaded per iteration? Defaults to 5,000,000 bytes. Configure a lower number to reduce memory utilization of clients and servers (such a change may also reduce request upload performance). Configure a higher number to improve request upload performance by reducing network latency (such a change may also increase memory utilization).

    Declaration

    Swift

    @inline(__always)
    public final var uploadIterationSize: Int { get set }
  • Upload content for a media entity to the target system Caution: Having too many threads simultaneously uploading streams may result in out-of-memory conditions on memory-constrained devices. Note: this function cannot be used to create a media entity. See DataService.createMedia.

    Declaration

    Swift

    open func uploadMedia(entity: EntityValue, content: StreamBase, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity whose content is to be uploaded.

    content

    Upload stream content. Will be closed before this function returns.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • Upload content for a stream property to the target system. Caution: Having too many threads simultaneously uploading streams may result in out-of-memory conditions on memory-constrained devices.

    See also

    Property.getStreamLink.

    Declaration

    Swift

    open func uploadStream(entity: EntityValue, link: StreamLink, content: StreamBase, headers: HTTPHeaders, options: RequestOptions) throws

    Parameters

    entity

    Entity containing the stream property whose content is to be uploaded.

    link

    Stream link for the stream to be uploaded.

    content

    Upload stream content. Will be closed before this function returns.

    headers

    Request-specific headers.

    options

    Request-specific options.

  • If the backend supports request upload for offline operation, should it be done with multiple threads in parallel? Defaults to 10 threads. Configure a lower number to reduce memory utilization of clients and servers (such a change may also reduce request upload performance). Configure a higher number to improve request upload performance by reducing network latency (such a change may also increase memory utilization).

    Declaration

    Swift

    @inline(__always)
    public final var uploadWorkerThreads: Int { get set }
  • If a background download or upload session completes, the application may need to wait for local processing of the background request results, before notifying a completion handler. When using background download/upload, call this function from the application delegate’s handleEventsForBackgroundURLSession callback.

    Declaration

    Swift

    open func waitForCompletion(sessionIdentifier: String, completionHandler: @escaping () -> Void)