---
title: NowTableService class - iOS
description: The NowTableService class provides functions that enable you to perform create, read, update, and delete operations on records of existing ServiceNow tables.Inserts the specified Codable model into the specified table.Inserts the specified Codable model into the specified table and then executes the completion handler.Inserts one Codable model into the specified table.Inserts a record in the specified table that contains the specified fields.Inserts the specified record in the specified table and then executes the completion handler after the record is saved.Inserts a record in the specified table that contains the specified fields.Deletes the specified Codable model from the specified table.Deletes the specified Codable model from the specified table and then executes the appropriate completion handler.Deletes the specified Codable model from the specified table.Deletes the specified record from the specified table.Deletes the specified record from the specified table and then executes the completion object after the record is deleted.Deletes the specified record from the specified table.Creates a NowTableService object.Enables the retrieval of decodable model\(s\) from a specified table.Retrieves decodable model\(s\) from a specified table.Creates a publisher that enables the retrieval of decodable model\(s\) from a specified table.Creates a paginator that enables iterating through pages of records.Creates a paginator that enables the iteration of pages of decoded model\(s\) that handle nesting.Retrieves a specified record from the specified table on a ServiceNow instance.Retrieves the specified record from the specified table and then executes a completion handler after the record is retrieved.Creates a publisher to retrieve a specified record from the specified table on a ServiceNow instance.Retrieves records from the specified table.Retrieves records from a specified table and then executes the completion handler after the records are retrieved.Creates a publisher that enable you to retrieve records from the specified table.Updates the specified Codable model in the specified table.Updates the specified Codable model in the specified table and then executes the completion handler.Updates the specified codable model in the specified table.Updates the specified record with the specified fields.Updates the specified record with the specified fields then executes the completion handler once the record is saved.Updates the specified record with the specified fields.
locale: en-US
canonical_url: https://www.servicenow.com/docs/r/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.html
release: australia
product: Cllent Mobile API Reference
classification: cllent-mobile-api-reference
topic_type: concept
last_updated: "2026-03-12"
reading_time_minutes: 76
breadcrumb: [Mobile SDK - iOS, Mobile SDK API reference, API reference, API implementation and reference]
---
# NowTableService class- iOS
The NowTableService class provides functions that enable you to perform create, read, update, and delete operations on records of existing ServiceNow tables.
|Name|Type|Description|
|----|----|-----------|
|configuration|[NowServiceConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowServiceConfigurationiOSStruct.md)|Configuration settings provided when the service was initialized.|
**Parent Topic:**[Mobile SDK - iOS](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/MobileSDKiOSAPI.md)
## NowTableService - create<Model: SysIdentifiableModel>\(\_ model: Model, in tableName: String, coder: Coder, writeOptions: FieldWriteOptions, configuration: FetchConfiguration\) async throws
Inserts the specified Codable model into the specified table.
In order to create a new record by model, the model must conform to the `SysIdentifiableModel` protocol. Each table will typically have its own model.
The model's **sys\_Id** parameter is ignored during creation as the **sysId** is generated by the ServiceNow platform. The ServiceNow platform generated **sys\_Id** is returned in the **completion** handler's `Result` model.
|
Name
|
Type
|
Description
|
|---|
|
model
|
SysIdentifiableModel
|
Model definition of the fields to insert into the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Model
|
Returned when the method is successful. Codable model that was inserted in the specified table, including the sys\_Id. Use this sys\_id to reference this record in future method calls.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code example shows how to call this method.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
do {
let result = try await service.create(user, in: “sys_user”)
} catch {
...
}
```
## NowTableService - create<Model: SysIdentifiableModel>\(\_ model: Model, in tableName: String, coder: Coder, writeOptions: FieldWriteOptions, configuration: FetchConfiguration, completion: @escaping \(Result<Model, NowDataError>\)\)
Inserts the specified Codable model into the specified table and then executes the **completion** handler.
In order to create a new record by model, the model must conform to the `SysIdentifiableModel` protocol. Each table will typically have its own model. For example:
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
service.create(Incident(fields: fields), in: tableName, writeOptions: writeOptions, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let newUser):
/// 'newUser' contains the platform assigned 'sys_id', use in subsequent 'update' or 'delete' calls.
case .failure(let error):
...
}
}
```
The model's **sys\_Id** parameter is ignored during creation as the **sysId** is generated by the ServiceNow platform. The ServiceNow platform generated **sys\_Id** is returned in the **completion** handler's `Result` model.
|
Name
|
Type
|
Description
|
|---|
|
model
|
SysIdentifiableModel
|
Model definition of the fields to insert into the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Model, NowDataError>\)
|
Completion handler to execute after creating the specified decodable model\(s\).Return values for the completion handler:
- Success: Model - Data for the created model type.
- Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
service.create(Incident(fields: fields), in: tableName, writeOptions: writeOptions, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let newUser):
/// 'newUser' contains the platform assigned 'sys_id' to use in subsequent update or delete calls.
case .failure(let error):
...
}
}
```
## NowTableService - create<Model: SysIdentifiableModel>\(model: Model, in tableName: String, path: String = Constants.resultPath, coder: Coder = .default, writeOptions: FieldWriteOptions? = nil, configuration: FetchConfiguration = nil\)
Inserts one Codable model into the specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
In order to create a new record by model, the model must conform to the `SysIdentifiableModel` protocol. Each table will typically have its own model. For example:
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
service.create(Incident(fields: fields), in: tableName, writeOptions: writeOptions, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let newUser):
/// 'newUser' contains the platform assigned 'sys_id', use in subsequent 'update' or 'delete' calls.
case .failure(let error):
...
}
}
```
**Note:** The model's **sys\_Id** parameter is ignored during creation. The **sysId** is assigned by the ServiceNow platform. The ServiceNow platform generated **sys\_Id** is returned in the publisher's `receiveValue` callback model.
|
Name
|
Type
|
Description
|
|---|
|
model
|
SysIdentifiableModel
|
`SysIdentifiableModel` model to insert into the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
path
|
String
|
Optional. Dot separated path for the nested type. For example, `result` or `foo.bar.baz` for deeper nesting.Default: `Constants.resultPath`
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Model,NowDataError>
|
Success: Codable model that was inserted in the specified table, including **sys\_Id**. Use this sys\_id to reference this record in future method calls.Failure: NowDataError
@escaping \(Result<Model, NowDataError>\)
|
Shows how to insert a single record into the User \[sys\_user\] table.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
let publisher: AnyPublisher = service.create(user, in: "sys_user")
publisher
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
...
} receiveValue: { [weak self] newUser in
/// 'newUser' contains the ServiceNow platform assigned 'sys_id' to use in subsequent update and delete calls.
...
}
.store(in: &subscriptions)
```
## NowTableService - createRecord\(with fields: \[FieldName: FieldValue\], in tableName: String, writeOptions: FieldWriteOptions? = nil, configuration: FieldReadConfiguration? = nil\) async throws
Inserts a record in the specified table that contains the specified fields.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Data
|
Returned when the method is successful. Data object containing the new record.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
do {
let dataResult: Data = try await tableService.createRecord(with: fields, in: tableName, writeOptions: writeOptions, configuration: configuration)
let recordResult: NowRecord = dataResult.convertToRecord()
} catch {
print("Record creation failed with NowDataError: \(error)")
}
```
## NowTableService - createRecord\(with fields: \[FieldName: FieldValue\], in tableName: String, writeOptions: FieldWriteOptions, configuration: FieldReadConfiguration, completion: @escaping \(Result<Data, NowDataError>\)
Inserts the specified record in the specified table and then executes the **completion** handler after the record is saved.
If needed, you can decode the return results into a custom Codable model or you can use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function instead. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myResult.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FieldReadConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldReadConfigurationiOSStruct.md)
|
Optional. Configuration options that specify which fields to return and what to include in the fields.Default: nil
|
|
completion
|
@escaping \(Result<Data, NowDataError>\)
|
Completion handler to execute after the records are retrieved. Return values:
- Success: Data - Requested records
- Error: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this function.
```
let fields = ["short_description" : "test description"]
let writeOptions: FieldWriteOptions = [.suppressAutoSysField, .treatInputValuesAsDisplayValues]
let readConfiguration = FieldReadConfiguration(includeFields: ["number", "short_description"])
tableService.createRecord(with: fields, in: tableName, writeOptions: writeOptions, configuration: readConfiguration) { [weak self] result in
switch result {
case .success(let dataResult):
let recordResult: NowRecord = dataResult.convertToRecord()
case .failure(let error):
print("Record creation failed with NowDataError: \(error)")
}
}
```
## NowTableService - createRecord\(with fields: \[FieldName: FieldValue\], in tableName: String, writeOptions: FieldWriteOptions? = nil, configuration: FieldReadConfiguration? = nil\)
Inserts a record in the specified table that contains the specified fields.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Data, NowDataError>
|
Success: Data object containing the updated record.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to create a function that inserts a record in the specified table, with the specified fields. The output of the call is a ByteArray which allows you to convert the data into any model that you want.
```
tableService.createRecord(with: fields, in: tableName, writeOptions: writeOptions, configuration: readConfiguration)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.convertToRecord()
.sink { completion in
if case let .failure(error) = completion {
print("Record creation failed with NowDataError: \(error)")
}
} receiveValue: { record in
print("Created NowRecord: \(record)")
}
.store(in: &subscriptions)
```
## NowTableService - delete\(\_ model: Model, from tableName: String\) async throws
Deletes the specified Codable model from the specified table.
|Name|Type|Description|
|----|----|-----------|
|model|Model|`SysIdentifiableModel` to delete from the table. It should contain the sys\_id of the record to delete.|
|from tableName|String|Name of the table from which to delete the information, such as incident.|
|
Type
|
Description
|
|---|
|
None
|
Nothing returned when the method is successful.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
do {
try await tableService.delete(model, from: tableName)
print("Deletion successful.")
} catch {
print("Deletion failed with NowDataError: \(error)")
}
```
## NowTableService - delete\(\_ model: Model, from tableName: String, completion: @escaping \(Result<Void, NowDataError>\)\)
Deletes the specified Codable model from the specified table and then executes the appropriate **completion** handler.
|
Name
|
Type
|
Description
|
|---|
|
model
|
Model
|
`SysIdentifiableModel` to delete from the table. It should contain the sys\_id of the record to delete.
|
|
from tableName
|
String
|
Name of the table from which to delete the information, such as incident.
|
|
completion
|
@escaping \(Result<Void, NowDataError>\)
|
Completion handler to execute after deleting the specified codable model\(s\).Return values:
- Success: Nothing returned
- Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this function.
```
tableService.delete(Incident(sysId: sysId), from: tableName) { [weak self] result in
switch result {
case .success:
// Delete successfully
case .failure(let error):
// Failed to delete with NowDataError
}
}
```
## NowTableService - delete\(\_ model: Model, from tableName: String\)
Deletes the specified Codable model from the specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
|Name|Type|Description|
|----|----|-----------|
|model|Model|`SysIdentifiableModel` to delete from the table. It should contain the sys\_id of the record to delete.|
|from tableName|String|Name of the table from which to delete the information, such as incident.|
|
Type
|
Description
|
|---|
|
AnyPublisher<Void, NowDataError>
|
Success: Nothing returnedFailure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code example shows how to call this function.
```
tableService.delete(Incident(sysId: sysId), from: tableName)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
switch completion {
case .finished:
// Delete successfully
case .failure(let error):
// Failed to delete with NowDataError
}
} receiveValue: { _ in
}
.store(in: &subscriptions)
```
## NowTableService - deleteRecord\(sysId: SysID, from tableName: String\) async throws
Deletes the specified record from the specified table.
|Name|Type|Description|
|----|----|-----------|
|sysId|String|Sys\_id of the record to delete.|
|from tableName|String|Name of the table from which to delete the information, such as incident.|
|
Type
|
Description
|
|---|
|
None
|
Nothing returned when the method is successful.
|
|
NowDataError
|
Thrown when the method fails.- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
do {
try await tableService.deleteRecord(sysId: sysId, from: tableName)
print("Deletion successful.")
} catch {
print("Deletion failed with NowDataError: \(error)")
}
```
## NowTableService - deleteRecord\(sysId: SysID, from tableName: String, completion: @escaping \(Result<Void, NowDataError>\)\)
Deletes the specified record from the specified table and then executes the **completion** object after the record is deleted.
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to delete.
|
|
from tableName
|
String
|
Name of the table from which to delete the information, such as incident.
|
|
completion
|
@escaping \(Result<Void, NowDataError>\)
|
Success: Nothing is returned.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this function.
```
tableService.deleteRecord(sysId: sysId, from: tableName) { [weak self] result in
switch result {
case .success:
// Delete successfully
case .failure(let error):
// Failed to delete with NowDataError
}
}
```
## NowTableService - deleteRecord\(sysId: SysID, from tableName: String\)
Deletes the specified record from the specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
|Name|Type|Description|
|----|----|-----------|
|sysId|String|Sys\_id of the record to delete.|
|from tableName|String|Name of the table from which to delete the information, such as incident.|
|
Type
|
Description
|
|---|
|
AnyPublisher<Void, NowDataError>
|
Success: Nothing returnedFailure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to create a function that deletes a record in a specified table.
```
tableService.deleteRecord(sysId: sysId, from: tableName)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.sink { completion in
switch completion {
case .finished:
print("Record deleted.")
case .failure(let error):
print("Deletion failed with NowDataError: \(error)")
}
} receiveValue: { _ in }
.store(in: &subscriptions)
```
## NowServiceTable - init\(configuration: NowServiceConfiguration, coreServiceProvider: NowCoreServiceProviding? = nil\)
Creates a NowTableService object.
|
Name
|
Type
|
Description
|
|---|
|
configuration
|
[NowServiceConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowServiceConfigurationiOSStruct.md)
|
Configuration parameters to use when creating the service.
|
|
coreServiceProvider
|
NowCoreServiceProviding
|
Optional. Service provider to associate with the NowTableService.Default: nil
|
The following code example shows how to call this function.
```
guard let coreService = NowSDK.core() else {
// Error with NowServiceError.sdkNotConfigured
return
}
guard
let instanceUrl = URL(string: "http://sample.service-now.com") ,
let serviceConfig = NowSDK.makeServiceConfiguration(for: instanceUrl) else {
// Could not create service –
// NowServiceError.serviceConfigurationInvalid
return
}
let tableService = NowTableService (configuration: serviceConfig, coreServiceProvider: coreService)
```
## NowTableService - model<Model: Decodable>\(with sysId: SysID? = nil, from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\) async throws
Enables the retrieval of decodable model\(s\) from a specified table.
Table API responses are nested inside a **result** parameter similar to the following:
```
{
"result": [
{ "name": "Ash Williams" },
{ "name": "Lionel Cosgrove" },
{ "name": "Laurie Strode" }
]
}
```
For large result sets, use one of the paginator functions, [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) or [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) to fetch paginated models.
|
Name
|
Type
|
Description
|
|---|
|
with sysId
|
SysID
|
Optional. Sys\_id of the record to return. Provide the sys\_id if you want to retrieve a specific record.Default: nil
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
path
|
String
|
Dot separated path for the nested type. For example, `result` or `foo.bar.baz` for deeper nesting.Default: `result`
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Model
|
Returned when the method is successful. Decodable model\(s\).
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code example shows how to call this method.
```
struct User: Codable {
var name: String
}
let service: NowTableService = ...
do {
let result = try await service.model([User].self, from: "sys_user", path: "result")
print("Fetched \(users.count) users")
} catch {
dump(error)
}
```
The following code example shows how to fetch a single Decodable model by sys\_id. Use a single model type, such as `User.self`, rather than `[User].self`.
```
let result = try await service.model(User.self, with: "5137153cc611227c000bbd1bd8cd2005", from: "sys_user", path: "result")
```
## NowTableService - model<Model: Decodable>\(\_ type: Model.Type, with sysId: SysID? = nil, from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil, completion: @escaping \(Result<Model, NowDataError>\)\)
Retrieves decodable model\(s\) from a specified table.
Table API responses are nested inside a **result** parameter similar to the following:
```
{
"result": [
{ "name": "Ash Williams" },
{ "name": "Lionel Cosgrove" },
{ "name": "Laurie Strode" }
]
}
```
Use this function to obtain decodable models instead of nested output.
|
Name
|
Type
|
Description
|
|---|
|
type
|
Model.Type
|
Type of value to decode.
|
|
with sysId
|
String
|
Optional. Sys\_id of the record to return.Default: All records returned per the **configuration** settings.
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
path
|
String
|
Optional. Dot separated path for the nested type. For example, `result` or `foo.bar.baz` for deeper nesting.Default: `Constants.resultPath`
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Default: `.default`
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Model, NowDataError>\)
|
Completion handler to execute after retrieving the specified decodable model\(s\).Return values for the completion handler:
- Success: Data for the requested model type.
- Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
To retrieve a collection of decoded **User** models.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let service: NowTableService = ...
let user = User(name: "Ash Williams")
service.create(Incident(fields: fields), in: tableName, writeOptions: writeOptions, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let newUser):
/// 'newUser' contains the platform assigned 'sys_id', use in subsequent 'update' or 'delete' calls.
case .failure(let error):
...
}
}
```
To fetch a single decodable model by sys\_id, use a single model type, such as `User.self`, rather than `[User].self`.
```
service.model(User.self, with: "5137153cc611227c000bbd1bd8cd2005", from: "sys_user", path: "result") { resultin ... }
```
## NowTableService - model<Model: Decodable>\(with sysId: SysID? = nil, from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)
Creates a publisher that enables the retrieval of decodable model\(s\) from a specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
Table API responses are nested inside a **result** parameter similar to the following:
```
{
"result": [
{ "name": "Ash Williams" },
{ "name": "Lionel Cosgrove" },
{ "name": "Laurie Strode" }
]
}
```
For large result sets, use one of the paginator functions, [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) or [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) to fetch paginated models.
|
Name
|
Type
|
Description
|
|---|
|
with sysId
|
SysID
|
Optional. Sys\_id of the record to return. Provide the sys\_id if you want to retrieve a specific record.Default: nil
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
path
|
String
|
Dot separated path for the nested type. For example, `result` or `foo.bar.baz` for deeper nesting.Default: `result`
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Model, NowDataError>
|
Success: Publisher returning a decodable model\(s\).Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
To obtain a publisher that provides decoded User models by type, such as `[Users].self`, fetch the models by specifying a dot-separated path.
```
struct User: Codable {
varname: String
}
let service: NowTableService = ...
let publisher: AnyPublisher<[User], NowDataError> = service.model(from: "sys_user", path: "user.photos.gps_location")
```
To fetch a single decodable model by sys\_id, use a single `User.self` model type, rather than `[User].self`.
```
let publisher: AnyPublisher = service.model(with: "5137153cc611227c000bbd1bd8cd2005", from: "sys_user", path: "result")
```
## NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)
Creates a paginator that enables iterating through pages of records.
The paginator's publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
**Note:** Unless overridden in the **configuration** parameter, a paginator returns 20 items per page. Depending on ACL evaluation, the actual number of fetched items for a page might be less than the default or configured value.
|
Name
|
Type
|
Description
|
|---|
|
tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Paginator<Data>
|
Success: Paginator object containing the specified records.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
```
private var tableService: NowTableService?
// Paginator creation uses type inference to determine the response type.
private var paginator: Paginator<[CustomerServiceCase]>?
func initializeTableService(for instanceUrl: URL) {
makeTableService(instanceUrl: instanceUrl) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let tableService):
self.tableService = tableService
// Create a paginator that iterates over pages of customer support cases. The paginator's response type is
// inferred from the paginator's type definition (e.g. `Paginator<[CustomerServiceCase]>`).
self.paginator = tableService.paginator(from: Self.tableName, configuration: self.fetchConfiguration)
// Subscribe to the paginator's publisher so you are able to receive paged results.
self.subscribeToPaginatorPublisher()
// Ready to start fetching data, inform the view controller.
self.onReady(self)
case .failure(let error):
debugPrint("Creating table service failed with error: \(error.localizedDescription)")
self.tableService = nil
self.paginator = nil
}
}
}
```
## NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)
Creates a paginator that enables the iteration of pages of decoded model\(s\) that handle nesting.
The ServiceNow REST Table API responses are nested inside a result property similar to the following:
```
{
"result": [
{ "name": "Ash Williams" },
{ "name": "Lionel Cosgrove" },
{ "name": "Laurie Strode" }
]
}
```
To obtain a paginator that provides decoded User models, fetch the paginator by specifying a dot-separated path; in this case, **result**.
```
struct User: Codable {
varname: String
}
let service: NowTableService = ...
let paginator: Paginator<[User]> = service.paginator(from: "sys_user", path: "result")
```
**Note:** Unless overridden in the **configuration** parameter, a paginator returns 20 items per page. Depending on the ACL evaluations, the actual number of fetched items for a page might be less than the default or configured value.
After obtaining a Paginator object, subscribe to its Combine Publisher to start receiving data:
```
paginator.publisher
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.sink { … }
.store(in: &subscriptions)
```
**Note:** As with all Combine subscriptions, ensure that you retain the subscription to avoid unexpected results.
|
Name
|
Type
|
Description
|
|---|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
path
|
String
|
Dot separated path for the nested type. For example, `result` or `result.user.photos` for deeper nesting. Specifying a custom path allows fetching or iterating over nested data*.*Default: `result`
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Paginator<Data>
|
Success: Paginator object containing paged `Decodable` model\(s\).Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to obtain a Paginator object that provides decoded User models. You can fetch the desired Paginator object by hinting the compiler to return a collection of User models \(\[User\]\) and informing the Paginator object that the users are nested beneath the result path.
```
struct User: Codable {
var name: String
}
let service: NowTableService = ...
let paginator: Paginator<[User]> = service.paginator(from: "sys_user", path: "result")
```
**Note:** The Table API always returns results nested beneath a result path, so you can safely eliminate the **path** parameter.
## NowTableService - record\(with sysId: SysID, from tableName: String, configuration: FieldReadConfiguration? = nil\) async throws
Retrieves a specified record from the specified table on a ServiceNow instance.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Data
|
Returned when the method is successful. Data object containing the specified record.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
func fetchTableRecord(sysId: String, tableName: String, includeFields: [FieldName] = [FieldName](), readOptions: FieldReadConfiguration.Options = []) async throws -> NowRecord {
let readConfig = FieldReadConfiguration(includeFields: includeFields, options: readOptions)
do {
let dataResult: Data = try await tableService.record(with: sysId, from: tableName, configuration: configuration)
let recordResult: NowRecord = dataResult.convertToRecord()
return recordResult
} catch {
print("Fetch failed with NowDataError: \(error)")
throw error
}
}
```
## NowTableService - record\(with sysId: SysID, from tableName: String, configuration: FieldReadConfiguration, completion: @escaping \(Result<Data, NowDataError>\)
Retrieves the specified record from the specified table and then executes a completion handler after the record is retrieved.
If needed, you can decode the return results into a custom Codable model or you can use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function instead. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myResult.convertToRecords()
```
For large result sets, use the [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function to fetch paginated results.
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Data, NowDataError>\)
|
Completion handler to execute after the records are retrieved. Return values:
- Success: Data - Requested records
- Error: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this method.
```
func fetchTableRecords( tableName: String, filterQuery: String, includeFields: [FieldName] = [FieldName](), readOptions: FieldReadConfiguration.Options = [], limit: Int?) {
let readConfig = FieldReadConfiguration(includeFields: includeFields, options: readOptions)
let config = FetchConfiguration(Filter(query: filterQuery), limit, readConfig)
tableService.records (from: tableName, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let dataResult):
let recordResult: [NowRecord] = dataResult.convertToRecords()
// Return recordResult
case .failure(let error):
// Failed to fetch record with NowDataError
}
}
}
```
## NowTableService - record\(with sysId: SysID, from tableName: String, configuration: FieldReadConfiguration? = nil\)
Creates a publisher to retrieve a specified record from the specified table on a ServiceNow instance.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Data, NowDataError>
|
Success: Data object containing the specified records.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to create a function that retrieves the specified record from the specified table, with the specified fields. The output of the call is a ByteArray which allows you to convert the data into any model that you want.
```
tableService.record(with: sysId, from: tableName, configuration: fetchConfiguration)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.convertToRecord()
.sink { completion in
if case let .failure(error) = completion {
print("Record retrieval failed with NowDataError: \(error)")
}
} receiveValue: { record in
print("Successfully retrieved record: \(record)")
}
.store(in: &subscriptions)
```
## NowTableService - records\(from tableName: String, configuration: FetchConfiguration? = nil\) async throws
Retrieves records from the specified table.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
For large result sets, use the [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function to fetch paginated results.
|
Name
|
Type
|
Description
|
|---|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Data
|
Returned when the method is successful. Data object containing the specified records.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code example shows how to call this method.
```
func fetchTableRecords( tableName: String, filterQuery: String,
includeFields: [FieldName] = [FieldName](), readOptions:
FieldReadConfiguration.Options = [], limit: Int?) {
let readConfig = FieldReadConfiguration(includeFields: includeFields, options: readOptions)
let config = FetchConfiguration(Filter(query: filterQuery), limit, readConfig)
do {
let dataResult: Data = try await tableService.records(from: tableName, configuration: config)
let recordResult: [NowRecord] = dataResult.convertToRecords()
// return recordResult
} catch {
print("Fetch failed with NowDataError: \(error)")
throw error
}
}
```
## NowTableService - records\(from tableName: String, configuration: FetchConfiguration? = nil, completion: @escaping \(Result<Data, NowDataError>\)\)
Retrieves records from a specified table and then executes the **completion** handler after the records are retrieved.
If needed, you can decode the return results into a custom Codable model or you can use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function instead. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myResult.convertToRecords()
```
For large result sets, use the [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function to fetch paginated results.
|
Name
|
Type
|
Description
|
|---|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Data, NowDataError>\)
|
Completion handler to execute after the records are retrieved. Return values:
- Success: Data - Requested records
- Error: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this method.
```
func fetchTableRecords( tableName: String, filterQuery: String, includeFields: [FieldName] = [FieldName](), readOptions: FieldReadConfiguration.Options = [], limit: Int?) {
let readConfig = FieldReadConfiguration(includeFields: includeFields, options: readOptions)
let config = FetchConfiguration(Filter(query: filterQuery), limit, readConfig)
tableService.records (from: tableName, configuration: fetchConfiguration) { [weak self] result in
switch result {
case .success(let dataResult):
let recordResult: [NowRecord] = dataResult.convertToRecords()
// return recordResult
case .failure(let error):
// Failed to fetch record with NowDataError
}
}
}
```
## NowTableService - records\(from tableName: String, configuration: FetchConfiguration? = nil\)
Creates a publisher that enable you to retrieve records from the specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
For large result sets, use the [NowTableService - paginator\(from tableName: String, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function to fetch paginated results.
|
Name
|
Type
|
Description
|
|---|
|
from tableName
|
String
|
Name of the table from which to retrieve the records, such as incident.
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Data, NowDataError>
|
Success: Data object containing the specified records.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to create a function that fetches multiple records from a specified table. It creates an object which will schedule the request to be executed at some point in the future and return a ByteArray response.
```
tableService.records(from: tableName, configuration: fetchConfiguration)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.convertToRecords()
.sink { completion in
if case let .failure(error) = completion {
print("Record retrieval failed with NowDataError: \(error)")
}
} receiveValue: { records in
print("Successfully retrieved records: \(records)")
}
.store(in: &subscriptions)
```
## NowTableService - update<Model: SysIdentifiableModel>\(\_ model: Model, in tableName: String, coder: Coder = .default, writeOptions: FieldWriteOptions? = nil, configuration: FetchConfiguration? = nil\) async throws
Updates the specified Codable model in the specified table.
|
Name
|
Type
|
Description
|
|---|
|
model
|
Model
|
`SysIdentifiableModel` model to update in the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Model
|
Returned when the method is successful. Decodable model that was updated in the specified table.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String}
func updateUser(user: User) async throws -> User {
do {
let result = try await tableService.update(user, in: “sys_user”)
return result
} catch {
print("Update failed with NowDataError: \(error)")
throw error
}
}
```
## NowTableService - update<Model: SysIdentifiableModel>\(\_ model: Model, in tableName: String, coder: Coder = .default, writeOptions: FieldWriteOptions? = nil, configuration: FetchConfiguration? = nil, completion: @escaping \(Result<Model, NowDataError>\)\)
Updates the specified Codable model in the specified table and then executes the **completion** handler.
|
Name
|
Type
|
Description
|
|---|
|
model
|
Model
|
`SysIdentifiableModel` model to update in the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Model, NowDataError>\)
|
Completion handler to execute after updating the specified Codable model\(s\).Return values:
- Success: Model
- Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this method.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let user = User(sysId: "12345", name: "abel")
let coder: Coder = .default
tableService.update(user, in: "sys_user") { [weak self] result in
switch result {
case .success(let model):
do {
let data = try coder.jsonEncoder.encode(model)
self?.publish(data: data)
} catch {
self?.publish(result: .failure(error))
}
case .failure(let error):
// Failed to update with NowDataError
self?.publish(result: .failure(error))
}
}
```
## NowTableService - update<Model: SysIdentifiableModel>\(\_ model: Model, in tableName: String, coder: Coder = .default, writeOptions: FieldWriteOptions? = nil, configuration: FetchConfiguration? = nil\)
Updates the specified codable model in the specified table.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
|
Name
|
Type
|
Description
|
|---|
|
model
|
Model
|
`SysIdentifiableModel` model to update in the table.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
coder
|
Coder
|
Optional. `Coder` to use to encode or decode data sent to and received from the ServiceNow instance.Possible values:
- default: The default encoders format dates using the `yyy-MM-dd HH:mm:ss` format by using the device `Locale` and `TimeZone`.
- custom\(JSONEncoder, JSONDecoder\):
Use `custom` coders to have more fine-grained control on JSON decoding/encoding.
Only use this enumeration to supply your own `JSONEncoder` and `JSONDecoder`, for example when using special date formats, time zones, or locales.
```
let myEncoder = JSONEncoder()
myEncoder.dateFormat = …
let myDecoder = JSONDecoder()
myDecoder.dateFormat = …
let coder: Coder = .custom(myEncoder, myDecoder)
```
Default: .default
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Model, NowDataError>
|
Success: Decodable models that were updated in the specified table.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code example shows how to call this method.
```
struct User: SysIdentifiableModel {
var sysId: String = ""
var name: String
}
let user = User(sysId: "12345", name: "abel")
let coder: Coder = .default
tableService.update(user, in: "sys_user")
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
if case let .failure(error) = completion {
// Failed to update with NowDataError
self?.publish(result: .failure(error))
}
} receiveValue: { [weak self] updatedModel in
do {
let data = try coder.jsonEncoder.encode(updatedModel)
self?.publish(data: data)
} catch {
// Failed to update with NowDataError
self?.publish(result: .failure(error))
}
}
.store(in: &subscriptions)
```
## NowTableService - updateRecord\(sysId: SysID, in tableName: String, withfields: \[FieldName: FieldValue\], writeOptions: FieldWriteOptions? = nil, configuration: FieldReadConfiguration? = nil\) async throws
Updates the specified record with the specified fields.
You can decode the data into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
Data
|
Returned when the method is successful. Data object containing the updated record.
|
|
NowDataError
|
Thrown when the method fails. - `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
The following code examples shows how to call this method.
```
do {
let dataResult: Data = try await tableService.updateRecord(with: fields, in: tableName, writeOptions: writeOptions, configuration: configuration)
let recordResult: NowRecord = dataResult.convertToRecord()
} catch {
print("Record update failed with NowDataError: \(error)")
}
```
## NowTableService - updateRecord\(sysId: SysID, in tableName: String, with fields: \[FieldName: FieldValue\], writeOptions: FieldWriteOptions? = nil, configuration: FieldReadConfiguration? = nil, completion: @escaping \(Result<Data, NowDataError>\)
Updates the specified record with the specified fields then executes the **completion** handler once the record is saved.
If needed, you can decode the return results into a custom Codable model or you can use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function instead. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myResult.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
completion
|
@escaping \(Result<Data, NowDataError>\)
|
Completion handler to execute after the records are retrieved. Return values:
- Success: Data - Requested records
- Error: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
|Type|Description|
|----|-----------|
|None| |
The following code example shows how to call this method.
```
tableService.updateRecord(sysId: sysId, in: tableName, with: fields, writeOptions: writeOptions, configuration: readConfiguration) { [weak self] result in
switch result {
case .success(let data):
self?.publish(data: data)
case .failure(let error):
// Failed to update with NowDataError
}
}
```
## NowTableService - updateRecord\(sysId: SysID, in tableName: String, withfields: \[FieldName: FieldValue\], writeOptions: FieldWriteOptions? = nil, configuration: FieldReadConfiguration? = nil\)
Updates the specified record with the specified fields.
**Note:** This method has been deprecated. You should use the async/await implementation of the method instead.
The publisher emits data that you can decode into a custom [Codable model](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types), or you can also use the [NowTableService - paginator<Model: Decodable>\(from tableName: String, path: String = Constants.resultPath, coder: Coder = .default, configuration: FetchConfiguration? = nil\)](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/NowTableServiceiOSAPI.md) function. Alternatively, you can use the convenience function convertToRecords\(\) to transform data into a NowRecord object. The following shows how to convert a publisher to emit NowRecords:
```
let dataPublisher: AnyPublisher = ...
let recordsPublisher: AnyPublisher<[NowRecord], NowDataError> = myPublisher.convertToRecords()
```
**Note:** All fields within a record may not be available for update. For example, fields that have a prefix of `sys_` are typically system parameters that are automatically generated and cannot be updated. Fields that are not specified and not auto-generated by the system are set to the associated data type's null value.
|
Name
|
Type
|
Description
|
|---|
|
sysId
|
String
|
Sys\_id of the record to return from the ServiceNow instance.
|
|
with fields
|
\[FieldName: FieldValue\]
|
Name-value pairs of the fields to include in the record.
|
|
in tableName
|
String
|
Name of the table in which to write the records, such as incident.
|
|
writeOptions
|
[FieldWriteOptions](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FieldWriteOptionsiOSStruct.md)
|
Optional. Configuration options to apply to the data being written to the record.Default: nil
|
|
configuration
|
[FetchConfiguration](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/cllent-mobile-api-reference/FetchConfigiOSStructure.md)
|
Optional. Configuration to apply to the retrieved records, including filters that define the records to return, pagination page size limit, which fields to retrieve, and what to include in the fields.Default: nil - All records returned.
|
|
Type
|
Description
|
|---|
|
AnyPublisher<Data, NowDataError>
|
Success: Data object containing the updated record.Failure: NowDataError
- `accessToken(AccessTokenProviderError)`
- **AccessTokenProviderError**: The access token provider's error code or message.
- accessTokenRetrievalFailed
- userSessionError\(\_ error: Error\)
Thrown when there is an error in the access token.
- `attachmentValidation`
Thrown when an attachment fails validation.
- `badResponse(statusCode: HTTPStatusCode)`
- **HTTPStatusCode**: Status code received from the instance.
Thrown when a request returns an unexpected response
- `cannotDecodeModel(DecodingError)`
- **DecodingError**: Decoding error detected.
Thrown when a Codable model cannot be decoded from JSON.
- `cannotDecodeProperty(type: Any, from: String)`
- **type**: Wrapped type to decode from a string.
- **from**: String to decode to the specified type.
Thrown when a string-wrapped value cannot be decoded from JSON.
- `cannotEncodeModel(EncodingError)`
- **EncodingError**: Encoding error detected.
Thrown when a Codable model cannot be encoded to JSON.
- `cannotParseResponse`
Thrown when a response from the instance cannot be parsed into its expected format.
- `invalidURL`
Thrown when a URL cannot be formed. For example, if the string contains characters that are illegal in a URL or is an empty string.
- `missingAttachmentMetadata`
Thrown when the attachment metadata header is missing.
- `missingServiceConfiguration`
Thrown when an expected service configuration is missing.
- `missingSysID`
Thrown when an expected sys\_id parameter is missing.
- `network(NetworkServiceError)`
- genericError\(String\)
- operationCanceled
- serviceDisabled
- serverError\(Error\)
- systemError\(Error\)
Thrown when a network service encountered an error.
|
This example shows how to create a function that updates a record in the specified table, with the specified fields. The output of the call is a ByteArray which allows you to convert the data into any model that you want.
```
tableService.updateRecord(sysId: sysId, in: tableName, with: fields, writeOptions: writeOptions, configuration: readConfiguration)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.main)
.convertToRecord()
.sink { completion in
if case let .failure(error) = completion {
print("Update failed with NowDataError: \(error)")
}
} receiveValue: { record in
print("Record updated: \(record)")
}
.store(in: &subscriptions)
```