Contents

streamData(for:dataHandler:)

Asynchronously returns the attachment’s data.

Declaration

func streamData(for attachment: HKAttachment, dataHandler: @escaping (Data?, (any Error)?, Bool) -> Void) -> Progress

Parameters

  • attachment:

    An attachment associated with an object in the HealthKit store.

  • dataHandler:

    A closure that the system calls repeatedly to return the attachment’s contents. This closure takes the following parameters:

    dataChunk

    A data object that contains the next chunk of the attachment’s contents. If an error occurred, the system sets this property to nil.

    error

    If an error occurred, this parameter contains information about the error. Otherwise, it’s nil.

    done

    A Boolean value that indicates whether the transfer is complete. If this is the last dataChunk, the system sets this property to True.

Discussion

Call this method to incrementally read the attachment’s contents directly from the attachment store.

var data = Data()
attachmentStore.streamData(for: myAttachment) { dataChunk, error, done in
    
    if let error {
        // Handle the error here.
        fatalError("*** An error occurred while streaming the attachment's data. \(error.localizedDescription) ***")
    }
    
    guard let dataChunk else { return }
    
    data.append(dataChunk)
    
    if done {
        // Use the attachment's data here.
        print(data)
    }
}

See Also

Accessing attachments