View in English

  • Apple Developer
    • Get Started

    Explore Get Started

    • Overview
    • Learn
    • Apple Developer Program

    Stay Updated

    • Latest News
    • Hello Developer
    • Platforms

    Explore Platforms

    • Apple Platforms
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store

    Featured

    • Design
    • Distribution
    • Games
    • Accessories
    • Web
    • Home
    • CarPlay
    • Technologies

    Explore Technologies

    • Overview
    • Xcode
    • Swift
    • SwiftUI

    Featured

    • Accessibility
    • App Intents
    • Apple Intelligence
    • Games
    • Machine Learning & AI
    • Security
    • Xcode Cloud
    • Community

    Explore Community

    • Overview
    • Meet with Apple events
    • Community-driven events
    • Developer Forums
    • Open Source

    Featured

    • WWDC
    • Swift Student Challenge
    • Developer Stories
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Centers
    • Documentation

    Explore Documentation

    • Documentation Library
    • Technology Overviews
    • Sample Code
    • Human Interface Guidelines
    • Videos

    Release Notes

    • Featured Updates
    • iOS
    • iPadOS
    • macOS
    • watchOS
    • visionOS
    • tvOS
    • Xcode
    • Downloads

    Explore Downloads

    • All Downloads
    • Operating Systems
    • Applications
    • Design Resources

    Featured

    • Xcode
    • TestFlight
    • Fonts
    • SF Symbols
    • Icon Composer
    • Support

    Explore Support

    • Overview
    • Help Guides
    • Developer Forums
    • Feedback Assistant
    • Contact Us

    Featured

    • Account Help
    • App Review Guidelines
    • App Store Connect Help
    • Upcoming Requirements
    • Agreements and Guidelines
    • System Status
  • Quick Links

    • Events
    • News
    • Forums
    • Sample Code
    • Videos
 

Vídeos

Abrir menu Fechar menu
  • Coleções
  • Todos os vídeos
  • Sobre

Mais vídeos

  • Sobre
  • Código
  • Explore wellbeing APIs in HealthKit

    Learn how to incorporate mental health and wellbeing into your app using HealthKit. There are new APIs for State of Mind, as well as for Depression Risk and Anxiety Risk. We'll dive into principles of emotion science to cover how reflecting on feelings can be beneficial, and how State of Mind can be used to represent different types of mood and emotion.

    Capítulos

    • 0:00 - Introduction
    • 1:28 - Mental wellbeing APIs
    • 2:13 - State of Mind API
    • 8:54 - State of Mind predicates

    Recursos

    • Visualizing HealthKit State of Mind in visionOS
    • Forum: Health & Fitness
    • HealthKit
      • Vídeo HD
      • Vídeo SD

    Vídeos relacionados

    WWDC24

    • Enhanced suggestions for your journaling app
    • Get started with HealthKit in visionOS

    WWDC20

    • Getting started with HealthKit
  • Buscar neste vídeo...
    • 5:37 - Request authorization to read and write State of Mind HealthKit samples

      // Request authorization to read and write State of Mind HealthKit samples
      
      import HealthKitUI
      
      func healthDataAccessRequest(
          store: HKHealthStore, 
          shareTypes: Set<HKSampleType>,
          readTypes: Set<HKObjectType>? = nil,
          trigger: some Equatable,
          completion: @escaping (Result<Bool, any Error>) -> Void
      ) -> some View
    • 6:26 - EmojiType

      // EmojiType
      
      enum EmojiType: CaseIterable {
          case angry
          case sad
          case indifferent
          case satisfied
          case happy
          
          var emoji: String {
              switch self {
              case .angry: return "😡"
              case .sad: return "😢"
              case .indifferent: return "😐"
              case .satisfied: return "😌"
              case .happy: return "😊"
              }
          }
        
      }
    • 6:32 - Create State of Mind sample for an event and emoji selection

      /// Create State of Mind sample for an event and emoji selection
      
      func createSample(for event: EventModel, emojiType: EmojiType) ->
      HKStateOfMind {
          let kind: HKStateOfMind.Kind = .momentaryEmotion
          let valence: Double = emojiType.valence
          let label = emojiType.label
          let association = event.association
          return HKStateOfMind(date: event.endDate,
                               kind: kind,
                               valence: valence,
                               labels: [label],
                               associations: [association])
      }
    • 7:21 - Save State of Mind sample from emoji choice

      // Save State of Mind sample from emoji choice
      
      func save(sample: HKSample, healthStore: HKHealthStore) async {
          do {
              try await healthStore.save(sample)
          }
          catch {
              // Handle error here.
          }
      }
    • 10:34 - Query State of Mind samples

      // Query State of Mind samples
      
      let datePredicate: NSPredicate = { ... }
      let associationsPredicate = NSCompoundPredicate (
          orPredicateWithSubpredicates: associations.map {
              HKQuery.predicateForStatesOfMind(with: $0)
          }
      )  
      let compoundPredicate = NSCompoundPredicate(
          andPredicateWithSubpredicates: [datePredicate, associationsPredicate]
      )
      let state0fMindPredicate = HKSamplePredicate.stateOfMind(compoundPredicate)
    • 10:49 - Query State of Mind samples

      // Query State of Mind samples
      
      let datePredicate: NSPredicate = { ... }
      let associationsPredicate = NSCompoundPredicate (
          orPredicateWithSubpredicates: associations.map {
              HKQuery.predicateForStatesOfMind(with: $0)
          }
      )  
      let compoundPredicate = NSCompoundPredicate(
          andPredicateWithSubpredicates: [datePredicate, associationsPredicate]
      )
      let stateOfMindPredicate = HKSamplePredicate.stateOfMind(compoundPredicate)
      
      let descriptor = HKSampleQueryDescriptor(predicates: [stateOfMindPredicate],
                                               sortDescriptors: [])
      var results: [HKStateOfMind] = []
      do {
          // Launch the query and wait for the results.
          results = try await descriptor.result(for: healthStore)
      } catch {
          // Handle error here.
      }
    • 10:54 - Query State of Mind samples (continued)

      // Adjust each valence value to be from a range of 0.0 to 2.0.
      let adjustedValenceResults = results.map { $0.valence + 1.0 }
      // Calculate average valence.
      let totalAdjustedValence = adjustedValenceResults.reduce (0.0, +)
      let averageAdjustedValence = totalAdjustedValence / Double(results.count)
      // Convert valence to percentage.
      let adjustedValenceAsPercent = Int(100.0 * (averageAdjustedValence / 2.0))
    • 11:33 - Query for relevant State of Mind samples with a specific label

      // Query for relevant State of Mind samples with a specific label
      let label: HKStateOfMind.Label = .happy
      
      // Configure the query
      let datePredicate = HKQuery.predicateForSamples(withStart: dateInterval.start,
                                                      end: dateInterval.end)
      let associationPredicate = HKQuery.predicateForStatesOfMind(with: association)
      let labelPredicate = HKQuery.predicateForStates0fMind(with: label)
      let compoundPredicate = NSCompoundPredicate(
          andPredicateWithSubpredicates: [datePredicate, associationPredicate, labelPredicate]
      )
      let stateOfMindPredicate = HKSamplePredicate.stateOfMind(compoundPredicate)
      let descriptor = HKAnchoredObjectQueryDescriptor(predicates: [state0fMindPredicate],
                                                       anchor: nil)
      
      // Fetch the results
      let results = descriptor.results(for: healthStore)
      let samples: [HKStateOfMind] = try await results.reduce([]) { $1.addedSamples }
    • 11:45 - Process State of Mind sample data

      // Process State of Mind sample data
      
      let happiestSample = samples.max { $0.valence < $1. valence }
      let happiestEvent: EventModel? = findClosestEvent(startDate: happiestSample?.startDate,
                                                        endDate: happiestSample?.endDate)

Developer Footer

  • Vídeos
  • WWDC24
  • Explore wellbeing APIs in HealthKit
  • Open Menu Close Menu
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store
    Open Menu Close Menu
    • Swift
    • SwiftUI
    • Swift Playground
    • TestFlight
    • Xcode
    • Xcode Cloud
    • Icon Composer
    • SF Symbols
    Open Menu Close Menu
    • Accessibility
    • Accessories
    • Apple Intelligence
    • Audio & Video
    • Augmented Reality
    • Business
    • Design
    • Distribution
    • Education
    • Games
    • Health & Fitness
    • In-App Purchase
    • Localization
    • Maps & Location
    • Machine Learning & AI
    • Security
    • Safari & Web
    Open Menu Close Menu
    • Documentation
    • Downloads
    • Sample Code
    • Videos
    Open Menu Close Menu
    • Help Guides & Articles
    • Contact Us
    • Forums
    • Feedback & Bug Reporting
    • System Status
    Open Menu Close Menu
    • Apple Developer
    • App Store Connect
    • Certificates, IDs, & Profiles
    • Feedback Assistant
    Open Menu Close Menu
    • Apple Developer Program
    • Apple Developer Enterprise Program
    • App Store Small Business Program
    • MFi Program
    • Mini Apps Partner Program
    • News Partner Program
    • Video Partner Program
    • Security Bounty Program
    • Security Research Device Program
    Open Menu Close Menu
    • Meet with Apple
    • Apple Developer Centers
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Academies
    • WWDC
    Read the latest news.
    Get the Apple Developer app.
    Copyright © 2026 Apple Inc. All rights reserved.
    Terms of Use Privacy Policy Agreements and Guidelines