CloudSyncProvider
open class CloudSyncProvider : ObjectBase, DataSyncProvider, ClientRegistrationProvider, @unchecked Sendable
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
onlineProviderFor backend system interactions.
offlineStoreFor local database interactions.
-
Enable automatic
downloadas part of initialopencall. Defaults totrue. Automatic initial download will only occur if this property is enabled andhasInitialDatawould returnfalse.Declaration
Swift
@inline(__always) public final var autoInitialDownload: Bool { get set } -
If
autoRefreshMetadataresults in detection of changed metadata for entity sets, should those entity sets be automatically refreshed on the nextdownload, even if not included in the downloadgroupsparameter? Defaults totrue.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.
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 tofalse.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
loadTimeEstimatesbe called on the first call todownloadafter application startup, andsaveTimeEstimatesbe called after eachdownload? Defaults totrue.See also
timeEstimatesFile.Declaration
Swift
@inline(__always) public final var autoSaveEstimates: Bool { get set } -
Maximum amount of time that
waitForCompletionshould 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.cancelone request at a time.See also
getQueuedRequests,getFailedRequests.Declaration
Swift
open func cancelPendingRequests(_ requests: PendingRequestList?) throwsParameters
requestsPending 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
hasMetadataChangeswould returntrue, then return a list of the entity sets that need to be re-downloaded.Declaration
Swift
open func changedEntitySets() throws -> EntitySetListReturn Value
List of entity sets that have metadata changes.
-
Clear this provider. This will
closethe 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. See also
SAP Offline Vocabulary.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.See also
RequestOptions.canCombineRequests.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.See also
RequestOptions.canCombineRequests.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).
Declaration
Swift
open func createDownloadQuery(name: String, query: DataQuery, streams: Bool) throwsParameters
nameQuery name. Must be unique.
queryData query. Use
DataQuery.fromto specify the query’s entity set.streamsIf
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
createIndexby accepting string-typed parameters. It is applicable even whenmetadatais not yet available.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
entitySetName of entity set for which index will be created.
itemFirst item to be indexed. This is a property name (e.g. “Quantity”) or property path (e.g. “Address/City”).
rest_itemsOptional additional items for a composite index.
-
Create an entity in the target system. Automatically calls
CsdlDocument.resolveEntityto ensure thatEntityValue.entitySetis available.Throws
DataServiceExceptionif the entity set hasn’t been explicitly provided before callingcreateEntityand 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) throwsParameters
entityEntity to be created.
headersRequest-specific headers.
optionsRequest-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).
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...) -
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) throwsParameters
fromSource entity for the link to be created.
propertySource navigation property for the link to be created.
toTarget entity for the link to be created.
headersRequest-specific headers.
optionsRequest-specific options.
-
Create a media entity with the specified content in the target system. If the
entityhas non-stream structural properties in addition to the key properties and media content, such aslabelin 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) throwsParameters
entityEntity to be created.
contentInitial content. Must be a
ByteStreamorCharStream. Will be closed before this function returns.headersRequest-specific headers.
optionsRequest-specific options.
-
Current user name for
open. Set this before callingopen. Note: setting this property does not have any affect on authentication of HTTP requests issued byuploadanddownload. The associatedonlineProviderneeds 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) throwsParameters
queryData query specifying the information to be deleted.
headersRequest-specific headers.
optionsRequest-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) throwsParameters
nameQuery name.
-
Delete an entity from the target system.
Declaration
Swift
open func deleteEntity(_ entity: EntityValue, headers: HTTPHeaders, options: RequestOptions) throwsParameters
entityEntity to be deleted.
headersRequest-specific headers.
optionsRequest-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) throwsParameters
fromSource entity for the link to be deleted.
propertySource navigation property for the link to be deleted.
toTarget entity for the link to be deleted.
headersRequest-specific headers.
optionsRequest-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) throwsParameters
entityEntity containing the stream property whose content is to be deleted.
headersRequest-specific headers.
optionsRequest-specific options.
linkStream link for the stream to be deleted.
-
Download backend data changes into the local database.
Declaration
Swift
open func download(groups: StringList, options: SyncOptions) throwsParameters
groupsIf null or empty, then data will be downloaded from all entity sets. If non-empty, then it specifies groups to be downloaded.
optionsDownload 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) -> DownloadGroupParameters
groupName 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 enablebatchEntityDownloadsandbatchStreamDownloads(where supported by the backend service). UsingDownloadMode.parallelorDownloadMode.sequencemight 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 callgetDownloadGroupand 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
groupDownload group name.
rest_entitySetsA 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 callgetDownloadPhaseand 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
phaseDownload 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_entitySetsA 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 -> ByteStreamParameters
entityEntity whose content is to be downloaded.
headersRequest-specific headers.
optionsRequest-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) -> DownloadPhaseParameters
phaseNumber of download phase.
Return Value
A download phase.
-
Retrieve all of the persistent queries previously created by
createDownloadQueryfor a specified entity set.Declaration
Swift
open func downloadQueries(from: EntitySet? = nil) throws -> DownloadQueryListParameters
fromEntity 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.filterfor 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.Declaration
Swift
open func downloadQueriesCanOverlap(_ entitySets: EntitySet...)Parameters
rest_entitySetsA list of entity sets whose
downloadQueriesCanOverlapproperty will be set totrue. 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
nameQuery name.
Return Value
The download query, or
nilif 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 -> ByteStreamParameters
entityEntity containing the stream property whose content is to be downloaded.
linkStream link for the stream to be downloaded.
headersRequest-specific headers.
optionsRequest-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 totrue. If you are considering setting this property totrue, please evaluate the client-side resource utilization, and consider the alternative option of delta-enabling the backend system.See also
EntitySet.downloadWithoutDeltaLinks.Declaration
Swift
open func downloadWithoutDeltaLinks(_ entitySets: EntitySet...)Parameters
rest_entitySetsA list of entity sets whose
downloadWithoutDeltaLinksproperty will be set totrue. 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 appropriateReferentialConstraintelements.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 appropriateReferentialConstraintelements.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 callingopen.See also
SQLDatabaseProvider.encryptionKey.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
10threads. 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 -> SyncEventListParameters
queryIf specified, then
DataQuery.queryFilterwill be used for event filtering andDataQuery.sortItemswill 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
DataServiceExceptionorDataNetworkExceptionif an error occurs during action invocation.Declaration
Swift
open func executeMethod(_ method: DataMethod, parameters: ParameterList, headers: HTTPHeaders, options: RequestOptions) throws -> DataValue?Parameters
methodData method.
parametersMethod parameters.
headersRequest-specific headers.
optionsRequest-specific options.
Return Value
The method result, or
nilif 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 -> QueryResultParameters
queryData query specifying the information to be returned.
headersRequest-specific headers.
optionsRequest-specific options.
Return Value
The query result.
-
Declaration
Swift
open func failedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> PendingRequestListParameters
queryIf specified, then
DataQuery.entitySetandDataQuery.queryFilterwill be used for request filtering andDataQuery.sortItemswill be used for result ordering. If not specified (or null), all failed requests will be returned.headersIf specified, then the returned pending requests will be further filtered to include only those with matching headers.
optionsIf 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
metadataproperty.See also
loadMetadata.Declaration
Swift
open func fetchMetadata(headers: HTTPHeaders, options: RequestOptions) throws -> CSDLDocumentParameters
headersOptional request-specific headers.
optionsOptional request-specific options.
Return Value
Latest service metadata.
-
If
currentUserdoesn’t matchgetPreviousUserwhenopenis called, shouldopenimplicitly calldownload? Defaults tofalse. If this flag istrueandforceUploadOnUserSwitchis alsotrue, thenuploadwill be called beforedownload.Declaration
Swift
@inline(__always) public final var forceDownloadOnUserSwitch: Bool { get set } -
If
currentUserdoesn’t matchgetPreviousUserwhenopenis called, shouldopenimplicitly callupload? Defaults tofalse. If this flag istrueandforceDownloadOnUserSwitchis alsotrue, thenuploadwill be called beforedownload.Declaration
Swift
@inline(__always) public final var forceUploadOnUserSwitch: Bool { get set } -
Declaration
Swift
open func hasFailedRequests(matching query: DataQuery?, headers: HTTPHeaders?, options: RequestOptions?) throws -> BoolParameters
queryIf specified, then
DataQuery.entitySetandDataQuery.queryFilterwill be used for request filtering.headersIf specified, then the returned pending requests will be further filtered to include only those with matching headers.
optionsIf 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
trueif there are any failed requests in the local database (matching thequery, if specified). -
Declaration
Swift
open func hasInitialData() throws -> BoolReturn Value
trueif adownloadhas 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.
Declaration
Swift
open func hasMetadataChanges() throws -> BoolReturn Value
trueif this provider has detected metadata changes. -
Declaration
Swift
open func hasPendingDownload() throws -> BoolReturn Value
trueif adownloadis 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 -> BoolReturn Value
trueif anuploadis 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 -> BoolParameters
queryIf specified, then
DataQuery.entitySetandDataQuery.queryFilterwill be used for request filtering.headersIf specified, then the returned pending requests will be further filtered to include only those with matching headers.
optionsIf 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
trueif there are any queued requests in the local database (matching thequery, if specified). -
Checks locally whether a previous
registerClientcall successfuly created a client registration for the remote OData service.Declaration
Swift
open func isClientRegistered() throws -> BoolReturn Value
trueif a registration was already established. -
Declaration
Swift
open func lastDownloadTime() throws -> GlobalDateTime?Return Value
Date and time for the last
downloadrequest. -
Declaration
Swift
open func lastUploadTime() throws -> GlobalDateTime?Return Value
Date and time for the last
uploadrequest. -
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) throwsParameters
entityPreviously loaded entity, whose properties will be modified to reflect the loaded state.
queryOptional data query, to specify loading criteria (especially for navigation properties).
headersOptional request-specific headers.
optionsOptional request-specific options.
-
Load service metadata (if not already loaded).
Declaration
Swift
open func loadMetadata(headers: HTTPHeaders, options: RequestOptions) throwsParameters
headersOptional request-specific headers.
optionsOptional request-specific options.
-
Load previously saved download time estimates from
file.Declaration
Swift
open func loadTimeEstimates(file: String, mustExist: Bool = false) throwsParameters
fileTime estimates file.
mustExistSpecify
trueif the file must exist. Existing in-memory time estimates remain unchanged if this parameter isfalseand 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.See also
EntitySet.downloadEntitiesByDefault.Declaration
Swift
open func noDefaultEntityDownload(_ entitySets: EntitySet...)Parameters
rest_entitySetsA list of entity sets whose
downloadEntitiesByDefaultproperty will be set tofalse. 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.
See also
EntitySet.downloadStreamsByDefault.Declaration
Swift
open func noDefaultStreamDownload(_ entitySets: EntitySet...)Parameters
rest_entitySetsA list of entity sets whose
downloadStreamsByDefaultproperty will be set tofalse. 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
forceUploadOnUserSwitchand/orforceDownloadOnUserSwitchis 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) throwsParameters
headersOptional request-specific headers.
optionsOptional request-specific options.
-
Should
downloadprefer compact responses such as Compact JSON encoding? Defaults totrue.Declaration
Swift
@inline(__always) public final var preferCompactResponses: Bool { get set } -
Should
traceWithDatashow pretty-printed JSON/XML content? Defaults tofalse.Declaration
Swift
open var prettyTracing: Bool { get set } -
Declaration
Swift
open func previousUser() throws -> String?Return Value
The
currentUserafteropenwas last called. -
Execute a request batch in the target system.
Declaration
Swift
open func processBatch(_ batch: RequestBatch, headers: HTTPHeaders, options: RequestOptions) throwsParameters
batchThe request batch.
headersRequest-specific headers.
optionsRequest-specific options.
-
Progress listener for
downloadandupload.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 -> PendingRequestListParameters
queryIf specified, then
DataQuery.entitySetandDataQuery.queryFilterwill be used for request filtering andDataQuery.sortItemswill be used for result ordering. If not specified (or null), all queued requests will be returned.headersIf specified, then the returned pending requests will be further filtered to include only those with matching headers.
optionsIf 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
isClientRegisteredwould returnfalse, 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 theServiceOptions.clientInstanceID. The server’s metadata is expected to include aClientRegistrationSetentity set with entity typeClientRegistration, a key property namedClientIDof typelong(Edm.Int64), and a property namedClientGUIDof typeguid(Edm.Guid). If a new registration is successfully created,ServiceOptions.clientInstanceIDis set, and will subsequently be used to populate theClient-Instance-IDHTTP 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?) throwsParameters
clientInstance of
ClientRegistrationentity 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) throwsParameters
fileTime estimates file.
-
Should
uploadsend Repeatable Requests? Defaults totrue.See also
ServiceOptions.supportsRepeatability.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
downloadphase. Selecting modeanymeans 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
phaseDownload phase.
modeDownload mode.
-
If the backend supports stream download for offline operation, should it be done with multiple threads in parallel? Defaults to
10threads. 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
uploadthrow an exception if one or more requests has a service failure due to an HTTP response with a non-successful HTTP status code? Defaults tofalse. Note: if a request fails due to any condition where an HTTP response status code cannot be obtained (e.g. a network failure), anuploadcall should always throw an exception.Declaration
Swift
@inline(__always) public final var throwUploadFailures: Bool { get set } -
Name to be used for time estimates file if
autoSaveEstimatesistrue.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
uploadtrace upload failures if one or more requests has a service failure due to an HTTP response with a non-successful HTTP status code? Defaults tofalse. Note: if a request fails due to any condition where an HTTP response status code cannot be obtained (e.g. a network failure), anuploadcall should always log an error (but without request details). Enabling tracing of upload failures can result in sensitive data being included in the log.See also
PendingRequestList.logError,PendingRequestList.includeHeaders,PendingRequestList.includeContent,PendingRequestList.hideCredentials.Declaration
Swift
@inline(__always) public final var traceUploadFailures: Bool { get set } -
If
traceRequestsis alsotrue, should all requests for this data service be traced with data? Defaults tofalse. 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) throwsParameters
entitiesA list of entities whose pending changes will be undone.
-
Unload service metadata (if previously loaded).
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 thedeleteFromServerparameter istrue.Declaration
Swift
open func unregisterClient(deleteFromServer: Bool) throwsParameters
deleteFromServerSpecify a value of
trueto 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) throwsParameters
entityEntity to be updated.
headersRequest-specific headers.
optionsRequest-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) throwsParameters
fromSource entity for the link to be updated.
propertySource navigation property for the link to be updated. This must be a one-to-one navigation property.
toTarget entity for the link to be updated.
headersRequest-specific headers.
optionsRequest-specific options.
-
Upload data changes for all uploadable entity sets.
Declaration
Swift
open func upload(groups: StringList, options: SyncOptions) throwsParameters
groupsIf empty, then data will be uploaded from all entity sets. If non-empty, then it specifies groups to be included.
optionsUpload 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
encryptionKeyis null, this operation might fail (depending on the provider). Note: if the local database is not encrypted, andencryptionKeyis non-null, this operation might fail (depending on the provider).Declaration
Swift
open func uploadDatabaseFile(encryptionKey: String?, note: String?, options: SyncOptions) throwsParameters
encryptionKeyEncryption key for the uploaded database, which may differ from the encryption key of the local database (if any).
noteAssociated note for trusted users who have access to uploaded databases for diagnostic purposes.
optionsUpload 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 enablebatchEntityUploadsandbatchStreamUploads(where supported by the backend service).See also
downloadInBackground.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,000bytes. 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) throwsParameters
entityEntity whose content is to be uploaded.
contentUpload stream content. Will be closed before this function returns.
headersRequest-specific headers.
optionsRequest-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) throwsParameters
entityEntity containing the stream property whose content is to be uploaded.
linkStream link for the stream to be uploaded.
contentUpload stream content. Will be closed before this function returns.
headersRequest-specific headers.
optionsRequest-specific options.
-
If the backend supports request upload for offline operation, should it be done with multiple threads in parallel? Defaults to
10threads. 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
handleEventsForBackgroundURLSessioncallback.Declaration
Swift
open func waitForCompletion(sessionIdentifier: String, completionHandler: @Sendable @escaping () -> Void)