---
sourceDocument: Xanadu API Reference
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/xanadu/api-reference

 Release :

    - xanadu

ft:locale :

    - en-US

ft:publication_title :

    - Xanadu API Reference

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# NowAttachmentService class - iOS

# NowAttachmentService class - iOS {#ariaid-title1}

* Release version: Xanadu
* 
* Updated August 1, 2024
* 
* ![](https://www.servicenow.com/docs/portal-asset/ico-clock) 29 minutes to read

The NowAttachmentService class provides functions that enable you to
upload and query attachments that are associated with records within a table on a ServiceNow instance.
You can upload or retrieve a single file with each request.
NowAttachmentService respects any system limitations on uploaded files,
such as maximum file size and allowed attachment types. You can control these settings using
the instance properties com.glide.attachment.max_size, 1024MB by default, and
glide.attachment.extensions.  
Note:  
NowAttachmentService accepts all Content-Type values (/). Specify the file content type when uploading an attachment. The content type is stored with the file metadata, enabling other tools to correctly identify and parse the file.
{#NowAttachmentServiceiOSAPI__table_vx2_klw_5pb__entry__3}

| Name | Type | Description |
|-|-|-|
| configuration | [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/A6W2zQ0fOO_VQ9lbo3VKwQ#NowServiceConfigurationiOSStruct "The NowServiceConfiguration structure defines configuration information for a feature service.") | Configuration settings provided when the service was initialized. |
[Table 1. Properties]

{#NowAttachmentServiceiOSAPI__table_vx2_klw_5pb}

## NowAttachmentService - attachment(for sysId: String, validateAttachment: Boolean) async throws {#ariaid-title2}

Retrieves the attachment with the specified sys_id and validates the attachment by comparing the computed hash of the attachment to the expected SHA256 checksum.
Note:  
Validation of an attachment can cause a performance impact. You can skip the validation step by setting the validateAttachment parameter to `false`. You can validate the attachment at a later stage if needed by calling the Attachment.validate() function.
{#NAttServiOS-attachment-async_S_B_O__table_dqr_hmx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment to retrieve. |
| validateAttachment | Boolean | Flag that indicates whether to validate the attachment. Valid values: * true: Validate the attachment. * false: Do not validate the attachment. Default: true |
[Table 2. Parameters]

{#NAttServiOS-attachment-async_S_B_O__table_dqr_hmx_spb} {#NAttServiOS-attachment-async_S_B_O__table_eqr_hmx_spb__entry__2}

| Type | Description |
|-|-|
| NowAttachment | Returned when the method is successful. Specified attachment. |
| 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. {#NAttServiOS-attachment-async_S_B_O__NowDataErroriOS-ul-enum} |
[Table 3. Returns]

{#NAttServiOS-attachment-async_S_B_O__table_eqr_hmx_spb}  
The following code examples shows how to call this method.

    func downloadAttachment(sysId: String) async throws -> NowAttachment {
        do {
            let nowAttachment = try await attachmentService.attachment(for: sysId, validateAttachment: false)
            return nowAttachment
        } catch {
            // Handle NowDataError
            throw error
        }
    }

## NowAttachmentService - attachment(for sysId: String, validateAttachment: Boolean, completion: @escaping (Result\<NowAttachment, NowDataError\>)) {#ariaid-title3}

Retrieves the attachment with the specified sys_id and validates the attachment by
comparing the computed hash of the attachment to the expected SHA256 checksum. Once finished, it
executes the passed completion handler.
Note:  
Validation of an attachment can cause a performance impact. You can skip the validation step by setting the validateAttachment parameter to `false`. You can validate the attachment at a later stage if needed by calling the Attachment.validate() function.
{#NAttServiOS-attachment_S_B_O__table_dqr_hmx_spb__entry__3}{#NAttServiOS-attachment_S_B_O__mobilesdkiOS-completion_data_dataerror-row}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment to retrieve. |
| validateAttachment | Boolean | Flag that indicates whether to validate the attachment. Valid values: * true: Validate the attachment. * false: Do not validate the attachment. {#NAttServiOS-attachment_S_B_O__ul_ftq_1q5_4pb} Default: true |
| completion | @escaping (Result​\<[NowAttachment](https://servicenow-prod.fluidtopics.net/g7KJD1~RU_nHzDzc18~DNg#NowAttachmentiOSStructure "The NowAttachment structure provides functions that enable you to validate attachments by comparing their computed hash."), NowDataError\>) | Completion handler to execute after the attachment is retrieved. Return values for the completion handler: * Success: [NowAttachment](https://servicenow-prod.fluidtopics.net/g7KJD1~RU_nHzDzc18~DNg#NowAttachmentiOSStructure "The NowAttachment structure provides functions that enable you to validate attachments by comparing their computed hash.") - Requested attachment * 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. {#NAttServiOS-attachment_S_B_O__NowDataErroriOS-ul-enum} {#NAttServiOS-attachment_S_B_O__ul_uzx_thj_ppb} |
[Table 4. Parameters]

{#NAttServiOS-attachment_S_B_O__table_dqr_hmx_spb} {#NAttServiOS-attachment_S_B_O__table_eqr_hmx_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 5. Returns]

{#NAttServiOS-attachment_S_B_O__table_eqr_hmx_spb}  
The following code example shows how to call this function.

    let sysId = UUID().uuidString  // UUID for the attachment
    private func downloadAttachment(sysId: String) {
      attachmentService.attachment(for: sysId, validateAttachment: false) { (result) in
        switch result {
          case .success(let attachment):
            // Attachment retrieved successful, return attachment
          case .failure(let error):
            // Attachment retrieved failed, return NowDataError
        }
      }
    }

## NowAttachmentService - attachment(for sysId: String, validateAttachment: Boolean) {#ariaid-title4}

Retrieves the attachment with the specified sys_id and validates the attachment by
comparing the computed hash of the attachment to the expected hash.
Note:  
Validation of an attachment can cause a performance impact. You can skip the validation step by setting the validateAttachment parameter to `false`. If needed, you can validate the attachment at a later stage by calling the Attachment.validate() function.  
Note:  
This method has been deprecated. You should use the async/await implementation of the method instead.
{#NAttServiOS-attachment_S_B__table_w4s_d3s_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment to retrieve. |
| validateAttachment | Boolean | Flag that indicates whether to validate the attachment. Valid values: * true: Validate the attachment. * false: Don't validate the attachment. {#NAttServiOS-attachment_S_B__ul_ftq_1q5_4pb} Default: true |
[Table 6. Parameters]

{#NAttServiOS-attachment_S_B__table_w4s_d3s_spb} {#NAttServiOS-attachment_S_B__table_x4s_d3s_spb__entry__2}

| Type | Description |
|-|-|
| AnyPublisher​\<[NowAttachment](https://servicenow-prod.fluidtopics.net/g7KJD1~RU_nHzDzc18~DNg#NowAttachmentiOSStructure "The NowAttachment structure provides functions that enable you to validate attachments by comparing their computed hash."), NowDataError\> | Success: [NowAttachment](https://servicenow-prod.fluidtopics.net/g7KJD1~RU_nHzDzc18~DNg#NowAttachmentiOSStructure "The NowAttachment structure provides functions that enable you to validate attachments by comparing their computed hash.") - Contains the specified attachment. 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. {#NAttServiOS-attachment_S_B__NowDataErroriOS-ul-enum} |
[Table 7. Returns]

{#NAttServiOS-attachment_S_B__table_x4s_d3s_spb}  
The following code example shows how to call this function.

    let sysId = UUID().uuidString  // UUID for the attachment
    private func downloadAttachment(sysId: String) {
      let publisher = self.attachmentService.attachment(for: sysId, validateAttachment: false)
      publisher
        .receive(on: DispatchQueue.main)
        .sink { [weak self] completion in
          if case let .failure(error) = completion {
            // Attachment retrieved failed, return NowDataError
          }
        } receiveValue: { [weak self] (attachment) in
          // Attachment retrieved successful, return attachment
        }
        .store(in: &subscriptions)
    }

## NowAttachmentService - attachmentMetadata(filter: Filter, limit: Int) async throws {#ariaid-title5}

Retrieves the metadata for all the attachments that meet the specified criteria.
{#NAttServiOS-attachMeta-async_S_I_O__table_tcn_cfs_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| filter | [Filter](https://servicenow-prod.fluidtopics.net/RU8GNeHrwTSXZYsrdNWpMQ#FilteriOSStructure "The Filter structure provides the ability to configure filters that define the data to return in the return results of a REST endpoint query.") | Optional. Query string to use to filter the attachments whose metadata to return. Default: nil - Returns metadata for all available attachments. Takes into consideration the limit parameter. |
| limit | Integer | Optional. Maximum number of attachment file's metadata to return. Default: nil - Returns all metadata that meets the filter parameter specifications. |
[Table 8. Parameters]

{#NAttServiOS-attachMeta-async_S_I_O__table_tcn_cfs_spb} {#NAttServiOS-attachMeta-async_S_I_O__table_ucn_cfs_spb__entry__2}

| Type | Description |
|-|-|
| \[NowAttachmentMetadata\] | Returned when the method is successful. Array that contains the metadata for the matching attachments. |
| 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. {#NAttServiOS-attachMeta-async_S_I_O__NowDataErroriOS-ul-enum} |
[Table 9. Returns]

{#NAttServiOS-attachMeta-async_S_I_O__table_ucn_cfs_spb}  
The following code examples shows how to call this method.

    let filter = Filter(criteria: [], sortBy: [.desc("created")],
                 queryCategory: nil)
    do {
        let metadata = try await attachmentService.attachmentMetadata(filter: filter, limit: 10)
        // Metadata retrieval successful
    } catch {
        // Metadata retrieval failed, NowDataError thrown
    }

## NowAttachmentService - attachmentMetadata(filter: Filter, limit: Int, completion: @escaping
(Result\<\[NowAttachmentMetadata\], NowDataError\>)) {#ariaid-title6}

Retrieves the metadata for all the attachments that meet the specified
criteria.
{#NAttServiOS-attachMetadata_S_I_O__table_tcn_cfs_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| filter | [Filter](https://servicenow-prod.fluidtopics.net/RU8GNeHrwTSXZYsrdNWpMQ#FilteriOSStructure "The Filter structure provides the ability to configure filters that define the data to return in the return results of a REST endpoint query.") | Optional. Query string to use to filter the attachments whose metadata to return. Default: nil - Returns metadata for all available attachments. Takes into consideration the limit parameter. |
| limit | Integer | Optional. Maximum number of attachment file's metadata to return. Default: nil - Returns all metadata that meets the filter parameter specifications. |
| completion | @escaping (Result​\<\[[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.")\], NowDataError\>) | Completion handler to execute after the metadata is retrieved. Return values for the completion handler: * Success: NowAttachmentMetadata - Objects containing the requested metadata. * 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. {#NAttServiOS-attachMetadata_S_I_O__NowDataErroriOS-ul-enum} {#NAttServiOS-attachMetadata_S_I_O__ul_uzx_thj_ppb} |
[Table 10. Parameters]

{#NAttServiOS-attachMetadata_S_I_O__table_tcn_cfs_spb} {#NAttServiOS-attachMetadata_S_I_O__table_ucn_cfs_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 11. Returns]

{#NAttServiOS-attachMetadata_S_I_O__table_ucn_cfs_spb}  
The following code example shows how to call this function.

    let query = "active=true^short_descriptionLIKEbroken"
    let filter = Filter(query: query)
    attachmentService.attachmentMetadata(filter: filter, limit: limit) { (result) in
      DispatchQueue.main.async { [weak self] in
        switch result {
        case .success(let response):
          do {
            let data = try JSONEncoder().encode(response)
            // Retrieve metadata successfully, return data
          } catch {
            // Retrieve metadata failed, return error 
          }
        case .failure(let error):
          // Retrieve metadata failed, return NowDataError
        }	
      }
    }

## NowAttachmentService - attachmentMetadata(filter: Filter, limit: Int) {#ariaid-title7}

Retrieves the metadata for all the attachments that meet the specified
criteria.
Note:  
This method has been deprecated. You should use the async/await implementation of the method instead.
{#NAttServiOS-attachMetadata_S_I__table_ahv_32s_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| filter | [Filter](https://servicenow-prod.fluidtopics.net/RU8GNeHrwTSXZYsrdNWpMQ#FilteriOSStructure "The Filter structure provides the ability to configure filters that define the data to return in the return results of a REST endpoint query.") | Optional. Query string to use to filter the attachments whose metadata to return. Default: nil - Returns metadata for all available attachments. Takes into consideration the limit parameter. |
| limit | Integer | Optional. Maximum number of attachment file's metadata to return. Default: nil - Returns all metadata that meets the filter parameter specifications. |
[Table 12. Parameters]

{#NAttServiOS-attachMetadata_S_I__table_ahv_32s_spb} {#NAttServiOS-attachMetadata_S_I__table_bhv_32s_spb__entry__2}

| Type | Description |
|-|-|
| AnyPublisher​\<\[[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.")\], NowDataError\> | Success: NowAttachmentMetadata - Objects that contain the metadata for the matching attachments. 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. {#NAttServiOS-attachMetadata_S_I__NowDataErroriOS-ul-enum} |
[Table 13. Returns]

{#NAttServiOS-attachMetadata_S_I__table_bhv_32s_spb}  
The following code example shows how to call this function.

    let query = "active=true^short_descriptionLIKEbroken"
    let filter = Filter(query: query)
    let publisher = self.attachmentService.attachmentMetadata(filter: filter)
    publisher
      .receive(on: DispatchQueue.main)
      .encode(encoder: JSONEncoder())
      .sink { [weak self] completion in
        if case let .failure(error) = completion {
          // Retrieve metadata failed, return NowDataError
      } receiveValue: { [weak self] (data) in
         // Retrieve metadata successfully, return data
      }
    .store(in: &subscriptions

## NowAttachmentService - attachmentMetadata(for sysId: String) async throws {#ariaid-title8}

Retrieves the metadata for the attachment associated with the specified sys_id.
{#NAttServiOS-attachMeta-async_S_O__table_ldt_3hs_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment whose metadata to retrieve. |
[Table 14. Parameters]

{#NAttServiOS-attachMeta-async_S_O__table_ldt_3hs_spb} {#NAttServiOS-attachMeta-async_S_O__table_mdt_3hs_spb__entry__2}

| Type | Description |
|-|-|
| NowAttachmentMetadata | Returned when the method is successful. Metadata for the requested attachment. |
| 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. {#NAttServiOS-attachMeta-async_S_O__NowDataErroriOS-ul-enum} |
[Table 15. Returns]

{#NAttServiOS-attachMeta-async_S_O__table_mdt_3hs_spb}  
The following code examples shows how to call this method.

    do {
        let metadata = try await attachmentService.attachmentMetadata(for: sysId)
        // Metadata retrieval successful
    } catch {
        // Metadata retrieval failed, NowDataError thrown
    }

## NowAttachmentService - attachmentMetadata(for sysId: String, completion: @escaping
(Result\<NowAttachmentMetadata, NowDataError\>)) {#ariaid-title9}

Retrieves the metadata for the attachment associated with the specified sys_id and then executes the completion handler after the metadata is retrieved.
{#NAttServiOS-attachMetadata_S_O__table_ldt_3hs_spb__entry__3}{#NAttServiOS-attachMetadata_S_O__mobilesdkiOS-completion_data_dataerror-row}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment whose metadata to retrieve. |
| completion | @escaping (Result​\<[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata."), NowDataError\>) | Completion handler to execute after the metadata is retrieved. Return values for the completion handler: * Success: [NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.") - Requested metadata * 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. {#NAttServiOS-attachMetadata_S_O__NowDataErroriOS-ul-enum} {#NAttServiOS-attachMetadata_S_O__ul_uzx_thj_ppb} |
[Table 16. Parameters]

{#NAttServiOS-attachMetadata_S_O__table_ldt_3hs_spb} {#NAttServiOS-attachMetadata_S_O__table_mdt_3hs_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 17. Returns]

{#NAttServiOS-attachMetadata_S_O__table_mdt_3hs_spb}  
The following code example shows how to call this function.

    let sysId = UUID().uuidString  // UUID for the attachment
    attachmentService.attachmentMetadata(for: sysId) { (result) in
      DispatchQueue.main.async { [weak self] in
        switch result {
          case .success(let response):
            do {
              let data = try JSONEncoder().encode(response)
              // Retrieve metadata successfully, return data
            } catch {
              // Retrieve metadata failed, return error      
            }
          case .failure(let error):
            // Retrieve metadata failed, return NowDataError
        }	
      }
    }

## NowAttachmentService - attachmentMetadata(for sysId: String) {#ariaid-title10}

Retrieves the metadata for the attachment associated with the specified
sys_id.
Note:  
This method has been deprecated. You should use the async/await implementation of the method instead.
{#NAttServiOS-attachMetadata_S__table_shc_ngs_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| for sysId | String | Sys_id of the attachment whose metadata to retrieve. |
[Table 18. Parameters]

{#NAttServiOS-attachMetadata_S__table_shc_ngs_spb} {#NAttServiOS-attachMetadata_S__table_thc_ngs_spb__entry__2}

| Type | Description |
|-|-|
| AnyPublisher​\<\[[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.")\], NowDataError\> | Success: NowAttachmentMetadata - Object that contains the metadata for the requested attachment. 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. {#NAttServiOS-attachMetadata_S__NowDataErroriOS-ul-enum} |
[Table 19. Returns]

{#NAttServiOS-attachMetadata_S__table_thc_ngs_spb}  
The following code example shows how to call this function.

    let sysId = UUID().uuidString  // UUID for the attachment
    let publisher = self.attachmentService.attachmentMetadata(for: sysId)
    publisher
      .receive(on: DispatchQueue.main)
      .encode(encoder: JSONEncoder())
      .sink { [weak self] completion in
        if case let .failure(error) = completion {
          // Retrieve metadata failed, return NowDataError
        }
      } receiveValue: { [weak self] (data) in
         // Retrieve metadata successfully, return data
      }
    .store(in: &subscriptions)

## NowAttachmentService - attachmentMetadataPaginator(filter: Filter, limit: Int) {#ariaid-title11}

Retrieves the metadata for all the attachments that meet the specified criteria and
returns a Paginator object for iterating through the pages of the returned metadata.
{#NAttServiOS-attachMetadataPag_S_I__table_tqh_dcs_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| filter | [Filter](https://servicenow-prod.fluidtopics.net/RU8GNeHrwTSXZYsrdNWpMQ#FilteriOSStructure "The Filter structure provides the ability to configure filters that define the data to return in the return results of a REST endpoint query.") | Optional. Query string to use to filter the attachments whose metadata to return. Default: nil - Returns metadata for all available attachments. Takes into consideration the limit parameter. |
| limit | Integer | Optional. Maximum number of attachment file's metadata to return. Default: nil - Returns all metadata that meets the filter parameter specifications. |
[Table 20. Parameters]

{#NAttServiOS-attachMetadataPag_S_I__table_tqh_dcs_spb} {#NAttServiOS-attachMetadataPag_S_I__table_uqh_dcs_spb__entry__2}

| Type | Description |
|-|-|
| [Paginator](https://servicenow-prod.fluidtopics.net/2PI_SgczzCsJPmA6W~Hulw#PaginatorIOSAPI "The Paginator class provides methods for iterating through a record set returned by a call to the ServiceNow Table API through the NowTableService. It is the object that is returned by the NowTableService paginator() methods. Do not call this method outside of that environment.")​\<\[[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.")\]\> | Success: Array of NowAttachmentMetadata objects. Failure: NowDataError object. * `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. {#NAttServiOS-attachMetadataPag_S_I__NowDataErroriOS-ul-enum} |
[Table 21. Returns]

{#NAttServiOS-attachMetadataPag_S_I__table_uqh_dcs_spb}  
The following code example shows how to call this function.

    let paginator: Paginator<T> = makePaginator(query: query, fetchLimit: 1)

    func makePaginator(query: String, fetchLimit: Int?) -> Paginator<[NowAttachmentMetadata]> {
      attachmentsService.attachmentMetadataPaginator(filter: Filter(query: query), limit: fetchLimit)
    }

## NowAttachmentService - delete(sysId: String) async throws {#ariaid-title12}

Deletes the attachment with the specified sys_id.
{#NAttServiOS-delete-async_S_O__table_e5b_zqx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| sysId | String | Sys_id of the attachment to delete. |
[Table 22. Parameters]

{#NAttServiOS-delete-async_S_O__table_e5b_zqx_spb} {#NAttServiOS-delete-async_S_O__table_f5b_zqx_spb__entry__2}

| Type | Description |
|-|-|
| None | Nothing is returned if the method was 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. {#NAttServiOS-delete-async_S_O__NowDataErroriOS-ul-enum} |
[Table 23. Returns]

{#NAttServiOS-delete-async_S_O__table_f5b_zqx_spb}  
The following code examples shows how to call this method.

    do {
        try await attachmentService.delete(sysId: sysId)
        // Deletion successful
    } catch {
        // Deletion failed, NowDataError thrown
    }

## NowAttachmentService - delete(sysId: String, completion: @escaping (Result\<Void,
NowDataError\>)) {#ariaid-title13}

Deletes the attachment with the specified sys_id and then executes the passed
completion handler after the attachment is deleted.
{#NAttServiOS-delete_S_O__table_e5b_zqx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| sysId | String | Sys_id of the attachment to delete. |
| completion | @escaping (Result\<Void, NowDataError\>) | Completion handler to execute after the attachment is deleted. Return values for the completion handler: * Success: Void * 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. {#NAttServiOS-delete_S_O__NowDataErroriOS-ul-enum} |
[Table 24. Parameters]

{#NAttServiOS-delete_S_O__table_e5b_zqx_spb} {#NAttServiOS-delete_S_O__table_f5b_zqx_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 25. Returns]

{#NAttServiOS-delete_S_O__table_f5b_zqx_spb}  
The following code example shows how to call this function.

    let sysId = UUID().uuidString  // UUID for the attachment
    attachmentService.delete(sysId: sysId) { (result) in
      DispatchQueue.main.async { [weak self] in
        switch result {
          case .success:
            // Attachment with sysId is deleted
          case .failure(let error):
            // Failed to delete, with NowDataError
        }
      }
    }

## NowAttachmentService - delete(sysId: String) {#ariaid-title14}

Deletes the attachment with the specified sys_id.
Note:  
This method has been deprecated. You should use the async/await implementation of the method instead.
{#NAttServiOS-delete_S__table_svp_2qx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| sysId | String | Sys_id of the attachment to delete. |
[Table 26. Parameters]

{#NAttServiOS-delete_S__table_svp_2qx_spb} {#NAttServiOS-delete_S__table_tvp_2qx_spb__entry__2}

| Type | Description |
|-|-|
| AnyPublisher\<Void, NowDataError\> | 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. {#NAttServiOS-delete_S__NowDataErroriOS-ul-enum} |
[Table 27. Returns]

{#NAttServiOS-delete_S__table_tvp_2qx_spb}  
The following code example shows how to call this function.

    let publisher = attachmentService.delete(sysId: sysId)
    publisher
      .receive(on: DispatchQueue.main)
      .sink { [weak self] completion in
        switch completion {
          case .finished:
            // Attachment with sysId is deleted
          case .failure(let error):
           // Failed to delete, with NowDataError
       }
     } receiveValue: {
     }
     .store(in: &subscriptions)

## NowAttachmentService - init(configuration: NowServiceConfiguration, coreServiceProvider:
NowCoreServiceProviding) {#ariaid-title15}

Initializes a new NowAttachmentService instance.
{#NAttServiOS-init_O_O__table_hfm_ry2_tpb__entry__3}

| Name | Type | Description |
|-|-|-|
| configuration | [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/A6W2zQ0fOO_VQ9lbo3VKwQ#NowServiceConfigurationiOSStruct "The NowServiceConfiguration structure defines configuration information for a feature service.") | Configuration information needed to properly initialize the service. |
| coreServiceProvider | NowCoreServiceProviding | Optional. Object implementing the NowCoreServiceProviding protocol. Default: nil |
[Table 28. Parameters]

{#NAttServiOS-init_O_O__table_hfm_ry2_tpb}  
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 attachmentService = NowAttachmentService(configuration: serviceConfig, coreServiceProvider: coreService)

## NowAttachmentService - upload(data: Data, configuration: NowAttachmentUploadConfiguration, progressUpdate: @escaping ProgressUpdate) async throws {#ariaid-title16}

Uploads the attachment data and attaches it to a record in a table as specified in the upload configuration.
The ProgressUpdate callback provides upload progress information that you can then use to provide UI feedback.
{#NAttServiOS-upload-async_O_O_O_O__table_n5z_mpx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| data | Data | Attachment to upload. |
| configuration | [NowAttachmentUpload Configuration](https://servicenow-prod.fluidtopics.net/KPcSTDQScxtEAhSD~AI6Qg#NowAttachUploadConfigiOSStruct "The NowAttachmentUploadConfiguration structure enables you to define the configuration information for an attachment that you are uploading to your ServiceNow instance.") | Configuration information that defines the upload parameters for the attachment, such as: * Table and record to attach the file to * Attachment file name * Type of attachment * Whether the file is encrypted |
| progressUpdate | @escaping ProgressUpdate | Completion handler to execute after the attachment is retrieved. This is called multiple times until the upload process is complete. Return values for the completion handler: ProgressUpdate - Returns the current progress of the upload. `ProgressUpdate = (_bytesWritten: Int64, _totalBytesWritten: Int64, _totalBytesExpectedToWrite: Int64) -> Void` |
[Table 29. Parameters]

{#NAttServiOS-upload-async_O_O_O_O__table_n5z_mpx_spb} {#NAttServiOS-upload-async_O_O_O_O__table_o5z_mpx_spb__entry__2}

| Type | Description |
|-|-|
| NowAttachmentMetadata | Returned when the method is successful. Object that contains the uploaded metadata. |
| 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. {#NAttServiOS-upload-async_O_O_O_O__NowDataErroriOS-ul-enum} |
[Table 30. Returns]

{#NAttServiOS-upload-async_O_O_O_O__table_o5z_mpx_spb}  
The following code examples shows how to call this method.

    func uploadFile(for tableName: String, sysId: String, mimeType: String, encryptionContext: String?, data: Data, filename: String) async throws -> NowAttachmentMetadata { 

        let mimeType = MediaUtilities.mimeType(forFileName: filename)
        let uploadConfig = NowAttachmentUploadConfiguration(tableName: tableName, 
                                                            recordSysId: sysId,
                                                            fileName: filename,
                                                            contentType: mimeType,
                                                            encryptionContext: encryptionContext) 

        do {
            let attachmentMetadata = try await attachmentService.upload(data: data, configuration: uploadConfig) { (_, _, _) in }
            return attachmentMetadata
        } catch {
            // Handle NowDataError
            throw error
        }
    }

## NowAttachmentService - upload(data: Data, configuration: NowAttachmentUploadConfiguration,
progressUpdate: @escaping ProgressUpdate, completion: @escaping
(Result\<NowAttachmentMetadata, NowDataError\>)) {#ariaid-title17}

Uploads the attachment data and attaches it to a record in a table as specified in the upload configuration.
The ProgressUpdate callback provides upload progress information that
you can then use to provide UI feedback.
{#NAttServiOS-upload_O_O_O_O__table_n5z_mpx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| data | Data | Attachment to upload. |
| configuration | [NowAttachmentUpload Configuration](https://servicenow-prod.fluidtopics.net/KPcSTDQScxtEAhSD~AI6Qg#NowAttachUploadConfigiOSStruct "The NowAttachmentUploadConfiguration structure enables you to define the configuration information for an attachment that you are uploading to your ServiceNow instance.") | Configuration information that defines the upload parameters for the attachment, such as: * Table and record to attach the file to * Attachment file name * Type of attachment * Whether the file is encrypted |
| progressUpdate | @escaping ProgressUpdate | Completion handler to execute after the attachment is retrieved. This is called multiple times until the upload process is complete. Return values for the completion handler: ProgressUpdate - Returns the current progress of the upload. `ProgressUpdate = (_bytesWritten: Int64, _totalBytesWritten: Int64, _totalBytesExpectedToWrite: Int64) -> Void` |
| completion | @escaping (Result\<[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata."), NowDataError\>) | Completion handler to execute after the metadata is uploaded. Return values for the completion handler: * Success: [NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.") - Object containing the metadata for the uploaded attachment. * 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. {#NAttServiOS-upload_O_O_O_O__NowDataErroriOS-ul-enum} |
[Table 31. Parameters]

{#NAttServiOS-upload_O_O_O_O__table_n5z_mpx_spb} {#NAttServiOS-upload_O_O_O_O__table_o5z_mpx_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 32. Returns]

{#NAttServiOS-upload_O_O_O_O__table_o5z_mpx_spb}  
The following code example shows how to call this function.

    typealias ProgressUpdate = (_ bytesWritten: Int64, _ totalBytesWritten: Int64, _ totalBytesExpectedToWrite: Int64) -> Void

    let image = UIImage(named: "photo.png") 
    let data = image.pngData() 
    let recordSysId = "" // Sys_id of the record on the SN instance

    let config = NowAttachmentUploadConfiguration(
      tableName: "tableName", 
      recordSysId: recordSysId, 
      fileName: "photo.png",
      contentType: "image/png",
      encryptionContext: nil)

    private func uploadFile(
      data: Data,
      config: NowAttachmentUploadConfiguration,
      progress: @escaping ProgressUpdate) {
        attachmentService.upload(data: data, configuration: config, progressUpdate: progress) { (result) in
          DispatchQueue.main.async { [weak self] in
            switch result {
              case .success(let response)
                do {
                  let data = try JSONEncoder().encode(response)
                    // Upload file successfully, return data
                } catch
                    // Upload file decode failed, return error
                }
              case .failure(let error):
                    // Upload file failed, return NowDataError
          }
        }
      }

## NowAttachmentService - upload(data: Data, configuration: NowAttachmentUploadConfiguration,
progressUpdate: @escaping ProgressUpdate) {#ariaid-title18}

Uploads the attachment data and attaches it to a record in a table as specified in the
upload configuration.
The ProgressUpdate callback provides upload progress information that
you can then use to provide UI feedback.  
Note:  
This method has been deprecated. You should use the async/await implementation of the method instead.
{#NAttServiOS-upload_O_O_O__table_ptn_lnx_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| data | Data | Attachment to upload. The data size and type of attachment that you can upload are controlled by your ServiceNow instance. |
| configuration | [NowAttachmentUploadConfiguration](https://servicenow-prod.fluidtopics.net/KPcSTDQScxtEAhSD~AI6Qg#NowAttachUploadConfigiOSStruct "The NowAttachmentUploadConfiguration structure enables you to define the configuration information for an attachment that you are uploading to your ServiceNow instance.") | Configuration information that defines the upload parameters for the attachment, such as: * Table and record to attach the file to * Attachment file name * Type of attachment * Whether the file is encrypted |
| progressUpdate | @escaping ProgressUpdate | Completion handler to execute after the attachment is retrieved. Return values for the completion handler: ProgressUpdate - Returns the current progress of the upload. This is called multiple times until the upload process is complete. `ProgressUpdate = (_bytesWritten: Int64, _totalBytesWritten: Int64, _totalBytesExpectedToWrite: Int64) -> Void` |
[Table 33. Parameters]

{#NAttServiOS-upload_O_O_O__table_ptn_lnx_spb} {#NAttServiOS-upload_O_O_O__table_qtn_lnx_spb__entry__2}

| Type | Description |
|-|-|
| AnyPublisher​\<[NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata."), NowDataError\> | Success: [NowAttachmentMetadata](https://servicenow-prod.fluidtopics.net/nwJnh9cBO0AXAggTe2nkCQ#NowAttachmentMetadataiOSStructure "The NowAttachmentMetadata structure provides functions that enable you to encode and manage attachment metadata.") - Object that contains the metadata for the requested attachment. 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. {#NAttServiOS-upload_O_O_O__NowDataErroriOS-ul-enum} |
[Table 34. Returns]

{#NAttServiOS-upload_O_O_O__table_qtn_lnx_spb}  
The following code example shows how to call this function.

    typealias ProgressUpdate = (_ bytesWritten: Int64, _ totalBytesWritten: Int64, _ totalBytesExpectedToWrite: Int64) -> Void

    let image = UIImage(named: "photo.png") 
    let data = image.pngData() 
    let recordSysId = "" // Sys_id of the record on the SN instance
    let config = NowAttachmentUploadConfiguration(
      tableName: "tableName", 
      recordSysId: recordSysId, 
      fileName: "photo.png",
      contentType: "image/png", 
      encryptionContext: nil)

    private func uploadFile(data: Data,
      config: NowAttachmentUploadConfiguration,
      progress: @escaping ProgressUpdate) {
        let publisher = attachmentService.upload(data: data, configuration: config, progressUpdate: progress)

        publisher
          .receive(on: DispatchQueue.main)
          .encode(encoder: JSONEncoder())
          .sink { [weak self] completion in
            if case let .failure(error) = completion {
              // Upload file failed, return NowDataError
            }
          } receiveValue: { [weak self] (data) in
            // Upload file successfully, return data
          }
          .store(in: &subscriptions)
      }


