Accessibility announcement - SwiftUI

In SwiftUI, you can enhance your app's accessibility by announcing interface changes to assistive technologies.

To achieve this, you can use the UIAccessibility object's post method. By setting the type to announcement and providing a String argument, you can deliver custom announcements to users who rely on assistive technologies like VoiceOver.

In iOS 17 and higher, you can also use AccessibilityNotification. In this case, create an AccessibilityNotification.Announcement with a String or AttributedString.

When providing an AttributedString, you can optionally customize the announcement behavior.

The announcement priority can be set with the accessibilitySpeechAnnouncementPriority property. Available options are: high, default and low.

For more options, check the AccessibilityAttributes struct.

@State private var isLoading = false

var body: some View {
  VStack {
    Button("Search Appt website") {
      isLoading = true
    }
        
    if isLoading {
      ProgressView()
    }
  }
  // Track state changes
  .onChange(of: isLoading) { _, isLoading in
    if isLoading {
      announce("Search in progress")
    }
  }
}

// Post an announcement
fun announce(_ message: String) {
  if #available(iOS 17, *) {
    // iOS 17+ can use AccessibilityNotification
    var announcement = AttributedString(message)
    announcement.accessibilitySpeechAnnouncementPriority = .high
    AccessibilityNotification.Announcement(announcement).post()
  } else {
    // Lower iOS versions can use UIAccessibility
    UIAccessibility.post(
      notification: .announcement, 
      argument: message
    )
  }
}