Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Process an image and return the first table detected
- func extractTable(from image: Data) async throws -> DocumentObservation.Container.Table {
- // The Vision request.
- let request = RecognizeDocumentsRequest()
- // Perform the request on the image data and return the results.
- let observations = try await request.perform(on: image)
- // Get the first observation from the array.
- guard let document = observations.first?.document else {
- throw AppError.noDocument
- }
- // Extract the first table detected.
- guard let table = document.tables.first else {
- throw AppError.noTable
- }
- return table
- }
- /// Extract name, email addresses, and phone number from a table into a list of contacts.
- private func parseTable(_ table: DocumentObservation.Container.Table) {
- var foundItems = [Contact]()
- // Iterate over each row in the table.
- for row in table.rows {
- // The contact name will be taken from the first column.
- guard let firstCell = row.first else {
- continue
- }
- // Extract the text content from the transcript.
- let name = firstCell.content.text.transcript
- // Look for emails and phone numbers in the remaining cells.
- var detectedPhone: String? = nil
- var detectedEmail: String? = nil
- for cell in row.dropFirst() {
- // Get all detected data in the cell, then match emails and phone numbers.
- let allDetectedData = cell.content.text.detectedData
- for data in allDetectedData {
- switch data.match.details {
- case .emailAddress(let email):
- detectedEmail = email.emailAddress
- case .phoneNumber(let phoneNumber):
- detectedPhone = phoneNumber.phoneNumber
- default:
- break
- }
- }
- }
- // Create a contact if an email was detected.
- if let email = detectedEmail {
- let contact = Contact(name: name, email: email, phoneNumber: detectedPhone)
- foundItems.append(contact)
- }
- }
- contacts = foundItems
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement