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
 

Videos

Abrir menú Cerrar menú
  • Colecciones
  • Todos los videos
  • Información

Más videos

  • Información
  • Código
  • There and back again: Data transfer on Apple Watch

    Advances in Apple Watch give you more ways to communicate to and from your app, and new audiences to consider. Learn what strategies are available for data communication and how to choose the right tool for the job. Compare and contrast the benefits of using technologies such as iCloud Keychain, Watch Connectivity, Core Data, and more.

    Recursos

    • Keeping your complications up to date
    • Downloading files from websites
    • WCSession
    • Sharing access to keychain items among a collection of apps
    • Keeping your watchOS content up to date
    • Supporting Associated Domains
      • Video HD
      • Video SD

    Videos relacionados

    WWDC21

    • Bring Core Data concurrency to Swift and SwiftUI
    • Build apps that share data through CloudKit and Core Data

    WWDC20

    • AutoFill everywhere
    • Keep your complications up to date

    WWDC19

    • Streaming Audio on watchOS 6
  • Buscar este video…
    • 4:20 - Password Autofill

      struct LoginView: View {
          
          @State private var username = ""
          @State private var password = ""
          
          var body: some View {
              Form {
                  TextField("User:", text: $username)
                      .textContentType(.username)
                  
                  SecureField("Password", text: $password) 
                      .textContentType(.password)
                  
                  Button {
                      processLogin()
                  } label: {
                      Text("Login")
                  }
                  
                  Button(role: .cancel) {
                      cancelLogin()
                  } label: {
                      Label("Cancel", systemImage: "xmark.circle")
                  }
              }
          }
          
          private func cancelLogin() {
              // Implement your cancel logic here
          }
          
          private func processLogin() {
              // Implement your login logic here
          }
      }
    • 6:25 - Store Item in Keychain

      func storeToken(_ token: OAuth2Token, for server: String, account: String) throws {
          let query: [String: Any] = [
            kSecClass as String: kSecClassInternetPassword,
            kSecAttrServer as String: server,
            kSecAttrAccount as String: account,
            kSecAttrSynchronizable as String: true,
          ]
          
          let tokenData = try encodeToken(token)
          let attributes: [String: Any] = [kSecValueData as String: tokenData]
          
          let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
          
          guard status != errSecItemNotFound else {
              try addTokenData(tokenData, for: server, account: account)
              return
          }
          
          guard status == errSecSuccess else {
              throw OAuthKeychainError.updateError(status)
          }
      }
    • 7:59 - Add Item to Keychain

      func addTokenData(_ tokenData: Data,
                        for server: String,
                        account: String) throws {
          let attributes: [String: Any] = [
            kSecClass as String: kSecClassInternetPassword,
            kSecAttrServer as String: server,
            kSecAttrAccount as String: account,
            kSecAttrSynchronizable as String: true,
            kSecValueData as String: tokenData,
          ]
          
          let status = SecItemAdd(attributes as CFDictionary, nil)
          
          guard status == errSecSuccess else {
              throw OAuthKeychainError.addError(status)
          }
      }
    • 8:25 - Retrieve Item from Keychain

      func retrieveToken(for server: String, account: String) throws -> OAuth2Token? {
          let query: [String: Any] = [
            kSecClass as String: kSecClassInternetPassword,
            kSecAttrServer as String: server,
            kSecAttrAccount as String: account,
            kSecAttrSynchronizable as String: true,
            kSecReturnAttributes as String: false,
            kSecReturnData as String: true,
          ]
              
          var item: CFTypeRef?
          let status = SecItemCopyMatching(query as CFDictionary,
                                           &item)
              
          guard status != errSecItemNotFound else {
              // No token stored for this server account combination.
              return nil
          }
          
          guard status == errSecSuccess else {
              throw OAuthKeychainError.retrievalError(status)
          }
          
          guard let existingItem = item as? [String : Any] else {
              throw OAuthKeychainError.invalidKeychainItemFormat
          }
          
          guard let tokenData = existingItem[kSecValueData as String] as? Data else {
              throw OAuthKeychainError.missingTokenDataFromKeychainItem
          }
          
          do {
              return try JSONDecoder().decode(OAuth2Token.self, from: tokenData)
          } catch {
              throw OAuthKeychainError.tokenDecodingError(error.localizedDescription)
          }
      }
    • 9:39 - Remove Item from Keychain

      func removeToken(for server: String, account: String) throws {
          let query: [String: Any] = [
            kSecClass as String: kSecClassInternetPassword,
            kSecAttrServer as String: server,
            kSecAttrAccount as String: account,
            kSecAttrSynchronizable as String: true,
          ]
        
          let status = SecItemDelete(query as CFDictionary)
          
          guard status == errSecSuccess || status == errSecItemNotFound else {
              throw OAuthKeychainError.deleteError(status)
          }
      }
    • 11:59 - Core Data SwiftUI View

      import CoreData
      import SwiftUI
      
      struct CoreDataView: View {
          
          @Environment(\.managedObjectContext) private var viewContext
          
          @FetchRequest(
              sortDescriptors: [NSSortDescriptor(keyPath: \Setting.itemKey, ascending: true)],
              animation: .easeIn)
          private var settings: FetchedResults<Setting>
          
          var body: some View {
              List {
                  ForEach(settings) { setting in
                      SettingRow(setting)
                  }
              }
          }
      }
    • 23:04 - Background URL Session Configuration

      class BackgroundURLSession: NSObject, ObservableObject, Identifiable {
          private let sessionIDPrefix = "com.example.backgroundURLSessionID."
          
          enum Status {
              case notStarted
              case queued
              case inProgress(Double)
              case completed
              case failed(Error)
          }
          
          private var url: URL
      
          /// Data to send with the URL request.
          ///
          /// If this is set, the HTTP method for the request will be POST
          var body: Data?
          
          /// Optional content type for the URL request
          var contentType: String?
          
          private(set) var id = UUID()
          
          /// The current status of the session
          @Published var status = Status.notStarted
          
          /// The downloaded data (populated when status == .completed)
          @Published var downloadedURL: URL?
          
          private var backgroundTasks = [WKURLSessionRefreshBackgroundTask]()
          
          private lazy var urlSession: URLSession = {
              let config = URLSessionConfiguration.background(withIdentifier: sessionID)
                  // Set isDiscretionary = true if you are sending or receiving large 
                  // amounts of data. Let Watch users know that their transfers might 
                  // not start until they are connected to Wi-Fi and power.
                  config.isDiscretionary = false
                  config.sessionSendsLaunchEvents = true
                  return URLSession(configuration: config,
                                    delegate: self, delegateQueue: nil)
              }()
          
          private var sessionID: String {
              "\(sessionIDPrefix)\(id.uuidString)"
          }
          
          /// Initialize the session
          /// - Parameter url: The URL for the Background URL Request
          init(url: URL) {
              self.url = url
              super.init()
          }
      
      }
    • 24:22 - Enqueue the background data transfer

      // This is a member of the BackgroundURLSession class in the example. 
      // Enqueue the URLRequest to send in the background. 
      func enqueueTransfer() {
          var request = URLRequest(url: url)
          request.httpBody = body
          if body != nil {
              request.httpMethod = "POST"
          }
          if let contentType = contentType {
              request.setValue(contentType, forHTTPHeaderField: "Content-type")
          }
          let task = urlSession.downloadTask(with: request)
          task.earliestBeginDate = nextTaskStartDate
        
          BackgroundURLSessions.sharedInstance().sessions[sessionID] = self
        
          task.resume()
          status = .queued
      }
    • 25:45 - WatchKit Extension Delegate

      class ExtensionDelegate: NSObject, WKExtensionDelegate {
          
          func applicationDidFinishLaunching() {
              // For Watch Connectivity, activate your WCSession as early as possible
              WatchConnectivityModel.shared.activateSession()
          }
          
          func applicationDidBecomeActive() {
              // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
          }
          
          func applicationWillResignActive() {
              // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
              // Use this method to pause ongoing tasks, disable timers, etc.
          }
          
          func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
              // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
              for task in backgroundTasks {
                  // Use a switch statement to check the task type
                  switch task {
                  case let backgroundTask as WKApplicationRefreshBackgroundTask:
                      // Be sure to complete the background task once you’re done.
                      backgroundTask.setTaskCompletedWithSnapshot(false)
                  case let snapshotTask as WKSnapshotRefreshBackgroundTask:
                      // Snapshot tasks have a unique completion call, make sure to set your expiration date
                      snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
                  case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
                      // Be sure to complete the connectivity task once you’re done.
                      connectivityTask.setTaskCompletedWithSnapshot(false)
                  case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
                      if let session = BackgroundURLSessions.sharedInstance()
                              .sessions[urlSessionTask.sessionIdentifier] {
                          session.addBackgroundRefreshTask(urlSessionTask)
                      } else {
                          // There is no model for this session, just set it complete
                          urlSessionTask.setTaskCompletedWithSnapshot(false)
                      }
                  case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
                      // Be sure to complete the relevant-shortcut task once you're done.
                      relevantShortcutTask.setTaskCompletedWithSnapshot(false)
                  case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
                      // Be sure to complete the intent-did-run task once you're done.
                      intentDidRunTask.setTaskCompletedWithSnapshot(false)
                  default:
                      // make sure to complete unhandled task types
                      task.setTaskCompletedWithSnapshot(false)
                  }
              }
          }
      }
    • 26:43 - Connect the WatchKit Extension Delegate to the App

      @main
      struct MyWatchApp: App {
          
          @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate
          
          @SceneBuilder var body: some Scene {
              WindowGroup {
                  NavigationView {
                      ContentView()
                  }
              }
          }
      }
    • 27:07 - Store the Background Refresh Task it can be completed

      // This is a member of the BackgroundURLSession class in the example. 
      // Add the Background Refresh Task to the list so it can be set to completed when the URL task is done.
      func addBackgroundRefreshTask(_ task: WKURLSessionRefreshBackgroundTask) {
          backgroundTasks.append(task)
      }
    • 27:31 - Process Downloaded Data

      extension BackgroundURLSession : URLSessionDownloadDelegate {
          
          private func saveDownloadedData(_ downloadedURL: URL) {
              // Move or quickly process this file before you return from this function.
              // The file is in a temporary location and will be deleted.
          }
          
          func urlSession(_ session: URLSession,
                          downloadTask: URLSessionDownloadTask,
                          didFinishDownloadingTo location: URL) {
              saveDownloadedData(location)
            
              // We don't need more updates on this session, so let it go.
              BackgroundURLSessions.sharedInstance().sessions[sessionID] = nil
            
              DispatchQueue.main.async {
                  self.status = .completed
              }
              
              for task in backgroundTasks {
                  task.setTaskCompletedWithSnapshot(false)
              }
          }
      }

Developer Footer

  • Videos
  • WWDC21
  • There and back again: Data transfer on Apple Watch
  • 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