filename
stringlengths
13
285
code
stringlengths
85
4.57M
SwiftUI.swift
## GradientBuilderApp.swift ```swift /* Abstract: The entry point into the app. */ import SwiftUI @main struct GradientBuilderApp: App { @State private var store = GradientModelStore.defaultStore var body: some Scene { WindowGroup { ContentView(store: $store) } } } ``` ## GradientModel.swift ```swift /* Abstract: The gradient model. */ import SwiftUI struct GradientModel: Equatable, Identifiable { /// A single gradient stop. struct Stop: Equatable, Identifiable { /// Stop color. var color: Color /// Stop location in [0, 1] range. var location: Double /// Unique identifier. var id: Int } /// Array of (possibly unsorted) color stops. var stops: [Stop] /// The name for this gradient. var name: String /// Unique identifier. var id: Int subscript(stopID stopID: Stop.ID) -> Stop { get { stops.first(where: { $0.id == stopID }) ?? Stop(color: .clear, location: 0, id: 0) } set { if let index = stops.firstIndex(where: { $0.id == stopID }) { stops[index] = newValue } } } @discardableResult mutating func append(color: Color, at location: Double) -> Stop { var id = 0 for stop in stops { id = max(id, stop.id) } let stop = Stop(color: color, location: location, id: id + 1) stops.append(stop) return stop } mutating func remove(_ stopID: Stop.ID) { stops.removeAll { $0.id == stopID } } var ordered: GradientModel { var copy = self copy.stops.sort(by: { $0.location < $1.location }) return copy } var gradient: Gradient { Gradient(stops: ordered.stops.map { Gradient.Stop(color: $0.color, location: $0.location) }) } } extension GradientModel { init(colors: [Color], name: String = "", id: Int = 0) { stops = [] for (index, color) in colors.enumerated() { stops.append(Stop( color: color, location: Double(index) / Double(colors.count - 1), id: index)) } self.name = name self.id = id } } ``` ## GradientModelStore.swift ```swift /* Abstract: Storage for the gradient model items. */ import SwiftUI struct GradientModelStore { var gradients: [GradientModel] = [] static let defaultStore: Self = { var data = Self() data.append(colors: [.gray, .white], name: "Grayscale") data.append(colors: [.teal, .blue], name: "Blue") data.append(colors: [.orange, .red], name: "Orange") data.append(colors: [.green, .mint], name: "Green") data.append(colors: [.purple, .indigo], name: "Purple") data.append(colors: [.pink, .red], name: "Pink") data.append(colors: [.black, .brown], name: "Dark") return data }() @discardableResult mutating func append(colors: [Color], name: String = "") -> GradientModel { var id = 0 for gradient in gradients { id = max(id, gradient.id) } let gradient = GradientModel(colors: colors, name: name, id: id + 1) gradients.append(gradient) return gradient } } ``` ## ContentView.swift ```swift /* Abstract: The main interface of the app. */ import SwiftUI struct ContentView: View { @Binding var store: GradientModelStore @State private var isPlaying = false var body: some View { #if os(iOS) content .fullScreenCover(isPresented: $isPlaying) { visualizer } #else let item = ToolbarItem(placement: .navigation) { Toggle(isOn: $isPlaying) { Image(systemName: "play.fill") } } if isPlaying { visualizer .toolbar { item } } else { content .toolbar { item } } #endif } var content: some View { NavigationView { List { ForEach(store.gradients.indices, id: \.self) { index in let gradient = store.gradients[index] NavigationLink(destination: GradientDetailView(gradient: $store.gradients[index])) { HStack { RoundedRectangle(cornerRadius: 6) .fill(.linearGradient(gradient.gradient, startPoint: .leading, endPoint: .trailing)) .frame(width: 32, height: 32) VStack(alignment: .leading) { gradient.name.isEmpty ? Text("New Gradient") : Text(gradient.name) Text("(gradient.stops.count) colors") .foregroundStyle(.secondary) } } } } } .navigationTitle("Gradients") .toolbar { ToolbarItem(placement: .primaryAction) { Button { store.append(colors: [.red, .orange, .yellow, .green, .blue, .indigo, .purple]) } label: { Image(systemName: "plus") } } #if os(iOS) ToolbarItem(placement: .cancellationAction) { Button { isPlaying = true } label: { Image(systemName: "play.fill") } } #endif } Text("No Gradient") } } var visualizer: some View { NavigationView { Visualizer(gradients: store.gradients.map(\.gradient)) .toolbar { #if os(iOS) Button { isPlaying = false } label: { Image(systemName: "xmark.circle.fill") } #endif } Text("Choose a visualizer") } .preferredColorScheme(.dark) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(store: .constant(GradientModelStore())) } } ``` ## GradientControl.swift ```swift /* Abstract: The gradient view. */ import SwiftUI struct GradientControl: View { @Binding var gradient: GradientModel @Binding var selectedStopID: Int? var drawGradient = true var body: some View { GeometryReader { geom in #if os(iOS) let dragGesture = DragGesture(minimumDistance: 0) .onEnded { selectedStopID = gradient.append( color: Color.white, at: $0.location.x / geom.size.width ).id } #endif VStack(spacing: 0) { if drawGradient { LinearGradient(gradient: gradient.gradient, startPoint: .leading, endPoint: .trailing) .border(.secondary, width: 1) } ZStack { ForEach(gradient.stops) { stop in StopHandle(stop: stop, gradient: $gradient, selectedStopID: $selectedStopID, width: geom.size.width) .position(x: geom.size.width * stop.location, y: 10) } } .frame(height: drawGradient ? 20 : 10) } #if os(iOS) .contentShape(Rectangle()) .gesture(dragGesture) #endif } .coordinateSpace(name: "gradient") .frame(minWidth: 200) .frame(height: drawGradient ? 50 : 10) } private struct StopHandle: View { var stop: GradientModel.Stop @Binding var gradient: GradientModel @Binding var selectedStopID: Int? var width: Double @GestureState private var oldLocation: Double? var body: some View { let dragGesture = DragGesture(coordinateSpace: .named("gradient")) .updating($oldLocation) { value, state, _ in if state == nil { state = stop.location } gradient[stopID: stop.id].location = max(0, min(1, state! + value.translation.width / width)) } let tapGesture = TapGesture().onEnded { selectedStopID = (selectedStopID == stop.id) ? nil : stop.id } Triangle() .frame(width: 12, height: 10) .foregroundStyle(stop.color) .overlay { Triangle().stroke(.secondary) } .scaleEffect(selectedStopID == stop.id ? 1.5 : 1) .animation(.default, value: selectedStopID == stop.id) .gesture(dragGesture) .gesture(tapGesture) #if os(macOS) .contextMenu { Button("Delete", role: .destructive) { gradient.remove(stop.id) } Button("Duplicate") { gradient.append(color: stop.color, at: stop.location + 0.05) } SystemColorPicker(color: $gradient[stopID: stop.id].color) } .focusable() .onDeleteCommand { gradient.remove(stop.id) } .onMoveCommand { direction in guard direction == .left || direction == .right else { return } let multiplier: Double = direction == .left ? -1 : 1 let newLocation = stop.location + multiplier * 0.01 gradient[stopID: stop.id].location = max(0, min(1, newLocation)) } #endif } } } struct Triangle: Shape { func path(in rect: CGRect) -> Path { Path { path in path.move(to: CGPoint(x: rect.midX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) path.closeSubpath() } } } ``` ## GradientDetailView.swift ```swift /* Abstract: The gradient detail view. */ import SwiftUI struct GradientDetailView: View { @Binding var gradient: GradientModel @State private var isEditing = false @State private var selectedStopID: Int? var body: some View { VStack { #if os(macOS) gradientBackground #else if !isEditing { gradientBackground } else { GradientControl(gradient: $gradient, selectedStopID: $selectedStopID) .padding() if let selectedStopID = selectedStopID { SystemColorList(color: $gradient[stopID: selectedStopID].color) { gradient.remove(selectedStopID) self.selectedStopID = nil } } else { SystemColorList.Empty() } } #endif } .safeAreaInset(edge: .bottom) { VStack(spacing: 0) { #if os(macOS) GradientControl(gradient: $gradient, selectedStopID: $selectedStopID, drawGradient: false) .padding(.horizontal) #endif HStack { #if os(macOS) // macOS always allows editing of the title TextField("Name", text: $gradient.name) .textFieldStyle(.roundedBorder) .frame(maxWidth: 200) #else if isEditing { TextField("Name", text: $gradient.name) } else { gradient.name.isEmpty ? Text("New Gradient") : Text(gradient.name) } #endif Spacer() Text("(gradient.stops.count) colors") .foregroundStyle(.secondary) } .padding() } .background(.thinMaterial) .controlSize(.large) } .navigationTitle(gradient.name) #if os(iOS) .toolbar { Button(isEditing ? "Done" : "Edit") { isEditing.toggle() } } .navigationBarTitleDisplayMode(.inline) #endif } private var gradientBackground: some View { LinearGradient(gradient: gradient.gradient, startPoint: .leading, endPoint: .trailing) .ignoresSafeArea(edges: .bottom) } } struct Detail_Previews: PreviewProvider { static var previews: some View { NavigationView { GradientDetailView( gradient: .constant(GradientModel(colors: [.red, .orange, .yellow, .green, .blue, .indigo, .purple]))) } } } ``` ## SystemColorPicker.swift ```swift /* Abstract: The color picker. */ import SwiftUI struct SystemColorList: View { @Binding var color: Color var remove: () -> Void var body: some View { List { Section(header: Text("Color")) { SystemColorPicker(color: $color) .pickerStyle(.inline) .labelsHidden() } Section { HStack { Spacer() Button("Delete", role: .destructive, action: remove) Spacer() } } } .listStyle(.plain) } struct Empty: View { var body: some View { List { Section(header: Text("Color")) { Text("No selection") .foregroundStyle(.secondary) } } .listStyle(.plain) } } } struct SystemColorPicker: View { @Binding var color: Color var body: some View { let options = [ ColorOption(name: "White", color: .white), ColorOption(name: "Gray", color: .gray), ColorOption(name: "Black", color: .black), ColorOption(name: "Red", color: .red), ColorOption(name: "Orange", color: .orange), ColorOption(name: "Yellow", color: .yellow), ColorOption(name: "Green", color: .green), ColorOption(name: "Mint", color: .mint), ColorOption(name: "Teal", color: .teal), ColorOption(name: "Cyan", color: .cyan), ColorOption(name: "Blue", color: .blue), ColorOption(name: "Indigo", color: .indigo), ColorOption(name: "Purple", color: .purple), ColorOption(name: "Pink", color: .pink), ColorOption(name: "Brown", color: .brown) ] Picker("Color", selection: $color) { ForEach(options) { option in Label { Text(option.name) } icon: { option.color .overlay { RoundedRectangle(cornerRadius: 6) .strokeBorder(.tertiary, lineWidth: 1) } .cornerRadius(6) .frame(width: 32, height: 32) } .tag(option.color) } } } } struct ColorOption: Identifiable { var name: String var color: Color var id: String { name } } ``` ## Visualizer.swift ```swift /* Abstract: The visualizer. */ import SwiftUI struct Visualizer: View { var gradients: [Gradient] var body: some View { List { NavigationLink(destination: ShapeVisualizer(gradients: gradients).ignoresSafeArea()) { Label("Shapes", systemImage: "star.fill") } NavigationLink(destination: ParticleVisualizer(gradients: gradients).ignoresSafeArea()) { Label("Particles", systemImage: "sparkles") } } .navigationTitle("Visualizers") } } ``` ## ParticleVisualizer.swift ```swift /* Abstract: The particle visualizer. */ import SwiftUI struct ParticleVisualizer: View { var gradients: [Gradient] @StateObject private var model = ParticleModel() var body: some View { TimelineView(.animation) { timeline in Canvas { context, size in let now = timeline.date.timeIntervalSinceReferenceDate model.update(time: now, size: size) context.blendMode = .screen model.forEachParticle { particle in var innerContext = context innerContext.opacity = particle.opacity innerContext.fill( Ellipse().path(in: particle.frame), with: particle.shading(gradients)) } } } .gesture( DragGesture(minimumDistance: 0) .onEnded { model.add(position: $0.location) } ) .accessibilityLabel("A particle visualizer") } } struct ParticleView_Previews: PreviewProvider { static var previews: some View { ParticleVisualizer(gradients: []) .preferredColorScheme(.dark) } } ``` ## Particle.swift ```swift /* Abstract: The definition of the particle. */ import SwiftUI struct Particle { var lifetime = 0.0 var position = CGPoint.zero var parentCenter = CGPoint.zero var velocity = CGSize.zero var size = 16.0 var sizeSpeed = 0.0 var opacity = 0.0 var opacitySpeed = 0.0 var gradientIndex = 0 var colorIndex = 0 var cell: ParticleCell? mutating func update(delta: Double) -> Bool { lifetime -= delta position.x += velocity.width * delta position.y += velocity.height * delta size += sizeSpeed * delta opacity += opacitySpeed * delta var active = lifetime > 0 if var cell = cell { cell.updateOldParticles(delta: delta) if active { cell.createNewParticles(delta: delta) { Particle(position: position, parentCenter: position, velocity: velocity, size: size, gradientIndex: gradientIndex) } } active = active || cell.isActive self.cell = cell } else { if (opacitySpeed <= 0 && opacity <= 0) || (sizeSpeed <= 0 && size <= 0) { active = false } } return active } var frame: CGRect { CGRect(origin: position, size: CGSize(width: size, height: size)) } func shading(_ gradients: [Gradient]) -> GraphicsContext.Shading { let stops = gradients[gradientIndex % gradients.count].stops return .color(stops[colorIndex % stops.count].color) } } ``` ## ParticleCell.swift ```swift /* Abstract: The particle cell. */ struct ParticleCell { typealias Generator = (inout Particle) -> Void var time = 0.0 var beginEmitting = 0.0 var endEmitting = Double.infinity var birthRate = 0.0 var lastBirth = 0.0 var generator: Generator = { _ in } var particles = [Particle]() var isActive: Bool { !particles.isEmpty } mutating func updateOldParticles(delta: Double) { let oldN = particles.count var newN = oldN var index = 0 while index < newN { if particles[index].update(delta: delta) { index += 1 } else { newN -= 1 particles.swapAt(index, newN) } } if newN < oldN { particles.removeSubrange(newN ..< oldN) } } mutating func createNewParticles(delta: Double, newParticle: () -> Particle) { time += delta guard time >= beginEmitting && lastBirth < endEmitting else { lastBirth = time return } let birthInterval = 1 / birthRate while time - lastBirth >= birthInterval { lastBirth += birthInterval guard lastBirth >= beginEmitting && lastBirth < endEmitting else { continue } var particle = newParticle() generator(&particle) if particle.update(delta: time - lastBirth) { particles.append(particle) } } } func forEachParticle(do body: (Particle) -> Void) { for index in particles.indices { if let cell = particles[index].cell { cell.forEachParticle(do: body) } else { body(particles[index]) } } } } ``` ## ParticleModel.swift ```swift /* Abstract: The particle model. */ import SwiftUI final class ParticleModel: ObservableObject { private var rootCell = ParticleCell(birthRate: 2.0) private var lastTime = 0.0 func update(time: Double, size: CGSize) { let delta = min(time - lastTime, 1.0 / 30.0) lastTime = time if delta > 0 { rootCell.updateOldParticles(delta: delta) rootCell.createNewParticles(delta: delta) { make(position: CGPoint( x: Double.random(in: 0..<size.width), y: Double.random(in: 0..<size.height))) } } } func add(position: CGPoint) { let particle = make(position: position) rootCell.particles.append(particle) } func make(position: CGPoint) -> Particle { var particle = Particle() particle.lifetime = 0.5 particle.position = position particle.parentCenter = particle.position particle.gradientIndex = Int.random(in: 0..<100) var cell = ParticleCell() cell.beginEmitting = 0.0 cell.endEmitting = Double.random(in: 0.05..<0.1) cell.birthRate = 8000 cell.generator = { particle in particle.lifetime = Double.random(in: 0.2..<0.5) let ang = Double.random(in: -.pi ..< .pi) let velocity = Double.random(in: 200..<400) particle.velocity = CGSize(width: velocity * cos(ang), height: velocity * -sin(ang)) particle.size *= Double.random(in: 0.25..<1) particle.sizeSpeed = -particle.size * 0.5 particle.opacity = Double.random(in: 0.25..<0.75) particle.opacitySpeed = -particle.opacity / particle.lifetime particle.colorIndex = Int.random(in: 0..<100) } particle.cell = cell return particle } func forEachParticle(do body: (Particle) -> Void) { rootCell.forEachParticle(do: body) } } ``` ## ShapeVisualizer.swift ```swift /* Abstract: The scale visualizer. */ import SwiftUI struct ShapeVisualizer: View { var gradients: [Gradient] @State private var state = SymbolState() var body: some View { GeometryReader { proxy in ZStack { ForEach(state.entries.indices, id: \.self) { index in let entry = state.entries[index] entry.symbol .foregroundStyle(.ellipticalGradient( gradients[entry.gradientSeed % gradients.count])) .scaleEffect(entry.selected ? 4 : 1) .position( x: proxy.size.width * entry.x, y: proxy.size.height * entry.y) .onTapGesture { withAnimation { state.entries[index].selected.toggle() } } .accessibilityAction { state.entries[index].selected.toggle() } } } } .font(.system(size: 24)) .contentShape(Rectangle()) .onTapGesture { withAnimation(.easeInOut(duration: 2)) { state.reposition() } } .accessibilityAction(named: "Reposition") { state.reposition() } .drawingGroup() } } struct SymbolState { var entries: [Entry] = [] init(count: Int = 100) { for index in 0..<count { entries.append(Entry(gradientSeed: index)) } } mutating func reposition() { for index in entries.indices { entries[index].reposition() } } struct Entry { var gradientSeed: Int var symbolSeed: Int var x: Double var y: Double var selected: Bool = false init(gradientSeed: Int) { self.gradientSeed = gradientSeed symbolSeed = Int.random(in: 1..<symbols.count) x = Double.random(in: 0..<1) y = Double.random(in: 0..<1) } mutating func reposition() { x = Double.random(in: 0..<1) y = Double.random(in: 0..<1) } var symbol: Image { Image(systemName: symbols[symbolSeed]) } } } private let symbols = [ "triangle.fill", "heart.fill", "star.fill", "diamond.fill", "octagon.fill", "capsule.fill", "square.fill", "seal.fill" ] ``` ## AppDelegate.swift ```swift /* Abstract: App delegate, which refers to the app's window. */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { return true } } ``` ## Model+Dragging.swift ```swift /* Abstract: Helper methods for providing and consuming drag-and-drop data. */ import UIKit import MobileCoreServices extension Model { /** A helper function that serves as an interface to the data model, called by the implementation of the `tableView(_ canHandle:)` method. */ func canHandle(_ session: UIDropSession) -> Bool { return session.canLoadObjects(ofClass: NSString.self) } /** A helper function that serves as an interface to the data mode, called by the `tableView(_:itemsForBeginning:at:)` method. */ func dragItems(for indexPath: IndexPath) -> [UIDragItem] { let placeName = placeNames[indexPath.row] let data = placeName.data(using: .utf8) let itemProvider = NSItemProvider() itemProvider.registerDataRepresentation(forTypeIdentifier: kUTTypePlainText as String, visibility: .all) { completion in completion(data, nil) return nil } return [ UIDragItem(itemProvider: itemProvider) ] } } ``` ## Model.swift ```swift /* Abstract: The model object for the table view. */ import Foundation /// The data model used to populate the table view on app launch. struct Model { private(set) var placeNames = [ "Yosemite", "Yellowstone", "Theodore Roosevelt", "Sequoia", "Pinnacles", "Mount Rainier", "Mammoth Cave", "Great Basin", "Grand Canyon" ] /// The traditional method for rearranging rows in a table view. mutating func moveItem(at sourceIndex: Int, to destinationIndex: Int) { guard sourceIndex != destinationIndex else { return } let place = placeNames[sourceIndex] placeNames.remove(at: sourceIndex) placeNames.insert(place, at: destinationIndex) } /// The method for adding a new item to the table view's data model. mutating func addItem(_ place: String, at index: Int) { placeNames.insert(place, at: index) } } ``` ## SceneDelegate.swift ```swift /* Abstract: The UIWindowSceneDelegate for this sample app. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? } ``` ## TableViewController+Data.swift ```swift /* Abstract: The standard delegate methods for a table view, which are required whether or not you add drag and drop. */ import UIKit // Logic that connects `TableViewController`'s data model with its user interface. extension TableViewController { // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model.placeNames.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = model.placeNames[indexPath.row] return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { model.moveItem(at: sourceIndexPath.row, to: destinationIndexPath.row) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } } ``` ## TableViewController+Drag.swift ```swift /* Abstract: Implements the delegate methods for providing data for a drag interaction. */ import UIKit extension TableViewController: UITableViewDragDelegate { // MARK: - UITableViewDragDelegate /** The `tableView(_:itemsForBeginning:at:)` method is the essential method to implement for allowing dragging from a table. */ func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { return model.dragItems(for: indexPath) } func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { navigationItem.rightBarButtonItem?.isEnabled = false } func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession) { navigationItem.rightBarButtonItem?.isEnabled = true } } ``` ## TableViewController+Drop.swift ```swift /* Abstract: Implements the delegate methods for consuming data for a drop interaction. */ import UIKit extension TableViewController: UITableViewDropDelegate { // MARK: - UITableViewDropDelegate /** Ensure that the drop session contains a drag item with a data representation that the view can consume. */ func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool { return model.canHandle(session) } /** A drop proposal from a table view includes two items: a drop operation, typically .move or .copy; and an intent, which declares the action the table view will take upon receiving the items. (A drop proposal from a custom view does includes only a drop operation, not an intent.) */ func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal { var dropProposal = UITableViewDropProposal(operation: .cancel) // Accept only one drag item. guard session.items.count == 1 else { return dropProposal } // The .move drag operation is available only for dragging within this app and while in edit mode. if tableView.hasActiveDrag { if tableView.isEditing { dropProposal = UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } } else { // Drag is coming from outside the app. dropProposal = UITableViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath) } return dropProposal } /** This delegate method is the only opportunity for accessing and loading the data representations offered in the drag item. The drop coordinator supports accessing the dropped items, updating the table view, and specifying optional animations. Local drags with one item go through the existing `tableView(_:moveRowAt:to:)` method on the data source. */ func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) { let destinationIndexPath: IndexPath if let indexPath = coordinator.destinationIndexPath { destinationIndexPath = indexPath } else { // Get last index path of table view. let section = tableView.numberOfSections - 1 let row = tableView.numberOfRows(inSection: section) destinationIndexPath = IndexPath(row: row, section: section) } coordinator.session.loadObjects(ofClass: NSString.self) { items in // Consume drag items. let stringItems = items as! [String] var indexPaths = [IndexPath]() for (index, item) in stringItems.enumerated() { let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section) self.model.addItem(item, at: indexPath.row) indexPaths.append(indexPath) } tableView.insertRows(at: indexPaths, with: .automatic) } } } ``` ## TableViewController.swift ```swift /* Abstract: Demonstrates how to enable drag and drop for a UITableView instance. */ import UIKit class TableViewController: UITableViewController { // MARK: - Properties var model = Model() // MARK: - View Life Cycle // Specify the table as its own drag source and drop delegate. override func viewDidLoad() { super.viewDidLoad() tableView.dragInteractionEnabled = true tableView.dragDelegate = self tableView.dropDelegate = self navigationItem.rightBarButtonItem = editButtonItem } } ``` ## BookClubApp.swift ```swift /* Abstract: The main app, which creates a scene, containing a window group, displaying a reading list view with data populated by the reading list data model. */ import SwiftUI @main struct BookClubApp: App { private var dataModel = ReadingListModel() var body: some Scene { WindowGroup("Reading List") { ReadingList(model: dataModel) } .commands { SidebarCommands() } #if os(macOS) WindowGroup("Book Details", for: Book.ID.self) { $bookId in BookDetailWindow(dataModel: dataModel, bookId: $bookId) } .commandsRemoved() Window("Reading Activity", id: "activity") { ReadingActivityList(activity: dataModel.activity) .frame(minWidth: 640, minHeight: 480) } .keyboardShortcut("1") .defaultPosition(.topTrailing) .defaultSize(width: 800, height: 600) #endif } } ``` ## Book.swift ```swift /* Abstract: A book data model. */ import SwiftUI struct Book: Identifiable { private(set) var id = UUID() let title: String let author: String let color: Color let coverName: String let description: String var byLine: String { "(title) by (author)" } } extension Book: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(id) hasher.combine(title) hasher.combine(author) hasher.combine(color) hasher.combine(coverName) hasher.combine(description) } } ``` ## Category.swift ```swift /* Abstract: An enumeration of reading list categories used to display sidebar items. */ import Foundation enum Category: Int, CaseIterable, Codable, Identifiable { case all case favorites case currentlyReading case wishlist var id: Self { self } var title: String { switch self { case .all: return "All Books" case .favorites: return "Favorites" case .currentlyReading: return "Currently Reading" case .wishlist: return "Wishlist" } } var iconName: String { switch self { case .all: return "books.vertical" case .favorites: return "heart" case .currentlyReading: return "book" case .wishlist: return "book.closed" } } } ``` ## CurrentlyReading.swift ```swift /* Abstract: A currently reading data model, which publishes changes to its subscribers. */ import SwiftUI class CurrentlyReading: Identifiable, ObservableObject { let book: Book @Published var progress = ReadingProgress() @Published var isFavorited = false @Published var isFinished = false var id: Book.ID { book.id } init(book: Book) { self.book = book } var isWishlisted: Bool { !hasProgress } var hasProgress: Bool { currentProgress > 0 } var currentProgress: Double { isFinished ? 1.0 : progress.progress } func markProgress(_ newProgress: Double, note: String? = nil) { progress.mark(newProgress, note: note) } func containsCaseInsensitive(query: String) -> Bool { guard !query.isEmpty else { return false } let content = [ book.title, book.author, book.description ] + progress.entries.compactMap(\.note) let results = content.first(where: { $0.range(of: query, options: .caseInsensitive) != nil }) return results != nil } } extension CurrentlyReading { static var mock: CurrentlyReading { MockFactory.currentlyReading[0] } static var mockFavorited: CurrentlyReading { let item = mock item.markProgress(0.5, note: "I love this!") item.isFavorited = true return item } static var mockWishlisted: CurrentlyReading { let item = mock item.markProgress(0, note: nil) item.isFavorited = false return item } } extension Collection where Element == CurrentlyReading { static var mocks: [CurrentlyReading] { MockFactory.currentlyReading } } extension Collection where Element == Category { static var mocks: [Category] { MockFactory.categories } } extension Color { fileprivate static func random<G: RandomNumberGenerator>( using generator: inout G ) -> Color { let hue = Double.random(in: 0...255, using: &generator) / 256 let brightness = Double.random(in: 64...127, using: &generator) / 256 return Color( hue: hue, saturation: 1, brightness: brightness, opacity: 1) } } private enum MockFactory { static let currentlyReading: [CurrentlyReading] = makeCurrentlyReading() static let categories = Category.allCases static func books() -> [Book] { var generator = SeededRandomNumberGenerator(seed: 6) return [ book( title: "Great Expectations", author: "Charles Dickens", using: &generator), book( title: "Pride and Prejudice", author: "Jane Austen", using: &generator), book( title: "Little Women", author: "Louisa May Alcott", using: &generator), book( title: "Wuthering Heights", author: "Emily Bront�", using: &generator), book( title: "Moby Dick", author: "Herman Melville", using: &generator), book( title: "Anne of Green Gables", author: "L.M. Montgomery", coverName: "Anne of Gables", using: &generator), book( title: "The Adventures of Sherlock Holmes", author: "Arthur Conan Doyle", coverName: "Sherlock Holmes", using: &generator), book( title: "Dracula", author: "Bram Stroker", using: &generator), book( title: "Frankenstein", author: "Mary Shelley", using: &generator) ] } private static func book<G: RandomNumberGenerator>( title: String, author: String, coverName: String? = nil, using generator: inout G ) -> Book { Book( title: title, author: author, color: .random(using: &generator), coverName: coverName == nil ? title : coverName!, description: placeholderDescription) } private static let placeholderDescription = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ Maecenas maximus viverra interdum. Ut interdum posuere magna, \ id porttitor ligula vehicula a. In turpis est, imperdiet non ante non, \ ultrices bibendum eros. Nam id lacinia tellus. Aliquam libero neque, \ fringilla eget mi a, ornare molestie sapien. Aenean malesuada tellus \ sit amet justo placerat, at egestas ligula pretium. """ private static let placeholderNotes = [ """ "Donec hendrerit justo sit amet arcu bibendum fringilla. \ Aenean scelerisque at orci vel dictum. \ Nam semper viverra viverra. """, """ Suspendisse elementum, tellus in malesuada hendrerit, \ sapien augue semper dolor, ac accumsan turpis risus in sem. """, """ Cras congue vel dui at semper. Etiam arcu ligula, \ pharetra sed cursus vel, dictum eget lacus. \ Nam lacinia maximus dolor, eget mattis dui fermentum sed. """, """ Nam non purus id diam vulputate vestibulum vitae quis neque. """, """ Sed ex felis, feugiat et felis sit amet, elementum euismod eros. \ Quisque gravida lobortis lacus, eu gravida nisl rhoncus quis. """ ] private static func makeCurrentlyReading() -> [CurrentlyReading] { var books = books().map(CurrentlyReading.init) let principalDate = Date(timeIntervalSince1970: 1_654_533_660) makeReadingProgress(for: &books, endDate: principalDate) makeFavorited(for: &books) makePrincipalBook(from: &books, startDate: principalDate) return books } private static func makeReadingProgress( for books: inout [CurrentlyReading], endDate: Date ) { let low = [0.1, 0.2, 0.3] let mid = [0.4, 0.5, 0.6] let high = [0.7, 0.8, 0.9] var generator = SeededRandomNumberGenerator(seed: 6) let progressBooks = books .dropFirst() // skip the principal book. .shuffled() .suffix(4) // randomly generate progress for (books 1-5) progressBooks.forEach { book in let dates = weekdays(endingOn: endDate).sorted() book.progress.mark( low.randomElement(using: &generator)!, date: dates[0...2].randomElement(using: &generator)!, note: placeholderNotes.randomElement(using: &generator)!) book.progress.mark( mid.randomElement(using: &generator)!, date: dates[3...4].randomElement(using: &generator)!, note: placeholderNotes.randomElement(using: &generator)!) book.progress.mark( high.randomElement(using: &generator)!, date: dates[5...6].randomElement(using: &generator)!, note: placeholderNotes.randomElement(using: &generator)!) } } private static func makeFavorited(for books: inout [CurrentlyReading]) { let favoritedBooks = books.filter { $0.hasProgress } .shuffled() .prefix(3) for book in favoritedBooks { book.isFavorited = true } } private static func makePrincipalBook( from books: inout [CurrentlyReading], startDate: Date ) { let principalBook = books[0] principalBook.progress.mark( 0.1, date: startDate, note: "?") principalBook.progress.mark( 0.42, date: Date(timeIntervalSince1970: 1_654_553_520), note: """ Maybe I should be working on my WWDC talk \ instead of reading, but this book is so good. """) principalBook.progress.mark( 0.57, date: Date(timeIntervalSince1970: 1_654_566_660), note: "?") } private static func weekdays( endingOn endDate: Date, in calendar: Calendar = .current ) -> [Date] { let startDate = calendar.date(byAdding: .day, value: -7, to: endDate)! let weekdayRange = calendar.range( of: .weekday, in: .weekOfYear, for: startDate)! let dayOfWeek = calendar.component(.weekday, from: startDate) - 1 let weekdays = weekdayRange.compactMap { weekday in calendar.date( byAdding: .day, value: weekday - dayOfWeek, to: startDate) } return weekdays } private static func randomDateInMonth() -> Date? { let date = Date() let calendar = Calendar.current let components: Set<Calendar.Component> = [.year, .month, .day] var dateComponents = calendar.dateComponents(components, from: date) guard let days = calendar.range(of: .day, in: .month, for: date) else { return nil } let randomDay = days.randomElement() dateComponents.setValue(randomDay, for: .day) return calendar.date(from: dateComponents) } } private struct SeededRandomNumberGenerator: RandomNumberGenerator { init(seed: Int) { srand48(seed) } func next() -> UInt64 { UInt64(drand48() * Double(UInt64.max)) } } ``` ## NavigationModel.swift ```swift /* Abstract: A navigation model used to persist and restore navigation state. */ import Combine import SwiftUI class NavigationModel: Codable, ObservableObject { enum CodingKeys: String, CodingKey { case columnVisibility case selectedCategory case selectedBookIds } @Published var columnVisibility: NavigationSplitViewVisibility @Published var selectedCategory: Category? @Published var selectedBookIds: Set<Book.ID> = [] @Published var jsonData: Data? private lazy var encoder = JSONEncoder() init( columnVisibility: NavigationSplitViewVisibility = .all, selectedCategory: Category? = .default, selectedBookIds: Set<Book.ID> = [] ) { self.columnVisibility = columnVisibility self.selectedCategory = selectedCategory self.selectedBookIds = selectedBookIds Publishers.Merge3( $columnVisibility.map { _ in }, $selectedCategory.map { _ in }, $selectedBookIds.map { _ in } ) .compactMap { [weak self] in guard let self = self else { return nil } return try? self.encoder.encode(self) } .assign(to: &$jsonData) } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) columnVisibility = try container.decode( NavigationSplitViewVisibility.self, forKey: .columnVisibility) selectedCategory = try container.decodeIfPresent( Category.self, forKey: .selectedCategory) selectedBookIds = try container.decodeIfPresent( Set<Book.ID>.self, forKey: .selectedBookIds) ?? [] } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(columnVisibility, forKey: .columnVisibility) try container.encodeIfPresent(selectedCategory, forKey: .selectedCategory) try container.encodeIfPresent(selectedBookIds, forKey: .selectedBookIds) } } extension NavigationModel: Equatable { static func ==(lhs: NavigationModel, rhs: NavigationModel) -> Bool { if ObjectIdentifier(lhs) == ObjectIdentifier(rhs) { return true } return lhs.columnVisibility == rhs.columnVisibility && lhs.selectedCategory == rhs.selectedCategory && lhs.selectedBookIds == rhs.selectedBookIds } } extension Optional where Wrapped == Category { fileprivate static var `default`: Category? { #if os(macOS) .all #else nil #endif } } ``` ## ProgressEditorModel.swift ```swift /* Abstract: Reading progress editor model for managing state and presentation. */ import Foundation struct ProgressEditorModel: Hashable { enum DismissAction { case save(in: CurrentlyReading) case cancel } var isPresented = false var note = "" var progress = 0.0 mutating func present(initialProgress: Double) { progress = initialProgress note = "" isPresented = true } mutating func dismiss(_ action: DismissAction) { switch action { case .save(let currentlyReading): currentlyReading.markProgress(progress, note: note) fallthrough case .cancel: isPresented = false note = "" } } mutating func togglePresentation(for currentlyReading: CurrentlyReading) { if isPresented { dismiss(.cancel) } else { present(initialProgress: currentlyReading.currentProgress) } } } extension ProgressEditorModel { static var mocks: [ProgressEditorModel] { [ .default, .presentedOnly, .presentedWithNote, .presentedWithNoteAndProgress, .noteOnly, .noteAndProgress ] } static var `default`: ProgressEditorModel { ProgressEditorModel() } static var presentedOnly: ProgressEditorModel { ProgressEditorModel(isPresented: true) } static var presentedWithNote: ProgressEditorModel { ProgressEditorModel(isPresented: true, note: note) } static var presentedWithNoteAndProgress: ProgressEditorModel { ProgressEditorModel(isPresented: true, note: note, progress: progress) } static var noteOnly: ProgressEditorModel { ProgressEditorModel(note: note) } static var noteAndProgress: ProgressEditorModel { ProgressEditorModel(note: note, progress: progress) } private static let note = "Hello World!" private static let progress = 0.75 } ``` ## ReadingActivity.swift ```swift /* Abstract: A reading activity data model representing a user's reading progress entries on macOS. */ import Combine #if os(macOS) class ReadingActivity: ObservableObject { let items: [CurrentlyReading] init(_ items: [CurrentlyReading]) { self.items = items } var entries: AnyPublisher<[ReadingActivityItem], Never> { items.publisher.flatMap { item in item.progress.entries.publisher.map { entry in ReadingActivityItem(book: item.book, entry: entry) } } .collect() .eraseToAnyPublisher() } } #endif ``` ## ReadingActivityItem.swift ```swift /* Abstract: A reading activity data model representing a user's reading progress entry on macOS. */ import Foundation struct ReadingActivityItem { var book: Book var entry: ReadingProgress.Entry } extension ReadingActivityItem: Comparable { static func <(lhs: ReadingActivityItem, rhs: ReadingActivityItem) -> Bool { if lhs.entry.date != rhs.entry.date { return lhs.entry.date < rhs.entry.date } else { return lhs.book.title < rhs.book.title } } } extension ReadingActivityItem: Equatable { static func ==(lhs: ReadingActivityItem, rhs: ReadingActivityItem) -> Bool { lhs.book.id == rhs.book.id && lhs.entry == rhs.entry } } extension ReadingActivityItem: Identifiable { struct ID: Hashable { var bookId: Book.ID var entryId: ReadingProgress.Entry.ID } var id: ID { ID(bookId: book.id, entryId: entry.id) } } extension ReadingActivityItem: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(book) hasher.combine(entry) hasher.combine(id) } } ``` ## ReadingListModel.swift ```swift /* Abstract: A reading list data model which generates mocked books for the sample app. */ import Combine import Foundation class ReadingListModel: ObservableObject { @Published var items: [CurrentlyReading] let categories: [Category] #if os(macOS) let activity: ReadingActivity #endif var favorites: [CurrentlyReading] { items.filter { $0.isFavorited } } var currentlyReading: [CurrentlyReading] { items.filter { $0.hasProgress } } var wishlist: [CurrentlyReading] { items.filter { $0.isWishlisted } } init( items: [CurrentlyReading] = .mocks, categories: [Category] = .mocks ) { self.items = items self.categories = categories #if os(macOS) self.activity = ReadingActivity(items) #endif } var objectWillChange: AnyPublisher<Void, Never> { $items .flatMap(\.publisher) .flatMap(\.objectWillChange) .eraseToAnyPublisher() } subscript(book id: Book.ID) -> CurrentlyReading? { items.first { $0.book.id == id } } subscript(books ids: [Book.ID]) -> [CurrentlyReading] { items.filter { ids.contains($0.id) } } subscript(category category: Category) -> [CurrentlyReading] { switch category { case .all: return items case .favorites: return favorites case .currentlyReading: return currentlyReading case .wishlist: return wishlist } } func items( for category: Category, matching query: String ) -> [CurrentlyReading] { let items = self[category: category] guard !query.isEmpty else { return items } return items.filter { $0.containsCaseInsensitive(query: query) } } } ``` ## ReadingProgress.swift ```swift /* Abstract: A reading progress data model used to track progress, and an entry data model used for input data. */ import Foundation struct ReadingProgress { var calendar: Calendar = .current private(set) var progress: Double = 0 private(set) var entriesByDate: [EntriesByDate] = [] var entries: [Entry] { entriesByDate.flatMap(\.entries) } mutating func mark( _ progress: Double, date: Date = Date(), note: String? = nil ) { let entry = Entry(progress: progress, date: date, note: note) addEntry(entry) } private mutating func addEntry(_ entry: Entry) { let dateComponents = entry.date.components(from: calendar) let existingEntryWithDateComponent = entriesByDate.first(where: { $0.dateComponents == dateComponents }) if let existingEntryByDate = existingEntryWithDateComponent { existingEntryByDate.entries.append(entry) } else { let newEntryByDate = EntriesByDate(entry: entry, calendar: calendar) entriesByDate.append(newEntryByDate) } progress = entry.progress } } extension ReadingProgress { class EntriesByDate: Hashable { let date: Date var entries: [Entry] let dateComponents: DateComponents init(date: Date, entries: [Entry], calendar: Calendar) { self.date = date self.entries = entries dateComponents = date.components(from: calendar) } convenience init(entry: Entry, calendar: Calendar) { self.init(date: entry.date, entries: [entry], calendar: calendar) } func contains(_ entry: Entry) -> Bool { entries.contains(entry) } func hash(into hasher: inout Hasher) { hasher.combine(date) hasher.combine(entries) hasher.combine(dateComponents) } static func ==(lhs: EntriesByDate, rhs: EntriesByDate) -> Bool { if ObjectIdentifier(lhs) == ObjectIdentifier(rhs) { return true } return lhs.dateComponents == rhs.dateComponents && lhs.entries == rhs.entries } } struct Entry: Identifiable, Comparable, Hashable { let id = UUID() let progress: Double let date: Date let calendar: Calendar = .current let note: String? var dateComponents: DateComponents { date.components(from: calendar) } static func <(lhs: Entry, rhs: Entry) -> Bool { lhs.date < rhs.date } } } ``` ## ColorAdditions.swift ```swift /* Abstract: Extended Color values used to define custom color values and assets. */ import SwiftUI extension Color { static var separator: Color { Color("separator") } static var arcInactiveStroke: Color { Color("arcInactiveStroke") } } ``` ## DateAdditions.swift ```swift /* Abstract: Extended Date values used to return DateComponents for a given Calendar. */ import Foundation extension Date { func components( _ components: Set<Calendar.Component> = [.year, .month, .day], from calendar: Calendar ) -> DateComponents { var dateComponents = calendar.dateComponents(components, from: self) dateComponents.calendar = calendar return dateComponents } } ``` ## LocaleAdditions.swift ```swift /* Abstract: Extended Locale values used to define custom locale identifiers. */ import Foundation extension Locale { static var italian: Locale { .init(identifier: "it_IT") } } ``` ## BookCard.swift ```swift /* Abstract: Book card view displaying the book title, author, and current reading progress. */ import SwiftUI struct BookCard: View { var book: Book var progress: Double var isSelected: Bool = false var body: some View { HStack { BookCover(book: book, size: 120) .padding(.vertical, 4) VStack(alignment: .leading) { Text(book.title) .lineLimit(3) .font(.title3) .fontWeight(.medium) Text(book.author) .foregroundStyle(.secondary) LinearReadingProgressView( value: progress, isSelected: isSelected) } .fixedSize(horizontal: false, vertical: true) Spacer() } .frame(maxWidth: .infinity) } } struct BookCard_Previews: PreviewProvider { static var previews: some View { let book = CurrentlyReading.mock.book return Group { BookCard(book: book, progress: 0.5, isSelected: true) BookCard(book: book, progress: 0.5, isSelected: false) } } } ``` ## BookContentList.swift ```swift /* Abstract: Book content list view showing filtered book results for a given category or search query. */ import SwiftUI struct BookContentList: View { @ObservedObject var dataModel: ReadingListModel @ObservedObject var navigationModel: NavigationModel @Environment(\.openWindow) private var openWindow @Environment(\.supportsMultipleWindows) private var supportsMultipleWindows @Environment(\.isSearching) private var isSearching private var searchText: String init( searchText: String, dataModel: ReadingListModel, navigationModel: NavigationModel ) { self.searchText = searchText self.dataModel = dataModel self.navigationModel = navigationModel } var body: some View { Group { if let category = navigationModel.selectedCategory { let items = dataModel.items(for: category, matching: searchText) List(selection: $navigationModel.selectedBookIds) { ForEach(items) { currentlyReading in NavigationLink(value: currentlyReading.id) { BookCard( book: currentlyReading.book, progress: currentlyReading.currentProgress, isSelected: isSelected(for: currentlyReading.id)) } .buttonStyle(.plain) } } .navigationTitle(category.title) .contextMenu(forSelectionType: Book.ID.self) { books in BookContextMenu(dataModel: dataModel, bookIds: books) } primaryAction: { books in if supportsMultipleWindows { books.forEach { openWindow(value: $0) } } else { books.compactMap { dataModel[book: $0] } .forEach { $0.isFavorited = true } } } #if os(macOS) .frame(minWidth: 240, idealWidth: 240) .navigationSubtitle(subtitle(for: items.count)) #endif } else { Text("No Category Selected") .font(.title) .foregroundStyle(.tertiary) } } .onDisappear { if navigationModel.selectedBookIds.isEmpty { navigationModel.selectedCategory = nil } } } func isSelected(for bookID: Book.ID) -> Bool { navigationModel.selectedBookIds.contains(bookID) } #if os(macOS) func subtitle(for count: Int) -> String { if isSearching { return "Found (count) results" } else { return count == 1 ? "(count) Item" : "(count) Items" } } #endif } struct BookContentList_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() let navigationModel = NavigationModel() return Group { BookContentList( searchText: "", dataModel: dataModel, navigationModel: navigationModel) BookContentList( searchText: "Jane", dataModel: dataModel, navigationModel: navigationModel) BookContentList( searchText: "", dataModel: dataModel, navigationModel: navigationModel) .environment(\.locale, .italian) BookContentList( searchText: "Jane", dataModel: dataModel, navigationModel: navigationModel) .environment(\.locale, .italian) } } } ``` ## BookContextMenu.swift ```swift /* Abstract: Book context menu view when for quick actions. */ import SwiftUI struct BookContextMenu: View { var dataModel: ReadingListModel var bookIds: Set<Book.ID> @Environment(\.supportsMultipleWindows) private var supportsMultipleWindows @Environment(\.openWindow) private var openWindow var body: some View { if supportsMultipleWindows { Section { Button { bookIds.forEach { openWindow(value: $0) } } label: { Label( bookIds.count > 1 ? "Open Each in New Window" : "Open in New Window", systemImage: "macwindow") } } } Section { let books = bookIds.compactMap { dataModel[book: $0] } Button { books.forEach { $0.markProgress(1.0) } } label: { Label( bookIds.count > 1 ? "Mark All as Finished" : "Mark as Finished", systemImage: "checkmark.square") } if bookIds.count == 1, let bookId = bookIds.first { FavoriteButton(dataModel: dataModel, bookId: bookId) ShareButton(dataModel: dataModel, bookId: bookId) } else { Button { books.forEach { $0.isFavorited = true } } label: { Label( bookIds.count > 1 ? "Add All to Favorites" : "Add to Favorites", systemImage: "heart") .symbolVariant( books.allSatisfy { $0.isFavorited } ? .fill : .none) } } } } } struct BookContextMenu_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() let bookId = CurrentlyReading.mock.id return Group { BookContextMenu(dataModel: dataModel, bookIds: [bookId]) BookContextMenu(dataModel: dataModel, bookIds: [bookId]) .environment(\.locale, .italian) } } } ``` ## BookCover.swift ```swift /* Abstract: Book cover view that displays an image or a rendered graphic and title overlay. */ import SwiftUI struct BookCover: View { var book: Book var size: CGFloat var image: Image { Image(book.coverName) .resizable() } var body: some View { RoundedRectangle(cornerRadius: 6, style: .continuous) .strokeBorder(strokeBorderStyle, lineWidth: 2) .overlay(alignment: .bottomLeading) { Title(book: book, fontSize: size / 12) .padding(padding / 2) } .padding(padding / 2) .background { Initial(book: book, fontSize: size) } .frame(width: size * 0.67, height: size) .overlay { image } } var strokeBorderStyle: some ShapeStyle { .background.blendMode(.colorDodge).opacity(0.5).shadow(.drop(radius: 3)) } var padding: CGFloat { size / 16 } } private struct Title: View { var book: Book var fontSize: CGFloat var body: some View { Text(book.title) .font(font) .minimumScaleFactor(0.25) .foregroundStyle(.background) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) .shadow(radius: 3) } var font: Font { .system(size: fontSize, weight: .medium, design: .rounded) } } private struct Initial: View { var book: Book var fontSize: CGFloat var body: some View { roundedRectangle .fill(book.color) .shadow(radius: 3, y: 3) .overlay { Text(initial) .font(font) .blendMode(.colorDodge) .foregroundStyle(foregroundStyle) .clipShape(roundedRectangle) } } var roundedRectangle: some Shape { RoundedRectangle(cornerRadius: 8, style: .continuous) } var initial: String { let title = book.title let offset = title.hasPrefix("The ") ? 4 : 0 let index = title.index(title.startIndex, offsetBy: offset) let character = title[index] return String(character) } var font: Font { .system(size: fontSize, weight: .ultraLight, design: .serif) } var foregroundStyle: some ShapeStyle { .background .blendMode(.colorDodge) .opacity(0.4) .shadow(.drop(radius: 3)) } } struct BookCover_Previews: PreviewProvider { static var previews: some View { BookCover(book: CurrentlyReading.mock.book, size: 216) } } ``` ## BookDetail.swift ```swift /* Abstract: Book detail view displaying the book detail view and action buttons. */ import SwiftUI struct BookDetail: View { @ObservedObject var dataModel: ReadingListModel private var bookIds: [Selection] @State private var isPresented = false init(dataModel: ReadingListModel, bookIds: Set<Book.ID>) { self.dataModel = dataModel let selection = zip(0..., bookIds).map(Selection.init).sorted() self.bookIds = selection } var body: some View { ZStack { if bookIds.isEmpty { Text("No Book Selected") .font(.title) .foregroundStyle(.tertiary) } else if let firstBook = dataModel[book: bookIds[0].bookId] { if bookIds.count == 1 { BookDetailContent(dataModel: dataModel, book: firstBook) .navigationTitle(firstBook.book.title) .toolbar { ToolbarItemGroup(placement: .primaryAction) { FavoriteButton(dataModel: dataModel, bookId: firstBook.id) ShareButton(dataModel: dataModel, bookId: firstBook.id) } ToolbarItemGroup(placement: toolbarItemPlacement) { Group { UpdateReadingProgressButton(book: firstBook) MarkAsFinishedButton(book: firstBook) } .labelStyle(.iconOnly) } } } else { ZStack { ForEach(bookIds, id: \.bookId) { selection in if let book = dataModel[book: selection.bookId] { BookDetailContent(dataModel: dataModel, book: book) .cornerRadius(8) .rotationEffect(.degrees(-2 * Double(selection.offset + 1))) .scaleEffect(0.9) .shadow(radius: 4) } } } .navigationTitle("(bookIds.count) Books Selected") } } } #if os(macOS) .frame(minWidth: 480, idealWidth: 480) #endif } var toolbarItemPlacement: ToolbarItemPlacement { #if os(iOS) return .bottomBar #else return .secondaryAction #endif } } private struct Selection: Comparable, Hashable, Identifiable { var offset: Int var bookId: Book.ID var id: Book.ID { bookId } static func <(lhs: Selection, rhs: Selection) -> Bool { lhs.offset < rhs.offset } } struct BookDetail_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() let bookId = CurrentlyReading.mock.id return Group { BookDetail(dataModel: dataModel, bookIds: []) BookDetail(dataModel: dataModel, bookIds: [bookId]) BookDetail(dataModel: dataModel, bookIds: []) .environment(\.locale, .italian) BookDetail(dataModel: dataModel, bookIds: [bookId]) .environment(\.locale, .italian) } } } ``` ## BookDetailContent.swift ```swift /* Abstract: Book detail view displaying the book metadata, as well as the user's reading progress and entry notes. */ import SwiftUI struct BookDetailContent: View { var dataModel: ReadingListModel @ObservedObject var book: CurrentlyReading #if os(iOS) @Environment(\.verticalSizeClass) private var verticalSizeClass #endif var body: some View { ScrollView { VStack(alignment: .leading) { BookDetailHeader(dataModel: dataModel, book: book) Divider() BookDetailReadingHistory(progress: book.progress) } .scenePadding(scenePadding) } .frame(minWidth: 350, minHeight: 350) .background(.background) } var scenePadding: Edge.Set { #if os(macOS) .all #else isCompactVerticalSizeClass ? .all : [.horizontal, .bottom] #endif } var isCompactVerticalSizeClass: Bool { #if os(iOS) return verticalSizeClass == .compact #else return false #endif } } struct BookDetailContent_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() return Group { BookDetailContent(dataModel: dataModel, book: .mock) BookDetailContent(dataModel: dataModel, book: .mock) .environment(\.locale, .italian) } } } ``` ## BookDetailHeader.swift ```swift /* Abstract: Book detail subview displaying the book metadata and the user's reading progress. */ import SwiftUI struct BookDetailHeader: View { var dataModel: ReadingListModel @ObservedObject var currentlyReading: CurrentlyReading #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass #endif init( dataModel: ReadingListModel, book currentlyReading: CurrentlyReading ) { self.dataModel = dataModel self.currentlyReading = currentlyReading } var body: some View { HStack(alignment: .top) { #if os(macOS) VStack { bookCover .padding(.bottom, 5) progressView } VStack(alignment: .leading) { title author description .padding(.top, 5) } .padding(.leading, 5) #else if isCompactVerticalSizeClass { VStack(alignment: .leading) { HStack { VStack { bookCover .padding(.bottom, 5) progressView } VStack(alignment: .leading) { author .padding(.bottom, 5) description Spacer() ButtonFooter(currentlyReading: currentlyReading) } .padding(.leading) } } } else { VStack(alignment: .leading) { author .padding(.leading, isCompactHorizonalSizeClass ? 0 : 5) HStack(alignment: .bookCover) { VStack { bookCover .padding(.bottom, 5) .alignmentGuide(.bookCover) { dimensions in dimensions[VerticalAlignment.center] } progressView } VStack(alignment: .trailing) { description .padding(.leading) .alignmentGuide(.bookCover) { dimensions in dimensions[VerticalAlignment.center] } if isCompactHorizonalSizeClass { ButtonFooter(currentlyReading: currentlyReading) } } } } } #endif } } var bookCover: some View { BookCover( book: currentlyReading.book, size: isCompactHorizonalSizeClass ? 148 : 172) } var progressView: some View { StackedProgressView(value: currentlyReading.currentProgress) } var isCompactHorizonalSizeClass: Bool { #if os(iOS) return horizontalSizeClass == .compact #else return false #endif } var isCompactVerticalSizeClass: Bool { #if os(iOS) return verticalSizeClass == .compact #else return false #endif } var title: some View { Text(currentlyReading.book.title) .font(.title) .fontWeight(.medium) .lineLimit(3) .minimumScaleFactor(0.7) } var author: some View { Text(currentlyReading.book.author) .font(.title3) .foregroundStyle(.secondary) } var description: some View { Text(currentlyReading.book.description) .font(.callout) .lineLimit(isCompactHorizonalSizeClass ? 7 : nil) } } extension VerticalAlignment { private struct BookCover: AlignmentID { static func defaultValue(in dimensions: ViewDimensions) -> CGFloat { dimensions[VerticalAlignment.center] } } fileprivate static let bookCover = VerticalAlignment(BookCover.self) } private struct ButtonFooter: View { var currentlyReading: CurrentlyReading @State private var showBookDescription = false var body: some View { HStack(alignment: .bottom) { Spacer() Button { showBookDescription.toggle() } label: { Label( "Read full description", systemImage: "ellipsis.circle") } UpdateReadingProgressButton(book: currentlyReading) MarkAsFinishedButton(book: currentlyReading) } .buttonStyle(.bordered) .labelStyle(.iconOnly) .sheet(isPresented: $showBookDescription) { BookDescriptionSheet(book: currentlyReading.book) } } } private struct BookDescriptionSheet: View { var book: Book var body: some View { VStack(alignment: .leading) { Text("Description") .font(.title3) .fontWeight(.medium) .padding(.vertical) Text(book.description) .presentationDetents([.medium]) .presentationDragIndicator(.visible) Spacer() } .scenePadding() } } struct BookDetailHeader_Previews: PreviewProvider { static var previews: some View { Group { ForEach(ProgressEditorModel.mocks, id: \.self) { model in BookDetailHeader( dataModel: ReadingListModel(), book: CurrentlyReading.mock) } } } } ``` ## BookDetailReadingHistory.swift ```swift /* Abstract: Book detail subview displaying the user's reading history, including reading progress and entry notes. */ import SwiftUI struct BookDetailReadingHistory: View { var progress: ReadingProgress var body: some View { VStack { Text("Reading Progress") .fontWeight(.medium) .padding(.vertical) BookDetailReadingProgressChart(entries: progress.entries) Divider() .padding(.vertical) Text("Notes") .fontWeight(.medium) .padding(.vertical) BookDetailReadingProgressNotesList(progress: progress) } } } struct BookDetailReadingHistory_Previews: PreviewProvider { static var previews: some View { BookDetailReadingHistory(progress: CurrentlyReading.mock.progress) } } ``` ## BookDetailReadingProgressChart.swift ```swift /* Abstract: Book detail subview displaying the user's reading progress as a line chart. */ import SwiftUI import Charts struct BookDetailReadingProgressChart: View { var entries: [ReadingProgress.Entry] var body: some View { if entries.isEmpty { Text("--") .foregroundColor(.secondary) .font(.caption) .frame(minHeight: 50) } else { Chart(entries) { entry in LineMark( x: .value("Date", entry.date), y: .value("Progress", entry.progress) ) } .frame(minHeight: 100) } } } struct BookDetailReadingProgressChart_Previews: PreviewProvider { static var previews: some View { let entries = CurrentlyReading.mock.progress.entries return BookDetailReadingProgressChart(entries: entries) } } ``` ## BookDetailReadingProgressNotesList.swift ```swift /* Abstract: Book detail subview displaying the user's reading progress notes in a list. */ import SwiftUI struct BookDetailReadingProgressNotesList: View { private var entriesByDate: [ReadingProgress.EntriesByDate] init(progress: ReadingProgress) { entriesByDate = progress.entriesByDate.reversed() } var body: some View { if entriesByDate.isEmpty { Text("--") .foregroundColor(.secondary) .font(.caption) .frame(minHeight: 50) } else { VStack(alignment: .leading) { ForEach(entriesByDate, id: \.self) { value in Section { ForEach(value.entries.sorted(by: >)) { entry in BookDetailReadingProgressRow(entry: entry) } } header: { VStack(alignment: .leading) { Text(value.date, style: .date) .font(.subheadline) .padding(padding) Divider() } } } } .frame(minHeight: 100) } } var padding: EdgeInsets { EdgeInsets(top: 8, leading: 12, bottom: 0, trailing: 12) } } struct BookDetailReadingProgressNotesList_Previews: PreviewProvider { static var previews: some View { let progress = CurrentlyReading.mock.progress return BookDetailReadingProgressNotesList(progress: progress) } } ``` ## BookDetailReadingProgressRow.swift ```swift /* Abstract: Book detail subview displaying the user's reading progress for a given entry. */ import SwiftUI struct BookDetailReadingProgressRow: View { var entry: ReadingProgress.Entry var body: some View { HStack { CircularProgressView(value: entry.progress) .frame(width: 64, height: 64) .padding(.trailing) if let note = entry.note { Text(note) Spacer() } } .padding(padding) } var padding: EdgeInsets { EdgeInsets(top: 4, leading: 12, bottom: 4, trailing: 12) } } struct BookDetailReadingProgressRow_Previews: PreviewProvider { static var previews: some View { let entry = CurrentlyReading.mock.progress.entries[0] return BookDetailReadingProgressRow(entry: entry) } } ``` ## BookDetailWindow.swift ```swift /* Abstract: Book detail view, which opens in its own presented window, displaying the book metadata, current reading progress, and notes. */ import SwiftUI struct BookDetailWindow: View { @ObservedObject var dataModel: ReadingListModel @Binding var bookId: Book.ID? var body: some View { if let bookId = bookId, let book = dataModel[book: bookId] { BookDetailContent(dataModel: dataModel, book: book) } else { Text("No Book Selected") .font(.title) .foregroundStyle(.tertiary) } } } struct BookDetailWindow_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() let bookId = CurrentlyReading.mock.id return Group { BookDetailWindow(dataModel: dataModel, bookId: .constant(bookId)) BookDetailWindow(dataModel: dataModel, bookId: .constant(bookId)) .environment(\.locale, .italian) } } } ``` ## CircularProgressView.swift ```swift /* Abstract: A circular progress view, that starts its progress from a 180 degree angle, and displays its percentage at the center. */ import SwiftUI struct CircularProgressView: View { var value: Double var body: some View { ProgressView(value: value) .progressViewStyle(CircularProgressViewStyle()) .frame(width: 60, height: 60) } } private struct CircularProgressViewStyle: ProgressViewStyle { func makeBody(configuration: Configuration) -> some View { let value = configuration.fractionCompleted ?? 0 return ArcView(value: value) } } private struct ArcView: View { var value: Double var body: some View { GeometryReader { proxy in ZStack { Circle() .strokeBorder(Color.arcInactiveStroke, style: strokeStyle) Arc(endAngle: .degrees(360 * value)) .strokeBorder(linearGradient, style: strokeStyle) .animation(.easeInOut(duration: 2), value: value) Text(Int(value * 100), format: .percent) .fontWeight(.thin) .frame(width: proxy.size.width * 0.9) } } } var strokeStyle: StrokeStyle { StrokeStyle(lineWidth: 6, lineCap: .round) } var linearGradient: LinearGradient { LinearGradient( gradient: Gradient(colors: [.blue, .purple]), startPoint: .bottomLeading, endPoint: .topTrailing ) } } private struct Arc: InsettableShape { var startAngle: Angle = .zero var endAngle: Angle var insetAmount: Double = .zero func path(in rect: CGRect) -> Path { let rotation = Angle.degrees(-90) var path = Path() path.addArc( center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2 - insetAmount, startAngle: startAngle - rotation, endAngle: endAngle - rotation, clockwise: false) return path } func inset(by amount: CGFloat) -> some InsettableShape { var arc = self arc.insetAmount += amount return arc } } struct CircularProgressView_Previews: PreviewProvider { static var previews: some View { ForEach([0, 0.25, 0.5, 0.75, 1], id: \.self) { value in CircularProgressView(value: value) } } } ``` ## FavoriteButton.swift ```swift /* Abstract: Favorite button to mark a currently reading book as favorited. */ import SwiftUI struct FavoriteButton: View { var dataModel: ReadingListModel var bookId: Book.ID? var body: some View { Button { toggleIsFavorited() } label: { Label("Favorite", systemImage: "heart") .symbolVariant(isFavorited() ? .fill : .none) } .help("Favorite the book.") .disabled(bookId == nil || isWishlisted()) } func toggleIsFavorited() { guard let bookId = bookId, let book = dataModel[book: bookId] else { return } book.isFavorited.toggle() } func isFavorited() -> Bool { guard let bookId = bookId, let book = dataModel[book: bookId] else { return false } return book.isFavorited } func isWishlisted() -> Bool { guard let bookId = bookId, let book = dataModel[book: bookId] else { return false } return book.isWishlisted } } struct FavoriteButton_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() return Group { FavoriteButton(dataModel: dataModel, bookId: nil) FavoriteButton( dataModel: dataModel, bookId: CurrentlyReading.mockFavorited.id) FavoriteButton( dataModel: dataModel, bookId: CurrentlyReading.mockWishlisted.id) } } } ``` ## LinearProgressView.swift ```swift /* Abstract: A linear progress view that displays its percentage at the leading edge. */ import SwiftUI struct LinearReadingProgressView: View { var value: Double var isSelected: Bool var body: some View { let style = LinearReadingProgressViewStyle(isSelected: isSelected) ProgressView(value: value) .progressViewStyle(style) .frame(width: 125) } } private struct LinearReadingProgressViewStyle: ProgressViewStyle { var isSelected: Bool func makeBody(configuration: Configuration) -> some View { let value = configuration.fractionCompleted ?? 0 return HStack { ZStack(alignment: .leading) { Capsule(style: .continuous) .foregroundStyle(.tertiary) .overlay { GeometryReader { proxy in Capsule(style: .continuous) .frame(width: proxy.size.width * value) .foregroundStyle(foregroundStyle(for: value)) } } } .frame(height: 4) Text(Int(value * 100), format: .percent) } func foregroundStyle(for value: Double) -> some ShapeStyle { if isSelected { return AnyShapeStyle(.background) } else if value == 1 { return AnyShapeStyle(.green) } else { return AnyShapeStyle(.tint) } } } } struct LinearReadingProgressView_Previews: PreviewProvider { static var previews: some View { LinearReadingProgressView(value: 0.5, isSelected: true) LinearReadingProgressView(value: 0.5, isSelected: false) } } ``` ## MarkAsFinishedButton.swift ```swift /* Abstract: A button to mark a book as finished, which sets its reading progress to 100%. */ import SwiftUI struct MarkAsFinishedButton: View { @ObservedObject var currentlyReading: CurrentlyReading init(book currentlyReading: CurrentlyReading) { self.currentlyReading = currentlyReading } var body: some View { Button { withAnimation { currentlyReading.isFinished.toggle() } } label: { Label("Mark As Finished", systemImage: "checkmark.square") } .help("Mark the book's reading progress as completed.") .disabled(currentlyReading.isFinished) } } struct MarkAsFinishedButton_Previews: PreviewProvider { static var previews: some View { MarkAsFinishedButton(book: .mock) } } ``` ## ProgressEditor.swift ```swift /* Abstract: Progress details editor view for updating the user's reading progress entries. */ import SwiftUI struct ProgressEditor: View { @ObservedObject var currentlyReading: CurrentlyReading @Binding var model: ProgressEditorModel @FocusState private var isTextEditorFocused: Bool init( book currentlyReading: CurrentlyReading, model: Binding<ProgressEditorModel> ) { self.currentlyReading = currentlyReading _model = model } var body: some View { VStack(alignment: .leading) { HStack { Slider(value: $model.progress, in: 0...1) Text(Int(model.progress * 100), format: .percent) } .padding(.bottom) TextField("Notes", text: $model.note, axis: .vertical) .lineLimit(5, reservesSpace: true) .focused($isTextEditorFocused) Spacer() buttons } .padding() #if os(iOS) .toolbar { ToolbarItemGroup(placement: .keyboard) { buttons } } .onAppear { isTextEditorFocused = true } #endif } var buttons: some View { HStack { Button("Cancel", action: cancel) Spacer() Button("Save", action: save) } } func cancel() { isTextEditorFocused = false model.dismiss(.cancel) } func save() { isTextEditorFocused = false model.dismiss(.save(in: currentlyReading)) } } extension View { func progressEditorModal( book: CurrentlyReading, model: Binding<ProgressEditorModel> ) -> some View { modifier(ProgressEditorModifier(book: book, model: model)) } } private struct ProgressEditorModifier: ViewModifier { #if os(iOS) @Environment(\.horizontalSizeClass) var horizontalSizeClass #endif @ObservedObject var book: CurrentlyReading @Binding var model: ProgressEditorModel func body(content: Content) -> some View { if isCompactHorizonalSizeClass { content.sheet(isPresented: $model.isPresented) { ProgressEditor(book: book, model: $model) .presentationDetents([.height(300)]) .presentationDragIndicator(.visible) } } else { content.popover(isPresented: $model.isPresented) { ProgressEditor(book: book, model: $model) .frame(idealWidth: 300, minHeight: 200, maxHeight: 250) } } } var isCompactHorizonalSizeClass: Bool { #if os(iOS) return horizontalSizeClass == .compact #else return false #endif } } struct ProgressEditor_Previews: PreviewProvider { static var previews: some View { Group { ForEach(ProgressEditorModel.mocks, id: \.self) { model in ProgressEditor(book: .mock, model: .constant(model)) } } } } ``` ## ReadingActivityList.swift ```swift /* Abstract: Reading activity list displayed from the Window > Activity menu item on macOS. */ import SwiftUI import Charts #if os(macOS) struct ReadingActivityList: View { @ObservedObject var activity: ReadingActivity @State private var items: [ReadingActivityItem] = [] @State private var selection: Set<ReadingActivityItem.ID> = [] var body: some View { VStack { Chart(chartData) { item in LineMark( x: .value("Date", item.entry.date), y: .value("Progress", item.entry.progress) ) .foregroundStyle(by: .value("Book", item.book.title)) } .chartForegroundStyleScale(domain: items.map(\.book.title)) .chartLegend(position: .bottom, alignment: .center, spacing: 20) .frame(minHeight: 240) .scenePadding() Table(items, selection: $selection) { TableColumn("Book") { item in Text(item.book.title) } .width(min: 240) TableColumn("Date") { item in Text(item.entry.date, style: .date) } .width(min: 120) TableColumn("Completion") { item in Text(item.entry.progress, format: .percent) } .width(min: 60) } .onReceive(activity.entries) { items = $0.sorted(by: >) } } } var chartData: [ReadingActivityItem] { guard !selection.isEmpty else { return items } return items.filter { selection.map(\.bookId).contains($0.book.id) } } } #endif ``` ## ReadingList.swift ```swift /* Abstract: The main reading list view for the app for the app's root scene. */ import SwiftUI struct ReadingList: View { var dataModel: ReadingListModel @SceneStorage("navigation") private var navigationData: Data? @StateObject private var navigationModel = NavigationModel() @State private var searchText = "" init(model: ReadingListModel) { dataModel = model } var body: some View { NavigationSplitView( columnVisibility: $navigationModel.columnVisibility ) { Sidebar( searchText: searchText, dataModel: dataModel, navigationModel: navigationModel) } content: { BookContentList( searchText: searchText, dataModel: dataModel, navigationModel: navigationModel) .searchable(text: $searchText) } detail: { BookDetail( dataModel: dataModel, bookIds: navigationModel.selectedBookIds) } .task { if let data = navigationData { navigationModel.jsonData = data } for await jsonData in navigationModel.$jsonData.values { if let data = jsonData { navigationData = data } } } } } struct ReadingList_Previews: PreviewProvider { static var previews: some View { let model = ReadingListModel() return Group { ReadingList(model: model) ReadingList(model: model) .environment(\.locale, .italian) } } } ``` ## ShareButton.swift ```swift /* Abstract: Share button to send book metadata to another application, with a share preview displaying a visual representation of the share data. */ import SwiftUI struct ShareButton: View { var dataModel: ReadingListModel var bookId: Book.ID? var body: some View { Group { if let bookId = bookId, let currentlyReading = dataModel[book: bookId], let image = image(for: currentlyReading) { let byLine = currentlyReading.book.byLine ShareLink( item: image, message: Text(byLine), preview: SharePreview(byLine, image: image)) } else { Button { } label: { Label("Share", systemImage: "square.and.arrow.up") } .disabled(true) } } .help("Share the book with friends.") } @MainActor func image(for currentlyReading: CurrentlyReading) -> Image? { let book = currentlyReading.book let progress = currentlyReading.currentProgress let bookCard = BookCard(book: book, progress: progress) let renderer = ImageRenderer(content: bookCard) guard let cgImage = renderer.cgImage else { return nil } let label = Text(book.byLine) let image = Image(cgImage, scale: renderer.scale, label: label) return image.resizable() } } struct ShareButton_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() return Group { ShareButton(dataModel: dataModel, bookId: nil) ShareButton( dataModel: dataModel, bookId: CurrentlyReading.mockFavorited.id) ShareButton( dataModel: dataModel, bookId: CurrentlyReading.mockWishlisted.id) } } } ``` ## Sidebar.swift ```swift /* Abstract: Sidebar view displaying a list of book categories. */ import SwiftUI struct Sidebar: View { var searchText: String var dataModel: ReadingListModel @ObservedObject var navigationModel: NavigationModel @State private var selectedBookIds: Set<Book.ID> = [] var body: some View { List(selection: $navigationModel.selectedCategory) { ForEach(dataModel.categories) { category in NavigationLink(value: category) { Label(category.title, systemImage: category.iconName) } } } .navigationTitle("Categories") .onChange(of: navigationModel.selectedBookIds) { bookIds in selectedBookIds = bookIds } .onChange(of: searchText) { navigationModel.selectedBookIds = $0.isEmpty ? selectedBookIds : [] } .onChange(of: navigationModel.selectedCategory) { _ in navigationModel.selectedBookIds = [] } #if os(macOS) .frame(minWidth: 200, idealWidth: 200) #endif } } struct Sidebar_Previews: PreviewProvider { static var previews: some View { let dataModel = ReadingListModel() let navigationModel = NavigationModel() return Group { Sidebar( searchText: "", dataModel: dataModel, navigationModel: navigationModel) Sidebar( searchText: "Jane", dataModel: dataModel, navigationModel: navigationModel) Sidebar( searchText: "", dataModel: dataModel, navigationModel: navigationModel) .environment(\.locale, .italian) Sidebar( searchText: "Jane", dataModel: dataModel, navigationModel: navigationModel) .environment(\.locale, .italian) } } } ``` ## StackedProgressView.swift ```swift /* Abstract: A vertically stacked progress view that displays its percentage at the bottom edge. */ import SwiftUI struct StackedProgressView: View { var value: Double var body: some View { ProgressView(value: value) .progressViewStyle(StackedProgressViewStyle()) .frame(width: 100) } } private struct StackedProgressViewStyle: ProgressViewStyle { func makeBody(configuration: Configuration) -> some View { let value = configuration.fractionCompleted ?? 0 return VStack { ZStack(alignment: .leading) { Capsule(style: .continuous) .foregroundStyle(.tertiary) .overlay { GeometryReader { proxy in Capsule(style: .continuous) .frame(width: proxy.size.width * value) .foregroundStyle(foregroundStyle(for: value)) } } } .frame(height: 4) Text(Int(value * 100), format: .percent) } func foregroundStyle(for value: Double) -> some ShapeStyle { if value == 1 { return AnyShapeStyle(.green) } else { return AnyShapeStyle(.tint) } } } } struct StackedProgressView_Previews: PreviewProvider { static var previews: some View { StackedProgressView(value: 0.5) } } ``` ## UpdateReadingProgressButton.swift ```swift /* Abstract: A button to update the reading progress for a given book. */ import SwiftUI struct UpdateReadingProgressButton: View { @ObservedObject var currentlyReading: CurrentlyReading @State private var progressEditor = ProgressEditorModel() init(book currentlyReading: CurrentlyReading) { self.currentlyReading = currentlyReading } var body: some View { Button { progressEditor.togglePresentation(for: currentlyReading) } label: { Label("Update Progress", systemImage: "bookmark") } .help("Update your reading progress for the book.") .disabled(currentlyReading.isFinished) .progressEditorModal(book: currentlyReading, model: $progressEditor) } } struct UpdateReadingProgressButton_Previews: PreviewProvider { static var previews: some View { Group { ForEach(ProgressEditorModel.mocks, id: \.self) { editor in UpdateReadingProgressButton(book: .mock) } } } } ``` ## Category.swift ```swift /* Abstract: An enumeration of recipe groupings used to display sidebar items. */ import SwiftUI enum Category: Int, Hashable, CaseIterable, Identifiable, Codable { case dessert case pancake case salad case sandwich var id: Int { rawValue } var localizedName: LocalizedStringKey { switch self { case .dessert: return "Dessert" case .pancake: return "Pancake" case .salad: return "Salad" case .sandwich: return "Sandwich" } } } ``` ## DataModel.swift ```swift /* Abstract: An observable data model of published recipes and miscellaneous groupings. */ import SwiftUI import Combine class DataModel: ObservableObject { @Published var recipes: [Recipe] = [] private var recipesById: [Recipe.ID: Recipe]? = nil private var cancellables: [AnyCancellable] = [] static let shared: DataModel = DataModel() private init() { recipes = builtInRecipes $recipes .sink { [weak self] _ in self?.recipesById = nil } .store(in: &cancellables) } func recipes(in category: Category?) -> [Recipe] { recipes .filter { $0.category == category } .sorted { $0.name < $1.name } } func recipes(relatedTo recipe: Recipe) -> [Recipe] { recipes .filter { recipe.related.contains($0.id) } .sorted { $0.name < $1.name } } subscript(recipeId: Recipe.ID) -> Recipe? { if recipesById == nil { recipesById = Dictionary( uniqueKeysWithValues: recipes.map { ($0.id, $0) }) } return recipesById![recipeId] } var recipeOfTheDay: Recipe { recipes.first! } } private let builtInRecipes: [Recipe] = { var recipes = [ "Apple Pie": Recipe( name: "Apple Pie", category: .dessert, ingredients: applePie.ingredients), "Baklava": Recipe( name: "Baklava", category: .dessert, ingredients: []), "Bolo de Rolo": Recipe( name: "Bolo de Rolo", category: .dessert, ingredients: []), "Chocolate Crackles": Recipe( name: "Chocolate Crackles", category: .dessert, ingredients: []), "Cr�me Br�l�e": Recipe( name: "Cr�me Br�l�e", category: .dessert, ingredients: []), "Fruit Pie Filling": Recipe( name: "Fruit Pie Filling", category: .dessert, ingredients: []), "Kanom Thong Ek": Recipe( name: "Kanom Thong Ek", category: .dessert, ingredients: []), "Mochi": Recipe( name: "Mochi", category: .dessert, ingredients: []), "Marzipan": Recipe( name: "Marzipan", category: .dessert, ingredients: []), "Pie Crust": Recipe( name: "Pie Crust", category: .dessert, ingredients: pieCrust.ingredients), "Shortbread Biscuits": Recipe( name: "Shortbread Biscuits", category: .dessert, ingredients: []), "Tiramisu": Recipe( name: "Tiramisu", category: .dessert, ingredients: []), "Cr�pe": Recipe( name: "Cr�pe", category: .pancake, ingredients: []), "Jianbing": Recipe( name: "Jianbing", category: .pancake, ingredients: []), "American": Recipe( name: "American", category: .pancake, ingredients: []), "Dosa": Recipe( name: "Dosa", category: .pancake, ingredients: []), "Injera": Recipe( name: "Injera", category: .pancake, ingredients: []), "Acar": Recipe( name: "Acar", category: .salad, ingredients: []), "Ambrosia": Recipe( name: "Ambrosia", category: .salad, ingredients: []), "Bok L'hong": Recipe( name: "Bok L'hong", category: .salad, ingredients: []), "Caprese": Recipe( name: "Caprese", category: .salad, ingredients: []), "Ceviche": Recipe( name: "Ceviche", category: .salad, ingredients: []), "�oban Salatas�": Recipe( name: "�oban Salatas�", category: .salad, ingredients: []), "Fiambre": Recipe( name: "Fiambre", category: .salad, ingredients: []), "Kachumbari": Recipe( name: "Kachumbari", category: .salad, ingredients: []), "Ni�oise": Recipe( name: "Ni�oise", category: .salad, ingredients: []) ] recipes["Apple Pie"]!.related = [ recipes["Pie Crust"]!.id, recipes["Fruit Pie Filling"]!.id ] recipes["Pie Crust"]!.related = [recipes["Fruit Pie Filling"]!.id] recipes["Fruit Pie Filling"]!.related = [recipes["Pie Crust"]!.id] return Array(recipes.values) }() let applePie = """ 3�4 cup white sugar 2 Tbsp. all-purpose flour 1�2 tsp. ground cinnamon 1�4 tsp. ground nutmeg 1�2 tsp. lemon zest 7 cups thinly sliced apples 2 tsp. lemon juice 1 Tbsp. butter 1 recipe pastry for a 9-inch double-crust pie 4 Tbsp. milk """ let pieCrust = """ 2 1�2 cups all-purpose flour 1 Tbsp. powdered sugar 1 tsp. sea salt 1�2 cup shortening 1�2 cup butter (cold, cut into small pieces) ? cup cold water (plus more as needed) """ extension String { var ingredients: [Ingredient] { split(separator: "\n", omittingEmptySubsequences: true) .map { Ingredient(description: String($0)) } } } ``` ## Experience.swift ```swift /* Abstract: An enumeration of navigation experiences used to define the app architecture. */ import SwiftUI enum Experience: Int, Identifiable, CaseIterable, Codable { var id: Int { rawValue } case stack case twoColumn case threeColumn case challenge var imageName: String { switch self { case .stack: return "list.bullet.rectangle.portrait" case .twoColumn: return "sidebar.left" case .threeColumn: return "rectangle.split.3x1" case .challenge: return "hands.sparkles" } } var localizedName: LocalizedStringKey { switch self { case .stack: return "Stack" case .twoColumn: return "Two columns" case .threeColumn: return "Three columns" case .challenge: return "WWDC22 Challenge" } } var localizedDescription: LocalizedStringKey { switch self { case .stack: return "Presents a stack of views over a root view." case .twoColumn: return "Presents views in two columns: sidebar and detail." case .threeColumn: return "Presents views in three columns: sidebar, content, and detail." case .challenge: return "A coding challenge to explore the new navigation architectures." } } } ``` ## Ingredient.swift ```swift /* Abstract: A data model for an ingredient for a given recipe. */ import SwiftUI struct Ingredient: Hashable, Identifiable { let id = UUID() var description: String } ``` ## NavigationModel.swift ```swift /* Abstract: A navigation model used to persist and restore the navigation state. */ import SwiftUI import Combine final class NavigationModel: ObservableObject, Codable { @Published var selectedCategory: Category? @Published var recipePath: [Recipe] @Published var columnVisibility: NavigationSplitViewVisibility private lazy var decoder = JSONDecoder() private lazy var encoder = JSONEncoder() init(columnVisibility: NavigationSplitViewVisibility = .automatic, selectedCategory: Category? = nil, recipePath: [Recipe] = [] ) { self.columnVisibility = columnVisibility self.selectedCategory = selectedCategory self.recipePath = recipePath } var selectedRecipe: Recipe? { get { recipePath.first } set { recipePath = [newValue].compactMap { $0 } } } var jsonData: Data? { get { try? encoder.encode(self) } set { guard let data = newValue, let model = try? decoder.decode(Self.self, from: data) else { return } selectedCategory = model.selectedCategory recipePath = model.recipePath columnVisibility = model.columnVisibility } } var objectWillChangeSequence: AsyncPublisher<Publishers.Buffer<ObservableObjectPublisher>> { objectWillChange .buffer(size: 1, prefetch: .byRequest, whenFull: .dropOldest) .values } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.selectedCategory = try container.decodeIfPresent( Category.self, forKey: .selectedCategory) let recipePathIds = try container.decode( [Recipe.ID].self, forKey: .recipePathIds) self.recipePath = recipePathIds.compactMap { DataModel.shared[$0] } self.columnVisibility = try container.decode( NavigationSplitViewVisibility.self, forKey: .columnVisibility) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(selectedCategory, forKey: .selectedCategory) try container.encode(recipePath.map(\.id), forKey: .recipePathIds) try container.encode(columnVisibility, forKey: .columnVisibility) } enum CodingKeys: String, CodingKey { case selectedCategory case recipePathIds case columnVisibility } } ``` ## Recipe.swift ```swift /* Abstract: A data model for a recipe and its metadata, including its related recipes. */ import SwiftUI struct Recipe: Hashable, Identifiable { let id = UUID() var name: String var category: Category var ingredients: [Ingredient] var related: [Recipe.ID] = [] var imageName: String? = nil } extension Recipe { static var mock: Recipe { DataModel.shared.recipeOfTheDay } } ``` ## NavigationCookbookApp.swift ```swift /* Abstract: The main app, which creates a scene that contains a window group, displaying the root content view. */ import SwiftUI @main struct NavigationCookbookApp: App { var body: some Scene { WindowGroup { ContentView() #if os(macOS) .frame(minWidth: 800, minHeight: 600) #endif } #if os(macOS) .commands { SidebarCommands() } #endif } } ``` ## ChallengeContentView.swift ```swift /* Abstract: The content view for the WWDC22 challenge. */ import SwiftUI struct ChallengeContentView: View { @Binding var showExperiencePicker: Bool @EnvironmentObject private var navigationModel: NavigationModel var dataModel = DataModel.shared var body: some View { VStack { Text("Put your navigation experience here") ExperienceButton(isActive: $showExperiencePicker) } } } struct ChallengeContentView_Previews: PreviewProvider { static var previews: some View { ChallengeContentView(showExperiencePicker: .constant(false)) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view the app uses to present the navigation experience picker and change the app navigation architecture based on the user selection. */ import SwiftUI struct ContentView: View { @SceneStorage("experience") private var experience: Experience? @SceneStorage("navigation") private var navigationData: Data? @StateObject private var navigationModel = NavigationModel() @State private var showExperiencePicker = false var body: some View { Group { switch experience { case .stack?: StackContentView(showExperiencePicker: $showExperiencePicker) case .twoColumn?: TwoColumnContentView( showExperiencePicker: $showExperiencePicker) case .threeColumn?: ThreeColumnContentView( showExperiencePicker: $showExperiencePicker) case .challenge?: ChallengeContentView( showExperiencePicker: $showExperiencePicker) case nil: VStack { Text("??? Bon app�tit!") .font(.largeTitle) ExperienceButton(isActive: $showExperiencePicker) } .padding() .onAppear { showExperiencePicker = true } } } .environmentObject(navigationModel) .sheet(isPresented: $showExperiencePicker) { ExperiencePicker(experience: $experience) } .task { if let jsonData = navigationData { navigationModel.jsonData = jsonData } for await _ in navigationModel.objectWillChangeSequence { navigationData = navigationModel.jsonData } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ``` ## ContinueButton.swift ```swift /* Abstract: A confirmation button, custom styled for iOS. */ import SwiftUI struct ContinueButton: View { var action: () -> Void var body: some View { Button("Continue", action: action) #if os(macOS) .buttonStyle(.borderedProminent) #else .buttonStyle(ContinueButtonStyle()) #endif } } #if os(iOS) struct ContinueButtonStyle: ButtonStyle { @Environment(\.isEnabled) private var isEnabled @Environment(\.horizontalSizeClass) private var horizontalSizeClass func makeBody(configuration: Configuration) -> some View { configuration.label .fontWeight(.bold) .frame(maxWidth: horizontalSizeClass == .compact ? .infinity : 280) .foregroundStyle(.background) .padding() .background { RoundedRectangle(cornerRadius: 12, style: .continuous) .fill(isEnabled ? Color.accentColor : .gray.opacity(0.6)) .opacity(configuration.isPressed ? 0.8 : 1) .scaleEffect(configuration.isPressed ? 0.98 : 1) .animation(.easeInOut, value: configuration.isPressed) } } } #endif struct ContinueButton_Previews: PreviewProvider { static var previews: some View { ContinueButton { } } } ``` ## ExperienceButton.swift ```swift /* Abstract: An button that presents the navigation experience picker when its action is invoked. */ import SwiftUI struct ExperienceButton: View { @Binding var isActive: Bool var body: some View { Button { isActive = true } label: { Label("Experience", systemImage: "wand.and.stars") .help("Choose your navigation experience") } } } struct ExperienceButton_Previews: PreviewProvider { static var previews: some View { ExperienceButton(isActive: .constant(false)) } } ``` ## ExperiencePicker.swift ```swift /* Abstract: A navigation experience picker used to select the navigation architecture for the app. */ import SwiftUI struct ExperiencePicker: View { @Binding var experience: Experience? @Environment(\.dismiss) private var dismiss @State private var selection: Experience? var body: some View { NavigationStack { VStack { Spacer() Text("Choose your navigation experience") .font(.largeTitle) .fontWeight(.bold) .lineLimit(2, reservesSpace: true) .multilineTextAlignment(.center) .minimumScaleFactor(0.8) .padding() Spacer() LazyVGrid(columns: columns) { ForEach(Experience.allCases) { experience in ExperiencePickerItem( selection: $selection, experience: experience) } } Spacer() } .scenePadding() #if os(iOS) .safeAreaInset(edge: .bottom) { ContinueButton(action: continueAction) .disabled(selection == nil) .scenePadding() } #endif } #if os(macOS) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { ContinueButton(action: continueAction) .disabled(selection == nil) } } .frame(width: 600, height: 350) #endif .interactiveDismissDisabled(selection == nil) } var columns: [GridItem] { [ GridItem(.adaptive(minimum: 250)) ] } func continueAction() { experience = selection dismiss() } } struct ExperiencePicker_Previews: PreviewProvider { static var previews: some View { ForEach(Experience.allCases + [nil], id: \.self) { ExperiencePicker(experience: .constant($0)) } } } ``` ## ExperiencePickerRow.swift ```swift /* Abstract: A navigation experience picker row that displays the icon, name, and description for each experience. */ import SwiftUI struct ExperiencePickerItem: View { @Binding var selection: Experience? var experience: Experience var body: some View { Button { selection = experience } label: { Label(selection: $selection, experience: experience) } .buttonStyle(.plain) } } private struct Label: View { @Binding var selection: Experience? var experience: Experience @State private var isHovering = false var body: some View { HStack(spacing: 20) { Image(systemName: experience.imageName) .font(.title) .foregroundStyle(shapeStyle(Color.accentColor)) VStack(alignment: .leading) { Text(experience.localizedName) .bold() .foregroundStyle(shapeStyle(Color.primary)) Text(experience.localizedDescription) .font(.callout) .lineLimit(3, reservesSpace: true) .multilineTextAlignment(.leading) .foregroundStyle(shapeStyle(Color.secondary)) } } .shadow(radius: selection == experience ? 4 : 0) .padding() .background { RoundedRectangle(cornerRadius: 12, style: .continuous) .fill(selection == experience ? AnyShapeStyle(Color.accentColor) : AnyShapeStyle(BackgroundStyle())) RoundedRectangle(cornerRadius: 12, style: .continuous) .stroke(isHovering ? Color.accentColor : .clear) } .scaleEffect(isHovering ? 1.02 : 1) .onHover { isHovering in withAnimation { self.isHovering = isHovering } } } func shapeStyle<S: ShapeStyle>(_ style: S) -> some ShapeStyle { if selection == experience { return AnyShapeStyle(.background) } else { return AnyShapeStyle(style) } } } struct ExperiencePickerItem_Previews: PreviewProvider { static var previews: some View { ForEach(Experience.allCases) { ExperiencePickerItem(selection: .constant(nil), experience: $0) ExperiencePickerItem(selection: .constant($0), experience: $0) } } } ``` ## RecipeDetail.swift ```swift /* Abstract: A detail view the app uses to display the metadata for a given recipe, as well as its related recipes. */ import SwiftUI struct RecipeDetail<Link: View>: View { var recipe: Recipe? var relatedLink: (Recipe) -> Link var body: some View { // Workaround for a known issue where `NavigationSplitView` and // `NavigationStack` fail to update when their contents are conditional. // For more information, see the iOS 16 Release Notes and // macOS 13 Release Notes. (91311311)" ZStack { if let recipe = recipe { Content(recipe: recipe, relatedLink: relatedLink) } else { Text("Choose a recipe") .navigationTitle("") } } } } private struct Content<Link: View>: View { var recipe: Recipe var dataModel = DataModel.shared var relatedLink: (Recipe) -> Link var body: some View { ScrollView { ViewThatFits(in: .horizontal) { wideDetails narrowDetails } .padding() } .navigationTitle(recipe.name) } var wideDetails: some View { VStack(alignment: .leading) { title HStack(alignment: .top) { image ingredients Spacer() } relatedRecipes } } var narrowDetails: some View { let alignment: HorizontalAlignment #if os(macOS) alignment = .leading #else alignment = .center #endif return VStack(alignment: alignment) { title image ingredients relatedRecipes } } var title: some View { #if os(macOS) Text(recipe.name) .font(.largeTitle) #else EmptyView() #endif } var image: some View { RecipePhoto(recipe: recipe) .frame(width: 300, height: 300) } @ViewBuilder var ingredients: some View { let padding = EdgeInsets(top: 16, leading: 0, bottom: 8, trailing: 0) VStack(alignment: .leading) { Text("Ingredients") .font(.headline) .padding(padding) VStack(alignment: .leading) { ForEach(recipe.ingredients) { ingredient in Text(ingredient.description) } } } .frame(minWidth: 300, alignment: .leading) } @ViewBuilder var relatedRecipes: some View { let padding = EdgeInsets(top: 16, leading: 0, bottom: 8, trailing: 0) if !recipe.related.isEmpty { VStack(alignment: .leading) { Text("Related Recipes") .font(.headline) .padding(padding) LazyVGrid(columns: columns, alignment: .leading) { let relatedRecipes = dataModel.recipes(relatedTo: recipe) ForEach(relatedRecipes) { relatedRecipe in relatedLink(relatedRecipe) } } } } } var columns: [GridItem] { [ GridItem(.adaptive(minimum: 120, maximum: 120)) ] } } struct RecipeDetail_Previews: PreviewProvider { static var previews: some View { Group { RecipeDetail(recipe: nil, relatedLink: link) RecipeDetail(recipe: .mock, relatedLink: link) } } static func link(recipe: Recipe) -> some View { EmptyView() } } ``` ## RecipeGrid.swift ```swift /* Abstract: A grid of recipe tiles, based on a given recipe category. */ import SwiftUI struct RecipeGrid: View { var category: Category? var dataModel = DataModel.shared var body: some View { // Workaround for a known issue where `NavigationSplitView` and // `NavigationStack` fail to update when their contents are conditional. // For more information, see the iOS 16 Release Notes and // macOS 13 Release Notes. (91311311)" ZStack { if let category = category { ScrollView { LazyVGrid(columns: columns) { ForEach(dataModel.recipes(in: category)) { recipe in NavigationLink(value: recipe) { RecipeTile(recipe: recipe) } .buttonStyle(.plain) } } .padding() } .navigationTitle(category.localizedName) .navigationDestination(for: Recipe.self) { recipe in RecipeDetail(recipe: recipe) { relatedRecipe in NavigationLink(value: relatedRecipe) { RecipeTile(recipe: relatedRecipe) } .buttonStyle(.plain) } } } else { Text("Choose a category") .navigationTitle("") } } } var columns: [GridItem] { [ GridItem(.adaptive(minimum: 240)) ] } } struct RecipeGrid_Previews: PreviewProvider { static var previews: some View { ForEach(Category.allCases) { RecipeGrid(category: nil, dataModel: .shared) RecipeGrid(category: $0, dataModel: .shared) } } } ``` ## RecipePhoto.swift ```swift /* Abstract: A photo view for a given recipe, displaying the recipe's image or a placeholder. */ import SwiftUI struct RecipePhoto: View { var recipe: Recipe var body: some View { if let imageName = recipe.imageName { Image(imageName) .resizable() .aspectRatio(contentMode: .fit) } else { ZStack { Rectangle() .fill(.tertiary) Image(systemName: "camera") .font(.system(size: 64)) .foregroundStyle(.secondary) } } } } struct RecipePhoto_Previews: PreviewProvider { static var previews: some View { RecipePhoto(recipe: .mock) } } ``` ## RecipeTile.swift ```swift /* Abstract: A recipe tile, displaying the recipe's photo and name. */ import SwiftUI struct RecipeTile: View { var recipe: Recipe var body: some View { VStack { RecipePhoto(recipe: recipe) .aspectRatio(1, contentMode: .fill) .frame(maxWidth: 240, maxHeight: 240) Text(recipe.name) .lineLimit(2, reservesSpace: true) .font(.headline) } .tint(.primary) } } struct RecipeTile_Previews: PreviewProvider { static var previews: some View { RecipeTile(recipe: .mock) } } ``` ## StackContentView.swift ```swift /* Abstract: The content view for the navigation stack view experience. */ import SwiftUI struct StackContentView: View { @Binding var showExperiencePicker: Bool @EnvironmentObject private var navigationModel: NavigationModel var dataModel = DataModel.shared var body: some View { NavigationStack(path: $navigationModel.recipePath) { List(Category.allCases) { category in Section { ForEach(dataModel.recipes(in: category)) { recipe in NavigationLink(recipe.name, value: recipe) } } header: { Text(category.localizedName) } } .navigationTitle("Categories") .toolbar { ExperienceButton(isActive: $showExperiencePicker) } .navigationDestination(for: Recipe.self) { recipe in RecipeDetail(recipe: recipe) { relatedRecipe in NavigationLink(value: relatedRecipe) { RecipeTile(recipe: relatedRecipe) } .buttonStyle(.plain) } } } } func showRecipeOfTheDay() { navigationModel.recipePath = [dataModel.recipeOfTheDay] } func showCategories() { navigationModel.recipePath.removeAll() } } struct StackContentView_Previews: PreviewProvider { static var previews: some View { StackContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel()) StackContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel( selectedCategory: .dessert, recipePath: [.mock])) } } ``` ## ThreeColumnContentView.swift ```swift /* Abstract: The content view for the three-column navigation split view experience. */ import SwiftUI struct ThreeColumnContentView: View { @Binding var showExperiencePicker: Bool @EnvironmentObject private var navigationModel: NavigationModel var dataModel = DataModel.shared var categories = Category.allCases var body: some View { NavigationSplitView( columnVisibility: $navigationModel.columnVisibility ) { List( categories, selection: $navigationModel.selectedCategory ) { category in NavigationLink(category.localizedName, value: category) } .navigationTitle("Categories") } content: { // Workaround for a known issue where `NavigationSplitView` and // `NavigationStack` fail to update when their contents are conditional. // For more information, see the iOS 16 Release Notes and // macOS 13 Release Notes. (91311311)" ZStack { if let category = navigationModel.selectedCategory { List(selection: $navigationModel.selectedRecipe) { ForEach(dataModel.recipes(in: category)) { recipe in NavigationLink(recipe.name, value: recipe) } } .navigationTitle(category.localizedName) .onDisappear { if navigationModel.selectedRecipe == nil { navigationModel.selectedCategory = nil } } .toolbar { ExperienceButton(isActive: $showExperiencePicker) } } else { Text("Choose a category") .navigationTitle("") } } } detail: { RecipeDetail(recipe: navigationModel.selectedRecipe) { relatedRecipe in Button { navigationModel.selectedCategory = relatedRecipe.category navigationModel.selectedRecipe = relatedRecipe } label: { RecipeTile(recipe: relatedRecipe) } .buttonStyle(.plain) } } } func showRecipeOfTheDay() { let recipe = dataModel.recipeOfTheDay navigationModel.selectedCategory = recipe.category navigationModel.recipePath = [recipe] } } struct ThreeColumnContentView_Previews: PreviewProvider { static var previews: some View { Group { ThreeColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel(columnVisibility: .all)) ThreeColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel( columnVisibility: .all, selectedCategory: .dessert)) ThreeColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel( columnVisibility: .all, selectedCategory: .dessert, recipePath: [.mock])) } } } ``` ## TwoColumnContentView.swift ```swift /* Abstract: The content view for the two-column navigation split view experience. */ import SwiftUI struct TwoColumnContentView: View { @Binding var showExperiencePicker: Bool @EnvironmentObject private var navigationModel: NavigationModel var categories = Category.allCases var dataModel = DataModel.shared var body: some View { NavigationSplitView( columnVisibility: $navigationModel.columnVisibility ) { List( categories, selection: $navigationModel.selectedCategory ) { category in NavigationLink(category.localizedName, value: category) } .navigationTitle("Categories") .toolbar { ExperienceButton(isActive: $showExperiencePicker) } } detail: { NavigationStack(path: $navigationModel.recipePath) { RecipeGrid(category: navigationModel.selectedCategory) } } } } struct TwoColumnContentView_Previews: PreviewProvider { static var previews: some View { Group { TwoColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel(columnVisibility: .doubleColumn)) TwoColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel( columnVisibility: .doubleColumn, selectedCategory: .dessert)) TwoColumnContentView( showExperiencePicker: .constant(false), dataModel: .shared) .environmentObject(NavigationModel( columnVisibility: .doubleColumn, selectedCategory: .dessert, recipePath: [.mock])) } } } ``` ## Color.swift ```swift /* Abstract: This file defines two colors. */ import SwiftUI // Defines app colors. extension Color { static let brandDarkBlue = Color("dark blue") static let brandLightBlue = Color("light blue") } ``` ## UTType+WritingApp.swift ```swift /* Abstract: This file defines a type for this app's writing document. */ import UniformTypeIdentifiers // This app's document type. extension UTType { static var writingAppDocument: UTType { UTType(exportedAs: "com.example.writingAppDocument") } } ``` ## AccessoryView.swift ```swift /* Abstract: The view for the accessories. */ import SwiftUI struct AccessoryView: View { @Environment(\.horizontalSizeClass) private var horizontal @State private var size: CGSize = CGSize() var body: some View { ZStack { Image(.robot) .resizable() .offset(x: size.width / 2 - 450, y: size.height / 2 - 300) .scaledToFit() .frame(width: 200) .opacity(horizontal == .compact ? 0 : 1) Image(.plant) .resizable() .offset(x: size.width / 2 + 250, y: size.height / 2 - 250) .scaledToFit() .frame(width: 200) .opacity(horizontal == .compact ? 0 : 1) } .onGeometryChange(for: CGSize.self) { proxy in proxy.size } action: { proxySize in size = proxySize } } } #Preview { AccessoryView() } ``` ## StorySheet.swift ```swift /* Abstract: The sheet view that appears when reading. */ import SwiftUI struct StorySheet: View { var story: String @Binding var isShowingSheet: Bool var body: some View { NavigationStack { VStack { #if os(macOS) HStack { Spacer() DismissButton(isShowingSheet: $isShowingSheet) .buttonStyle(.borderless) .padding() } #endif ScrollView { VStack { Text(story) .font(.system(.body, design: .serif, weight: .regular)) .foregroundStyle(Color.brandDarkBlue) } .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 50) } } #if os(iOS) .toolbar { ToolbarItem(placement: .topBarTrailing) { DismissButton(isShowingSheet: $isShowingSheet) } } .toolbarBackgroundVisibility(.hidden) .navigationBarBackButtonHidden() #endif .background(Color.brandLightBlue) } } } struct DismissButton: View { @Binding var isShowingSheet: Bool var body: some View { Button { isShowingSheet.toggle() } label: { Image(systemName: "xmark") .font(.system(size: 10, weight: .bold, design: .rounded)) .frame(width: 20, height: 20) .foregroundColor(Color.brandLightBlue) .background(Color.brandDarkBlue) .cornerRadius(26) } } } #Preview { StorySheet(story: "", isShowingSheet: .constant(true)) } ``` ## StoryView.swift ```swift /* Abstract: The primary entry point for the app's user interface. */ import SwiftUI struct StoryView: View { @Binding var document: WritingAppDocument @State private var isShowingSheet = false @FocusState private var isFocused: Bool var body: some View { VStack { TextEditor(text: $document.story) .font(.title) .textEditorStyle(.plain) .scrollIndicators(.never) .onAppear { self.isFocused = true } .focused($isFocused) } .padding(.horizontal, 30) .padding(.vertical, 20) .background(.background) .scrollClipDisabled() .clipShape(RoundedRectangle(cornerRadius: 13)) .shadow(color: .black.opacity(0.2), radius: 5) #if os(macOS) .padding(.horizontal, 30) #else .frame(maxWidth: 700) #endif .frame(maxWidth: .infinity) .padding() .background { Image(.pinkJungle) .resizable() .ignoresSafeArea() .frame(maxWidth: .infinity) } .toolbar { ToolbarItem() { Button("Show Story", systemImage: "book") { isShowingSheet.toggle() } .sheet(isPresented: $isShowingSheet) { StorySheet(story: document.story, isShowingSheet: $isShowingSheet) .presentationSizing(.page) } } } } } #Preview { StoryView(document: .constant(WritingAppDocument())) } ``` ## WritingApp.swift ```swift /* Abstract: The main entry point into this app. */ import SwiftUI // - Tag : AppBody @main struct WritingApp: App { var body: some Scene { #if os(iOS) DocumentGroupLaunchScene("Writing App") { NewDocumentButton("Start Writing") } background: { Image(.pinkJungle) .resizable() .scaledToFill() .ignoresSafeArea() } overlayAccessoryView: { _ in AccessoryView() } #endif DocumentGroup(newDocument: WritingAppDocument()) { file in StoryView(document: file.$document) } } } ``` ## WritingAppDocument.swift ```swift /* Abstract: The document type. */ import SwiftUI import UniformTypeIdentifiers struct WritingAppDocument: FileDocument { // Define the document type this app loads. // - Tag: ContentType static var readableContentTypes: [UTType] { [.writingAppDocument] } var story: String init(text: String = "") { self.story = text } // Load a file's contents into the document. // - Tag: DocumentInit init(configuration: ReadConfiguration) throws { guard let data = configuration.file.regularFileContents, let string = String(data: data, encoding: .utf8) else { throw CocoaError(.fileReadCorruptFile) } story = string } // Saves the document's data to a file. // - Tag: FileWrapper func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { let data = Data(story.utf8) return .init(regularFileWithContents: data) } } ``` ## GardenApp.swift ```swift /* Abstract: The main application code for this sample. */ import SwiftUI @main struct GardenApp: App { @StateObject private var store = Store() var body: some Scene { WindowGroup { ContentView() .environmentObject(store) } .commands { SidebarCommands() PlantCommands() } } } ``` ## PlantCommands.swift ```swift /* Abstract: The plant commands. */ import SwiftUI struct PlantCommands: Commands { @FocusedBinding(\.garden) private var garden: Garden? @FocusedBinding(\.selection) private var selection: Set<Plant.ID>? var body: some Commands { CommandGroup(before: .newItem) { AddPlantButton(garden: $garden) } CommandMenu("Plants") { WaterPlantsButton(garden: $garden, plants: $selection) } } } ``` ## Garden.swift ```swift /* Abstract: The data model describing the Garden. */ import Foundation struct Garden: Codable, Identifiable { var id: String var year: Int var name: String var plants: [Plant] var numberOfPlantsNeedingWater: Int { plants.reduce(0) { count, plant in count + (plant.needsWater ? 1 : 0) } } mutating func water(_ plantsToWater: Set<Plant.ID>) { for (index, plant) in plants.enumerated() { if plantsToWater.contains(plant.id) { plants[index].lastWateredOn = Date() } } } mutating func remove(_ plants: Set<Plant.ID>) { self.plants.removeAll(where: { plants.contains($0.id) }) } var displayYear: String { String(year) } subscript(plantId: Plant.ID?) -> Plant { get { if let id = plantId { return plants.first(where: { $0.id == id })! } return Plant() } set(newValue) { if let index = plants.firstIndex(where: { $0.id == newValue.id }) { plants[index] = newValue } } } } extension Garden { static var placeholder: Self { Garden(id: UUID().uuidString, year: 2021, name: "New Garden", plants: []) } } ``` ## Plant.swift ```swift /* Abstract: The data model describing the Plant. */ import Foundation struct Plant: Identifiable, Codable { var id: UUID var variety: String var plantingDepth: Float? var daysToMaturity: Int = 0 var datePlanted = Date() var favorite: Bool = false var lastWateredOn = Date() var wateringFrequency: Int? init( id: UUID, variety: String, plantingDepth: Float? = nil, daysToMaturity: Int = 0, datePlanted: Date = Date(), favorite: Bool = false, lastWateredOn: Date = Date(), wateringFrequency: Int? = 5 ) { self.id = id self.variety = variety self.plantingDepth = plantingDepth self.daysToMaturity = daysToMaturity self.datePlanted = datePlanted self.favorite = favorite self.lastWateredOn = lastWateredOn self.wateringFrequency = wateringFrequency } init() { self.init(id: UUID(), variety: "New Plant") } var harvestDate: Date { return datePlanted.addingTimeInterval(TimeInterval(daysToMaturity) * 24 * 60 * 60) } var needsWater: Bool { if let wateringFrequency = wateringFrequency { return lastWateredOn.timeIntervalSince(Date()) > TimeInterval(wateringFrequency) * 24 * 60 * 60 } else { return true } } } ``` ## Store.swift ```swift /* Abstract: The data store for this sample. */ import Foundation class Store: ObservableObject { @Published var gardens: [Garden] = [] @Published var selectedGarden: Garden.ID? @Published var mode: GardenDetail.ViewMode = .table private var applicationSupportDirectory: URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! } private var filename = "database.json" private var databaseFileUrl: URL { applicationSupportDirectory.appendingPathComponent(filename) } private func loadGardens(from storeFileData: Data) -> [Garden] { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return try decoder.decode([Garden].self, from: storeFileData) } catch { print(error) return [] } } init() { if let data = FileManager.default.contents(atPath: databaseFileUrl.path) { gardens = loadGardens(from: data) } else { if let bundledDatabaseUrl = Bundle.main.url(forResource: "database", withExtension: "json") { if let data = FileManager.default.contents(atPath: bundledDatabaseUrl.path) { gardens = loadGardens(from: data) } } else { gardens = [] } } } subscript(gardenID: Garden.ID?) -> Garden { get { if let id = gardenID { return gardens.first(where: { $0.id == id }) ?? .placeholder } return .placeholder } set(newValue) { if let id = gardenID { gardens[gardens.firstIndex(where: { $0.id == id })!] = newValue } } } func append(_ garden: Garden) { gardens.append(garden) } func save() { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = .prettyPrinted do { let data = try encoder.encode(gardens) if FileManager.default.fileExists(atPath: databaseFileUrl.path) { try FileManager.default.removeItem(at: databaseFileUrl) } try data.write(to: databaseFileUrl) } catch { //.. } } } extension Store { func gardens(in year: Int) -> [Garden] { gardens.filter({ $0.year == year }) } var currentYear: Int { 2021 } var previousYears: ClosedRange<Int> { (2018...2020) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view for this sample. */ import SwiftUI struct ContentView: View { @EnvironmentObject var store: Store @SceneStorage("selection") private var selectedGardenID: Garden.ID? var body: some View { NavigationView { Sidebar(selection: $selectedGardenID) GardenDetail(gardenId: $selectedGardenID) } } } struct ContentViewPreviews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(Store()) } } struct Sidebar: View { @EnvironmentObject var store: Store @SceneStorage("expansionState") var expansionState = ExpansionState() @Binding var selection: Garden.ID? var body: some View { List(selection: $selection) { DisclosureGroup(isExpanded: $expansionState[store.currentYear]) { ForEach(store.gardens(in: store.currentYear)) { garden in Label(garden.name, systemImage: "leaf") .badge(garden.numberOfPlantsNeedingWater) } } label: { Label("Current", systemImage: "chart.bar.doc.horizontal") } Section("History") { GardenHistoryOutline(range: store.previousYears, expansionState: $expansionState) } } .frame(minWidth: 250) } } ``` ## GardenDetail.swift ```swift /* Abstract: The detail view for each garden. */ import SwiftUI struct GardenDetail: View { enum ViewMode: String, CaseIterable, Identifiable { var id: Self { self } case table case gallery } @EnvironmentObject var store: Store @Binding var gardenId: Garden.ID? @State var searchText: String = "" @SceneStorage("viewMode") private var mode: ViewMode = .table @State private var selection = Set<Plant.ID>() @State var sortOrder: [KeyPathComparator<Plant>] = [ .init(\.variety, order: SortOrder.forward) ] var table: some View { Table(plants, selection: $selection, sortOrder: $sortOrder) { TableColumn("Variety", value: \.variety) TableColumn("Days to Maturity", value: \.daysToMaturity) { plant in Text(plant.daysToMaturity.formatted()) } TableColumn("Date Planted", value: \.datePlanted) { plant in Text(plant.datePlanted.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Harvest Date", value: \.harvestDate) { plant in Text(plant.harvestDate.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Last Watered", value: \.lastWateredOn) { plant in Text(plant.lastWateredOn.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Favorite", value: \.favorite, comparator: BoolComparator()) { plant in Toggle("Favorite", isOn: gardenBinding[plant.id].favorite) .labelsHidden() } .width(50) } } var body: some View { table .focusedSceneValue(\.garden, gardenBinding) .focusedSceneValue(\.selection, $selection) .searchable(text: $searchText) .toolbar { DisplayModePicker(mode: $mode) Button(action: addPlant) { Label("Add Plant", systemImage: "plus") } } .navigationTitle(garden.name) .navigationSubtitle("(garden.displayYear)") } } struct GardenDetailPreviews: PreviewProvider { static var store = Store() static var previews: some View { GardenDetail(gardenId: .constant(store.gardens(in: 2021).first!.id)) .environmentObject(store) .frame(width: 450) } } extension GardenDetail { var garden: Garden { store[gardenId] } var gardenBinding: Binding<Garden> { $store[gardenId] } func addPlant() { let plant = Plant() gardenBinding.wrappedValue.plants.append(plant) selection = Set([plant.id]) } var plants: [Plant] { return garden.plants .filter { searchText.isEmpty ? true : $0.variety.localizedCaseInsensitiveContains(searchText) } .sorted(using: sortOrder) } } private struct BoolComparator: SortComparator { typealias Compared = Bool func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult { switch (lhs, rhs) { case (true, false): return order == .forward ? .orderedDescending : .orderedAscending case (false, true): return order == .forward ? .orderedAscending : .orderedDescending default: return .orderedSame } } var order: SortOrder = .forward } ``` ## ExpansionState.swift ```swift /* Abstract: The expansion state for the side bar. */ import Foundation struct ExpansionState: RawRepresentable { var ids: Set<Int> let current = 2021 init?(rawValue: String) { ids = Set(rawValue.components(separatedBy: ",").compactMap(Int.init)) } init() { ids = [] } var rawValue: String { ids.map({ "($0)" }).joined(separator: ",") } var isEmpty: Bool { ids.isEmpty } func contains(_ id: Int) -> Bool { ids.contains(id) } mutating func insert(_ id: Int) { ids.insert(id) } mutating func remove(_ id: Int) { ids.remove(id) } subscript(year: Int) -> Bool { get { // Expand the current year by default ids.contains(year) ? true : year == current } set { if newValue { ids.insert(year) } else { ids.remove(year) } } } } ``` ## FocusedValues+Garden.swift ```swift /* Abstract: The focused value definitions. */ import SwiftUI extension FocusedValues { var garden: Binding<Garden>? { get { self[FocusedGardenKey.self] } set { self[FocusedGardenKey.self] = newValue } } var selection: Binding<Set<Plant.ID>>? { get { self[FocusedGardenSelectionKey.self] } set { self[FocusedGardenSelectionKey.self] = newValue } } private struct FocusedGardenKey: FocusedValueKey { typealias Value = Binding<Garden> } private struct FocusedGardenSelectionKey: FocusedValueKey { typealias Value = Binding<Set<Plant.ID>> } } ``` ## AddPlantButton.swift ```swift /* Abstract: The plant button view. */ import SwiftUI struct AddPlantButton: View { @Binding var garden: Garden? var body: some View { Button { garden?.plants.append(Plant()) } label: { Label("Add Plant", systemImage: "plus") } .keyboardShortcut("N", modifiers: [.command, .shift]) .disabled(garden == nil) } } ``` ## DisplayModePicker.swift ```swift /* Abstract: The garden display mode picker found in the toolbar. */ import SwiftUI struct DisplayModePicker: View { @Binding var mode: GardenDetail.ViewMode var body: some View { Picker("Display Mode", selection: $mode) { ForEach(GardenDetail.ViewMode.allCases) { viewMode in viewMode.label } } .pickerStyle(SegmentedPickerStyle()) } } extension GardenDetail.ViewMode { var labelContent: (name: String, systemImage: String) { switch self { case .table: return ("Table", "tablecells") case .gallery: return ("Gallery", "photo") } } var label: some View { let content = labelContent return Label(content.name, systemImage: content.systemImage) } } ``` ## GardenHistoryOutline.swift ```swift /* Abstract: The garden history outline view. */ import SwiftUI struct GardenHistoryOutline: View { @EnvironmentObject var store: Store var range: ClosedRange<Int> @Binding var expansionState: ExpansionState struct CurrentLabel: View { var body: some View { Label("Current", systemImage: "chart.bar.doc.horizontal") } } struct PastLabel: View { var year: Int var body: some View { Label(String(year), systemImage: "clock") } } var body: some View { ForEach(range.reversed(), id: \.self) { year in DisclosureGroup(isExpanded: $expansionState[year]) { ForEach(store.gardens(in: year)) { garden in SidebarLabel(garden: garden) } } label: { Group { if store.currentYear == year { CurrentLabel() } else { PastLabel(year: year) } } } } } } ``` ## SidebarLabel.swift ```swift /* Abstract: The side bar label view. */ import SwiftUI struct SidebarLabel: View { var garden: Garden var body: some View { Label(garden.name, systemImage: "leaf") } } ``` ## WaterPlantsButton.swift ```swift /* Abstract: The water plants button view. */ import SwiftUI struct WaterPlantsButton: View { @Binding var garden: Garden? @Binding var plants: Set<Plant.ID>? var body: some View { Button { if let plants = plants { garden?.water(plants) } } label: { Label("Water Plants", systemImage: "drop") } .keyboardShortcut("U", modifiers: [.command, .shift]) .disabled(garden == nil || plants!.isEmpty) } } ``` ## GardenApp.swift ```swift /* Abstract: The main application code for this sample. */ import SwiftUI @main struct GardenApp: App { @StateObject private var store = Store() var body: some Scene { WindowGroup { ContentView() .environmentObject(store) } } } ``` ## PlantCommands.swift ```swift /* Abstract: The plant commands. */ import SwiftUI struct PlantCommands: Commands { var body: some Commands { EmptyCommands() } } ``` ## Garden.swift ```swift /* Abstract: The data model describing the Garden. */ import Foundation struct Garden: Codable, Identifiable { var id: String var year: Int var name: String var plants: [Plant] var numberOfPlantsNeedingWater: Int { plants.reduce(0) { count, plant in count + (plant.needsWater ? 1 : 0) } } mutating func water(_ plantsToWater: Set<Plant.ID>) { for (index, plant) in plants.enumerated() { if plantsToWater.contains(plant.id) { plants[index].lastWateredOn = Date() } } } mutating func remove(_ plants: Set<Plant.ID>) { self.plants.removeAll(where: { plants.contains($0.id) }) } var displayYear: String { String(year) } subscript(plantId: Plant.ID?) -> Plant { get { if let id = plantId { return plants.first(where: { $0.id == id })! } return Plant() } set(newValue) { if let index = plants.firstIndex(where: { $0.id == newValue.id }) { plants[index] = newValue } } } } extension Garden { static var placeholder: Self { Garden(id: UUID().uuidString, year: 2021, name: "New Garden", plants: []) } } ``` ## Plant.swift ```swift /* Abstract: The data model describing the Plant. */ import Foundation struct Plant: Identifiable, Codable { var id: UUID var variety: String var plantingDepth: Float? var daysToMaturity: Int = 0 var datePlanted = Date() var favorite: Bool = false var lastWateredOn = Date() var wateringFrequency: Int? init( id: UUID, variety: String, plantingDepth: Float? = nil, daysToMaturity: Int = 0, datePlanted: Date = Date(), favorite: Bool = false, lastWateredOn: Date = Date(), wateringFrequency: Int? = 5 ) { self.id = id self.variety = variety self.plantingDepth = plantingDepth self.daysToMaturity = daysToMaturity self.datePlanted = datePlanted self.favorite = favorite self.lastWateredOn = lastWateredOn self.wateringFrequency = wateringFrequency } init() { self.init(id: UUID(), variety: "New Plant") } var harvestDate: Date { return datePlanted.addingTimeInterval(TimeInterval(daysToMaturity) * 24 * 60 * 60) } var needsWater: Bool { if let wateringFrequency = wateringFrequency { return lastWateredOn.timeIntervalSince(Date()) > TimeInterval(wateringFrequency) * 24 * 60 * 60 } else { return true } } } ``` ## Store.swift ```swift /* Abstract: The data store for this sample. */ import Foundation class Store: ObservableObject { @Published var gardens: [Garden] = [] @Published var selectedGarden: Garden.ID? @Published var mode: GardenDetail.ViewMode = .table private var applicationSupportDirectory: URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! } private var filename = "database.json" private var databaseFileUrl: URL { applicationSupportDirectory.appendingPathComponent(filename) } private func loadGardens(from storeFileData: Data) -> [Garden] { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return try decoder.decode([Garden].self, from: storeFileData) } catch { print(error) return [] } } init() { if let data = FileManager.default.contents(atPath: databaseFileUrl.path) { gardens = loadGardens(from: data) } else { if let bundledDatabaseUrl = Bundle.main.url(forResource: "database", withExtension: "json") { if let data = FileManager.default.contents(atPath: bundledDatabaseUrl.path) { gardens = loadGardens(from: data) } } else { gardens = [] } } } subscript(gardenID: Garden.ID?) -> Garden { get { if let id = gardenID { return gardens.first(where: { $0.id == id }) ?? .placeholder } return .placeholder } set(newValue) { if let id = gardenID { gardens[gardens.firstIndex(where: { $0.id == id })!] = newValue } } } func append(_ garden: Garden) { gardens.append(garden) } func save() { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = .prettyPrinted do { let data = try encoder.encode(gardens) if FileManager.default.fileExists(atPath: databaseFileUrl.path) { try FileManager.default.removeItem(at: databaseFileUrl) } try data.write(to: databaseFileUrl) } catch { //.. } } } extension Store { func gardens(in year: Int) -> [Garden] { gardens.filter({ $0.year == year }) } var currentYear: Int { 2021 } var previousYears: ClosedRange<Int> { (2018...2020) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view for this sample. */ import SwiftUI struct ContentView: View { var body: some View { Text("Hello World!") .padding() } } struct ContentViewPreviews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(Store()) } } ``` ## GardenDetail.swift ```swift /* Abstract: The detail view for each garden. */ import SwiftUI struct GardenDetail: View { enum ViewMode: String, CaseIterable, Identifiable { var id: Self { self } case table case gallery } @EnvironmentObject var store: Store @Binding var gardenId: Garden.ID? @State var searchText: String = "" @SceneStorage("viewMode") private var mode: ViewMode = .table @State private var selection = Set<Plant.ID>() @State var sortOrder: [KeyPathComparator<Plant>] = [ .init(\.variety, order: SortOrder.forward) ] var body: some View { Text("Plant Table") .navigationTitle(garden.name) .navigationSubtitle("(garden.displayYear)") } } struct GardenDetailPreviews: PreviewProvider { static var store = Store() static var previews: some View { GardenDetail(gardenId: .constant(store.gardens(in: 2021).first!.id)) .environmentObject(store) .frame(width: 450) } } extension GardenDetail { var garden: Garden { store[gardenId] } var gardenBinding: Binding<Garden> { $store[gardenId] } func addPlant() { let plant = Plant() gardenBinding.wrappedValue.plants.append(plant) selection = Set([plant.id]) } var plants: [Plant] { return garden.plants .filter { searchText.isEmpty ? true : $0.variety.localizedCaseInsensitiveContains(searchText) } .sorted(using: sortOrder) } } private struct BoolComparator: SortComparator { typealias Compared = Bool func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult { switch (lhs, rhs) { case (true, false): return order == .forward ? .orderedDescending : .orderedAscending case (false, true): return order == .forward ? .orderedAscending : .orderedDescending default: return .orderedSame } } var order: SortOrder = .forward } ``` ## ExpansionState.swift ```swift /* Abstract: The expantion state for the side bar. */ import Foundation struct ExpansionState: RawRepresentable { var ids: Set<Int> let current = 2021 init?(rawValue: String) { ids = Set(rawValue.components(separatedBy: ",").compactMap(Int.init)) } init() { ids = [] } var rawValue: String { ids.map({ "($0)" }).joined(separator: ",") } var isEmpty: Bool { ids.isEmpty } func contains(_ id: Int) -> Bool { ids.contains(id) } mutating func insert(_ id: Int) { ids.insert(id) } mutating func remove(_ id: Int) { ids.remove(id) } subscript(year: Int) -> Bool { get { // Expand the current year by default ids.contains(year) ? true : year == current } set { if newValue { ids.insert(year) } else { ids.remove(year) } } } } ``` ## FocusedValues+Garden.swift ```swift /* Abstract: The focused value definitions. */ import SwiftUI extension FocusedValues { var garden: Binding<Garden>? { get { self[FocusedGardenKey.self] } set { self[FocusedGardenKey.self] = newValue } } var selection: Binding<Set<Plant.ID>>? { get { self[FocusedGardenSelectionKey.self] } set { self[FocusedGardenSelectionKey.self] = newValue } } private struct FocusedGardenKey: FocusedValueKey { typealias Value = Binding<Garden> } private struct FocusedGardenSelectionKey: FocusedValueKey { typealias Value = Binding<Set<Plant.ID>> } } ``` ## AddPlantButton.swift ```swift /* Abstract: The plant button view. */ import SwiftUI struct AddPlantButton: View { @Binding var garden: Garden? var body: some View { Button { garden?.plants.append(Plant()) } label: { Label("Add Plant", systemImage: "plus") } .keyboardShortcut("N", modifiers: [.command, .shift]) .disabled(garden == nil) } } ``` ## DisplayModePicker.swift ```swift /* Abstract: The garden display mode picker found in the toolbar. */ import SwiftUI struct DisplayModePicker: View { @Binding var mode: GardenDetail.ViewMode var body: some View { Picker("Display Mode", selection: $mode) { ForEach(GardenDetail.ViewMode.allCases) { viewMode in viewMode.label } } .pickerStyle(SegmentedPickerStyle()) } } extension GardenDetail.ViewMode { var labelContent: (name: String, systemImage: String) { switch self { case .table: return ("Table", "tablecells") case .gallery: return ("Gallery", "photo") } } var label: some View { let content = labelContent return Label(content.name, systemImage: content.systemImage) } } ``` ## GardenHistoryOutline.swift ```swift /* Abstract: The garden history outline view. */ import SwiftUI struct GardenHistoryOutline: View { @EnvironmentObject var store: Store var range: ClosedRange<Int> @Binding var expansionState: ExpansionState struct CurrentLabel: View { var body: some View { Label("Current", systemImage: "chart.bar.doc.horizontal") } } struct PastLabel: View { var year: Int var body: some View { Label(String(year), systemImage: "clock") } } var body: some View { ForEach(range.reversed(), id: \.self) { year in DisclosureGroup(isExpanded: $expansionState[year]) { ForEach(store.gardens(in: year)) { garden in SidebarLabel(garden: garden) } } label: { Group { if store.currentYear == year { CurrentLabel() } else { PastLabel(year: year) } } } } } } ``` ## SidebarLabel.swift ```swift /* Abstract: The side bar label view. */ import SwiftUI struct SidebarLabel: View { var garden: Garden var body: some View { Label(garden.name, systemImage: "leaf") } } ``` ## TableColumns.swift ```swift /* Abstract: The table colum views. */ /** TABLE COLUMNS TableColumn("Date Planted", value: \.datePlanted) { plant in Text(plant.datePlanted.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Harvest Date", value: \.harvestDate) { plant in Text(plant.harvestDate.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Last Watered", value: \.lastWateredOn) { plant in Text(plant.lastWateredOn.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Favorite", value: \.favorite, comparator: BoolComparator()) { plant in Toggle("Favorite", isOn: gardenBinding[plant.id].favorite) .labelsHidden() } .width(50) */ ``` ## WaterPlantsButton.swift ```swift /* Abstract: The water plants button view. */ import SwiftUI struct WaterPlantsButton: View { @Binding var garden: Garden? @Binding var plants: Set<Plant.ID>? var body: some View { Button { if let plants = plants { garden?.water(plants) } } label: { Label("Water Plants", systemImage: "drop") } .keyboardShortcut("U", modifiers: [.command, .shift]) .disabled(garden == nil || plants!.isEmpty) } } ``` ## GardenApp.swift ```swift /* Abstract: The main application code for this sample. */ import SwiftUI @main struct GardenApp: App { @StateObject private var store = Store() var body: some Scene { WindowGroup { ContentView() .environmentObject(store) } .commands { SidebarCommands() PlantCommands() ImportExportCommands(store: store) ImportFromDevicesCommands() } Settings { SettingsView() .environmentObject(store) } } } ``` ## ImportExportCommands.swift ```swift /* Abstract: The import and export command group. */ import SwiftUI struct ImportExportCommands: Commands { var store: Store @State private var isShowingExportDialog = false var body: some Commands { CommandGroup(replacing: .importExport) { Section { Button("Export�") { isShowingExportDialog = true } .fileExporter( isPresented: $isShowingExportDialog, document: store, contentType: Store.readableContentTypes.first!) { result in } } } } } ``` ## PlantCommands.swift ```swift /* Abstract: The plant commands. */ import SwiftUI struct PlantCommands: Commands { @FocusedBinding(\.garden) private var garden: Garden? @FocusedBinding(\.selection) private var selection: Set<Plant.ID>? var body: some Commands { CommandGroup(before: .newItem) { AddPlantButton(garden: $garden) } CommandMenu("Plants") { WaterPlantsButton(garden: $garden, plants: $selection) } } } ``` ## Garden.swift ```swift /* Abstract: The data model describing the Garden. */ import Foundation struct Garden: Codable, Identifiable { var id: String var year: Int var name: String var plants: [Plant] var numberOfPlantsNeedingWater: Int { let result = plants.reduce(0) { count, plant in count + (plant.needsWater ? 1 : 0) } print("(name) has (result)") for plant in plants { print("- (plant)") } return result } mutating func water(_ plantsToWater: Set<Plant.ID>) { for (index, plant) in plants.enumerated() { if plantsToWater.contains(plant.id) { plants[index].lastWateredOn = Date() } } } mutating func remove(_ plants: Set<Plant.ID>) { self.plants.removeAll(where: { plants.contains($0.id) }) } var displayYear: String { String(year) } subscript(plantId: Plant.ID?) -> Plant { get { if let id = plantId { return plants.first(where: { $0.id == id })! } return Plant() } set(newValue) { if let index = plants.firstIndex(where: { $0.id == newValue.id }) { plants[index] = newValue } } } } extension Garden { static var placeholder: Self { Garden(id: UUID().uuidString, year: 2021, name: "New Garden", plants: []) } } ``` ## Plant+ImportImage.swift ```swift /* Abstract: The plant extension to support importing an image. */ import AppKit import Foundation import UniformTypeIdentifiers extension Plant { static var importImageTypes = NSImage.imageTypes.compactMap { UTType($0) } /// Extracts image data from the given item providers, and saves the image to disk. /// The specified closure will be called with the URL for the extracted image file if successful. /// /// Note: because this method uses `NSItemProvider.loadDataRepresentation(forTypeIdentifier:completionHandler:)` /// internally, it is currently not marked as `async`. static func importImageFromProviders(_ itemProviders: [NSItemProvider], completion: @escaping (URL?) -> Void) -> Bool { guard let provider = itemProviders.first else { return false } for type in importImageTypes { let typeIdentifier = type.identifier if provider.hasItemConformingToTypeIdentifier(typeIdentifier) { provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { (data, error) in guard let data = data, let directoryURL = imageDirectory() else { DispatchQueue.main.async { completion(nil) } return } do { try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) var imageURL = directoryURL.appendingPathComponent(UUID().uuidString) if let fileExtension = type.preferredFilenameExtension { imageURL.appendPathExtension(fileExtension) } try data.write(to: imageURL) DispatchQueue.main.async { completion(imageURL) } } catch { DispatchQueue.main.async { completion(nil) } } } return true } } return false } } private func imageDirectory() -> URL? { guard var result = FileManager.default.urls( for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil } result.appendPathComponent(Bundle.main.bundleIdentifier!, isDirectory: true) result.appendPathComponent("images", isDirectory: true) return result } ``` ## Plant+ItemProvider.swift ```swift /* Abstract: The plant extension to support drag and drop. */ import Foundation import UniformTypeIdentifiers extension Plant { static var draggableType = UTType(exportedAs: "com.example.apple-samplecode.GardenApp.plant") /// Extracts encoded plant data from the specified item providers. /// The specified closure will be called with the array of resulting`Plant` values. /// /// Note: because this method uses `NSItemProvider.loadDataRepresentation(forTypeIdentifier:completionHandler:)` /// internally, it is currently not marked as `async`. static func fromItemProviders(_ itemProviders: [NSItemProvider], completion: @escaping ([Plant]) -> Void) { let typeIdentifier = Self.draggableType.identifier let filteredProviders = itemProviders.filter { $0.hasItemConformingToTypeIdentifier(typeIdentifier) } let group = DispatchGroup() var result = [Int: Plant]() for (index, provider) in filteredProviders.enumerated() { group.enter() provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { (data, error) in defer { group.leave() } guard let data = data else { return } let decoder = JSONDecoder() guard let plant = try? decoder.decode(Plant.self, from: data) else { return } result[index] = plant } } group.notify(queue: .global(qos: .userInitiated)) { let plants = result.keys.sorted().compactMap { result[$0] } DispatchQueue.main.async { completion(plants) } } } var itemProvider: NSItemProvider { let provider = NSItemProvider() provider.registerDataRepresentation(forTypeIdentifier: Self.draggableType.identifier, visibility: .all) { let encoder = JSONEncoder() do { let data = try encoder.encode(self) $0(data, nil) } catch { $0(nil, error) } return nil } return provider } } ``` ## Plant.swift ```swift /* Abstract: The data model describing the Plant. */ import Foundation struct Plant: Identifiable, Codable { var id: UUID var variety: String var plantingDepth: Float? var daysToMaturity: Int = 0 var datePlanted = Date() var favorite: Bool = false var lastWateredOn = Date() var wateringFrequency: Int? var imageURL: URL? init( id: UUID, variety: String, plantingDepth: Float? = nil, daysToMaturity: Int = 0, datePlanted: Date = Date(), favorite: Bool = false, lastWateredOn: Date = Date(), wateringFrequency: Int? = 5 ) { self.id = id self.variety = variety self.plantingDepth = plantingDepth self.daysToMaturity = daysToMaturity self.datePlanted = datePlanted self.favorite = favorite self.lastWateredOn = lastWateredOn self.wateringFrequency = wateringFrequency } init() { self.init(id: UUID(), variety: "New Plant") } var harvestDate: Date { return datePlanted.addingTimeInterval(TimeInterval(daysToMaturity) * 24 * 60 * 60) } var needsWater: Bool { if let wateringFrequency = wateringFrequency { return lastWateredOn.timeIntervalSince(Date()) > TimeInterval(wateringFrequency) * 24 * 60 * 60 } else { return true } } } ``` ## Store+ReferenceFileDocument.swift ```swift /* Abstract: The store extension file support. */ import SwiftUI import UniformTypeIdentifiers extension Store: ReferenceFileDocument { typealias Snapshot = [Garden] static var readableContentTypes = [UTType.commaSeparatedText] convenience init(configuration: ReadConfiguration) throws { self.init() } func snapshot(contentType: UTType) throws -> Snapshot { gardens } func fileWrapper(snapshot: Snapshot, configuration: WriteConfiguration) throws -> FileWrapper { var exportedData = Data() if let header = Bundle.main.localizedString(forKey: "CSV Header", value: nil, table: nil).data(using: .utf8) { exportedData.append(header) exportedData.append(newline) } for garden in snapshot { for plant in garden.plants { garden.append(to: &exportedData) plant.append(to: &exportedData) exportedData.append(newline) } } return FileWrapper(regularFileWithContents: exportedData) } } extension Garden { fileprivate func append(to csvData: inout Data) { if let data = name.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: year as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } } } extension Plant { fileprivate func append(to csvData: inout Data) { if let data = variety.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: (plantingDepth ?? 0) as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: daysToMaturity as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = dateFormatter.string(from: datePlanted).data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = favorite.description.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = dateFormatter.string(from: lastWateredOn).data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: (wateringFrequency ?? 0) as NSNumber)?.data(using: .utf8) { csvData.append(data) } } } private let newline = "\n".data(using: .utf8)! private let comma = ",".data(using: .utf8)! private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .none formatter.hasThousandSeparators = false formatter.usesSignificantDigits = true return formatter }() private let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none return formatter }() ``` ## Store.swift ```swift /* Abstract: The data store for this sample. */ import Foundation final class Store: ObservableObject { @Published var gardens: [Garden] = [] @Published var selectedGarden: Garden.ID? @Published var mode: GardenDetail.ViewMode = .table private var applicationSupportDirectory: URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! } private var filename = "database.json" private var databaseFileUrl: URL { applicationSupportDirectory.appendingPathComponent(filename) } private func loadGardens(from storeFileData: Data) -> [Garden] { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return try decoder.decode([Garden].self, from: storeFileData) } catch { print(error) return [] } } init() { if let data = FileManager.default.contents(atPath: databaseFileUrl.path) { gardens = loadGardens(from: data) } else { if let bundledDatabaseUrl = Bundle.main.url(forResource: "database", withExtension: "json") { if let data = FileManager.default.contents(atPath: bundledDatabaseUrl.path) { gardens = loadGardens(from: data) } } else { gardens = [] } } } subscript(gardenID: Garden.ID?) -> Garden { get { if let id = gardenID { return gardens.first(where: { $0.id == id }) ?? .placeholder } return .placeholder } set(newValue) { if let id = gardenID { gardens[gardens.firstIndex(where: { $0.id == id })!] = newValue } } } func append(_ garden: Garden) { gardens.append(garden) } func save() { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = .prettyPrinted do { let data = try encoder.encode(gardens) if FileManager.default.fileExists(atPath: databaseFileUrl.path) { try FileManager.default.removeItem(at: databaseFileUrl) } try data.write(to: databaseFileUrl) } catch { //.. } } } extension Store { func gardens(in year: Int) -> [Garden] { gardens.filter({ $0.year == year }) } var currentYear: Int { 2021 } var previousYears: ClosedRange<Int> { (2018...2020) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view for this sample. */ import SwiftUI struct ContentView: View { @EnvironmentObject var store: Store @SceneStorage("selection") private var selectedGardenID: Garden.ID? @AppStorage("defaultGarden") private var defaultGardenID: Garden.ID? var body: some View { NavigationView { Sidebar(selection: selection) GardenDetail(garden: selectedGarden) } } private var selection: Binding<Garden.ID?> { Binding(get: { selectedGardenID ?? defaultGardenID }, set: { selectedGardenID = $0 }) } private var selectedGarden: Binding<Garden> { $store[selection.wrappedValue] } } ``` ## GardenDetail.swift ```swift /* Abstract: The detail view for each garden. */ import SwiftUI struct GardenDetail: View { enum ViewMode: String, CaseIterable, Identifiable { var id: Self { self } case table case gallery } @Binding var garden: Garden @State var searchText: String = "" @SceneStorage("viewMode") private var mode: ViewMode = .table @State private var selection = Set<Plant.ID>() @State var sortOrder: [KeyPathComparator<Plant>] = [ .init(\.variety, order: SortOrder.forward) ] var table: some View { Table(selection: $selection, sortOrder: $sortOrder) { TableColumn("Variety", value: \.variety) TableColumn("Days to Maturity", value: \.daysToMaturity) { plant in Text(plant.daysToMaturity.formatted()) } TableColumn("Date Planted", value: \.datePlanted) { plant in Text(plant.datePlanted.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Harvest Date", value: \.harvestDate) { plant in Text(plant.harvestDate.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Last Watered", value: \.lastWateredOn) { plant in Text(plant.lastWateredOn.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Favorite", value: \.favorite, comparator: BoolComparator()) { plant in Toggle("Favorite", isOn: $garden[plant.id].favorite) .labelsHidden() } .width(50) } rows: { ForEach(plants) { plant in TableRow(plant) .itemProvider { plant.itemProvider } } .onInsert(of: [Plant.draggableType]) { index, providers in Plant.fromItemProviders(providers) { plants in garden.plants.insert(contentsOf: plants, at: index) } } } } var body: some View { Group { switch mode { case .table: table case .gallery: PlantGallery(garden: $garden, selection: $selection) } } .focusedSceneValue(\.garden, $garden) .focusedSceneValue(\.selection, $selection) .searchable(text: $searchText) .toolbar { DisplayModePicker(mode: $mode) Button(action: addPlant) { Label("Add Plant", systemImage: "plus") } } .navigationTitle(garden.name) .navigationSubtitle("(garden.displayYear)") .importsItemProviders(selection.isEmpty ? [] : Plant.importImageTypes) { providers in Plant.importImageFromProviders(providers) { url in for plantID in selection { garden[plantID].imageURL = url } } } } } extension GardenDetail { func addPlant() { let plant = Plant() garden.plants.append(plant) selection = Set([plant.id]) } var plants: [Plant] { return garden.plants .filter { searchText.isEmpty ? true : $0.variety.localizedCaseInsensitiveContains(searchText) } .sorted(using: sortOrder) } } private struct BoolComparator: SortComparator { typealias Compared = Bool func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult { switch (lhs, rhs) { case (true, false): return order == .forward ? .orderedDescending : .orderedAscending case (false, true): return order == .forward ? .orderedAscending : .orderedDescending default: return .orderedSame } } var order: SortOrder = .forward } ``` ## Sidebar.swift ```swift /* Abstract: The sample's side bar view. */ import SwiftUI struct Sidebar: View { @EnvironmentObject var store: Store @SceneStorage("expansionState") var expansionState = ExpansionState() @Binding var selection: Garden.ID? var body: some View { List(selection: $selection) { DisclosureGroup(isExpanded: $expansionState[store.currentYear]) { ForEach(store.gardens(in: store.currentYear)) { garden in SidebarLabel(garden: garden) .badge(garden.numberOfPlantsNeedingWater) } } label: { Label("Current", systemImage: "chart.bar.doc.horizontal") } Section("History") { GardenHistoryOutline(range: store.previousYears, expansionState: $expansionState) } } .frame(minWidth: 250) } } ``` ## DateFormatStyle+Abbreviated.swift ```swift /* Abstract: The date formatting utilities. */ import Foundation extension Date.FormatStyle { static var abbreviatedDate: Self { .init(date: .abbreviated) } } ``` ## ExpansionState.swift ```swift /* Abstract: The expantion state for the side bar. */ import Foundation struct ExpansionState: RawRepresentable { var ids: Set<Int> let current = 2021 init?(rawValue: String) { ids = Set(rawValue.components(separatedBy: ",").compactMap(Int.init)) } init() { ids = [] } var rawValue: String { ids.map({ "($0)" }).joined(separator: ",") } var isEmpty: Bool { ids.isEmpty } func contains(_ id: Int) -> Bool { ids.contains(id) } mutating func insert(_ id: Int) { ids.insert(id) } mutating func remove(_ id: Int) { ids.remove(id) } subscript(year: Int) -> Bool { get { // Expand the current year by default ids.contains(year) ? true : year == current } set { if newValue { ids.insert(year) } else { ids.remove(year) } } } } ``` ## FocusedValues+Garden.swift ```swift /* Abstract: The focused value definitions. */ import SwiftUI extension FocusedValues { var garden: Binding<Garden>? { get { self[FocusedGardenKey.self] } set { self[FocusedGardenKey.self] = newValue } } var selection: Binding<Set<Plant.ID>>? { get { self[FocusedGardenSelectionKey.self] } set { self[FocusedGardenSelectionKey.self] = newValue } } private struct FocusedGardenKey: FocusedValueKey { typealias Value = Binding<Garden> } private struct FocusedGardenSelectionKey: FocusedValueKey { typealias Value = Binding<Set<Plant.ID>> } } ``` ## AddPlantButton.swift ```swift /* Abstract: The plant button view. */ import SwiftUI struct AddPlantButton: View { @Binding var garden: Garden? var body: some View { Button { garden?.plants.append(Plant()) } label: { Label("Add Plant", systemImage: "plus") } .keyboardShortcut("N", modifiers: [.command, .shift]) .disabled(garden == nil) } } ``` ## DisplayModePicker.swift ```swift /* Abstract: The garden display mode picker found in the toolbar. */ import SwiftUI struct DisplayModePicker: View { @Binding var mode: GardenDetail.ViewMode var body: some View { Picker("Display Mode", selection: $mode) { ForEach(GardenDetail.ViewMode.allCases) { viewMode in viewMode.label } } .pickerStyle(SegmentedPickerStyle()) } } extension GardenDetail.ViewMode { var labelContent: (name: String, systemImage: String) { switch self { case .table: return ("Table", "tablecells") case .gallery: return ("Gallery", "photo") } } var label: some View { let content = labelContent return Label(content.name, systemImage: content.systemImage) } } ``` ## GardenHistoryOutline.swift ```swift /* Abstract: The garden history outline view. */ import SwiftUI struct GardenHistoryOutline: View { @EnvironmentObject var store: Store var range: ClosedRange<Int> @Binding var expansionState: ExpansionState struct CurrentLabel: View { var body: some View { Label("Current", systemImage: "chart.bar.doc.horizontal") } } struct PastLabel: View { var year: Int var body: some View { Label(String(year), systemImage: "clock") } } var body: some View { ForEach(range.reversed(), id: \.self) { year in DisclosureGroup(isExpanded: $expansionState[year]) { ForEach(store.gardens(in: year)) { garden in SidebarLabel(garden: garden) } } label: { Group { if store.currentYear == year { CurrentLabel() } else { PastLabel(year: year) } } } } } } ``` ## PlantGallery.swift ```swift /* Abstract: The plant gallery view. */ import SwiftUI import Foundation struct PlantGallery: View { @State private var itemSize: CGFloat = 250 @Binding var garden: Garden @Binding var selection: Set<Plant.ID> var body: some View { ScrollView { LazyVGrid(columns: columns, spacing: 40) { ForEach(garden.plants) { GalleryItem(plant: $0, size: itemSize, selection: $selection) } } } .padding([.horizontal, .top]) .safeAreaInset(edge: .bottom, spacing: 0) { ItemSizeSlider(size: $itemSize) } .onTapGesture { selection = [] } } var columns: [GridItem] { [GridItem(.adaptive(minimum: itemSize, maximum: itemSize), spacing: 40)] } private struct GalleryItem: View { var plant: Plant var size: CGFloat @Binding var selection: Set<Plant.ID> var body: some View { VStack { GalleryImage(plant: plant, size: size) .background(selectionBackground) Text(verbatim: plant.variety) .font(.callout) } .frame(width: size) .onTapGesture { selection = [plant.id] } } var isSelected: Bool { selection.contains(plant.id) } @ViewBuilder var selectionBackground: some View { if isSelected { RoundedRectangle(cornerRadius: 8) .fill(.selection) } } } private struct GalleryImage: View { var plant: Plant var size: CGFloat var body: some View { AsyncImage(url: plant.imageURL) { image in image .resizable() .aspectRatio(contentMode: .fit) .background(background) .frame(width: size, height: size) } placeholder: { Image(systemName: "leaf") .symbolVariant(.fill) .font(.system(size: 40)) .foregroundColor(Color.green) .background(background) .frame(width: size, height: size) } } var background: some View { RoundedRectangle(cornerRadius: 8) .fill(.quaternary) .frame(width: size, height: size) } } private struct ItemSizeSlider: View { @Binding var size: CGFloat var body: some View { HStack { Spacer() Slider(value: $size, in: 100...500) .controlSize(.small) .frame(width: 100) .padding(.trailing) } .frame(maxWidth: .infinity) .background(.bar) } } } ``` ## SettingsView.swift ```swift /* Abstract: The settings view for this app's preferences window. */ import SwiftUI struct SettingsView: View { var body: some View { TabView { GeneralSettings() .tabItem { Label("General", systemImage: "gear") } ViewingSettings() .tabItem { Label("Viewing", systemImage: "eyeglasses") } } .frame(width: 400, height: 200, alignment: .top) } private struct GeneralSettings: View { @EnvironmentObject var store: Store @AppStorage("defaultGarden") private var selection: Garden.ID? var body: some View { Form { Picker("Default Garden", selection: $selection) { Text("None").tag(Garden.ID?.none) ForEach(store.gardens) { garden in Text("(garden.name), (garden.displayYear)") .tag(Garden.ID?.some(garden.id)) } } .fixedSize() .padding() } } } private struct ViewingSettings: View { var body: some View { Color.clear } } } ``` ## SidebarLabel.swift ```swift /* Abstract: The side bar label view. */ import SwiftUI struct SidebarLabel: View { var garden: Garden var body: some View { Label(garden.name, systemImage: "leaf") } } ``` ## WaterPlantsButton.swift ```swift /* Abstract: The water plants button view. */ import SwiftUI struct WaterPlantsButton: View { @Binding var garden: Garden? @Binding var plants: Set<Plant.ID>? var body: some View { Button { if let plants = plants { garden?.water(plants) } } label: { Label("Water Plants", systemImage: "drop") } .keyboardShortcut("U", modifiers: [.command, .shift]) .disabled(garden == nil || plants!.isEmpty) } } ``` ## GardenApp.swift ```swift /* Abstract: The main application code for this sample. */ import SwiftUI @main struct GardenApp: App { @StateObject private var store = Store() var body: some Scene { WindowGroup { ContentView() .environmentObject(store) } .commands { SidebarCommands() PlantCommands() } } } ``` ## ImportExportCommands.swift ```swift /* Abstract: The import and export command support. */ import SwiftUI struct ImportExportCommands: Commands { var store: Store var body: some Commands { EmptyCommands() } } ``` ## PlantCommands.swift ```swift /* Abstract: The plant commands. */ import SwiftUI struct PlantCommands: Commands { @FocusedBinding(\.garden) private var garden: Garden? @FocusedBinding(\.selection) private var selection: Set<Plant.ID>? var body: some Commands { CommandGroup(before: .newItem) { AddPlantButton(garden: $garden) } CommandMenu("Plants") { WaterPlantsButton(garden: $garden, plants: $selection) } } } ``` ## Garden.swift ```swift /* Abstract: The data model describing the Garden. */ import Foundation struct Garden: Codable, Identifiable { var id: String var year: Int var name: String var plants: [Plant] var numberOfPlantsNeedingWater: Int { plants.reduce(0) { count, plant in count + (plant.needsWater ? 1 : 0) } } mutating func water(_ plantsToWater: Set<Plant.ID>) { for (index, plant) in plants.enumerated() { if plantsToWater.contains(plant.id) { plants[index].lastWateredOn = Date() } } } mutating func remove(_ plants: Set<Plant.ID>) { self.plants.removeAll(where: { plants.contains($0.id) }) } var displayYear: String { String(year) } subscript(plantId: Plant.ID?) -> Plant { get { if let id = plantId { return plants.first(where: { $0.id == id })! } return Plant() } set(newValue) { if let index = plants.firstIndex(where: { $0.id == newValue.id }) { plants[index] = newValue } } } } extension Garden { static var placeholder: Self { Garden(id: UUID().uuidString, year: 2021, name: "New Garden", plants: []) } } ``` ## Plant+ImportImage.swift ```swift /* Abstract: The plant extension to support importing an image. */ import AppKit import Foundation import UniformTypeIdentifiers extension Plant { static var importImageTypes = NSImage.imageTypes.compactMap { UTType($0) } /// Extracts image data from the given item providers, and saves the image to disk. /// The specified closure will be called with the URL for the extracted image file if successful. /// /// Note: because this method uses `NSItemProvider.loadDataRepresentation(forTypeIdentifier:completionHandler:)` /// internally, it is currently not marked as `async`. static func importImageFromProviders(_ itemProviders: [NSItemProvider], completion: @escaping (URL?) -> Void) -> Bool { guard let provider = itemProviders.first else { return false } for type in importImageTypes { let typeIdentifier = type.identifier if provider.hasItemConformingToTypeIdentifier(typeIdentifier) { provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { (data, error) in guard let data = data, let directoryURL = imageDirectory() else { DispatchQueue.main.async { completion(nil) } return } do { try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) var imageURL = directoryURL.appendingPathComponent(UUID().uuidString) if let fileExtension = type.preferredFilenameExtension { imageURL.appendPathExtension(fileExtension) } try data.write(to: imageURL) DispatchQueue.main.async { completion(imageURL) } } catch { DispatchQueue.main.async { completion(nil) } } } return true } } return false } } private func imageDirectory() -> URL? { guard var result = FileManager.default.urls( for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil } result.appendPathComponent(Bundle.main.bundleIdentifier!, isDirectory: true) result.appendPathComponent("images", isDirectory: true) return result } ``` ## Plant+ItemProvider.swift ```swift /* Abstract: The extension to Plant to support drag and drop. */ import Foundation import UniformTypeIdentifiers extension Plant { static var draggableType = UTType(exportedAs: "com.example.apple-samplecode.GardenApp.plant") /// Extracts encoded plant data from the specified item providers. /// The specified closure will be called with the array of resulting`Plant` values. /// /// Note: because this method uses `NSItemProvider.loadDataRepresentation(forTypeIdentifier:completionHandler:)` /// internally, it is currently not marked as `async`. static func fromItemProviders(_ itemProviders: [NSItemProvider], completion: @escaping ([Plant]) -> Void) { let typeIdentifier = Self.draggableType.identifier let filteredProviders = itemProviders.filter { $0.hasItemConformingToTypeIdentifier(typeIdentifier) } let group = DispatchGroup() var result = [Int: Plant]() for (index, provider) in filteredProviders.enumerated() { group.enter() provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { (data, error) in defer { group.leave() } guard let data = data else { return } let decoder = JSONDecoder() guard let plant = try? decoder.decode(Plant.self, from: data) else { return } result[index] = plant } } group.notify(queue: .global(qos: .userInitiated)) { let plants = result.keys.sorted().compactMap { result[$0] } DispatchQueue.main.async { completion(plants) } } } var itemProvider: NSItemProvider { let provider = NSItemProvider() provider.registerDataRepresentation(forTypeIdentifier: Self.draggableType.identifier, visibility: .all) { let encoder = JSONEncoder() do { let data = try encoder.encode(self) $0(data, nil) } catch { $0(nil, error) } return nil } return provider } } ``` ## Plant.swift ```swift /* Abstract: The data model describing the Plant. */ import Foundation struct Plant: Identifiable, Codable { var id: UUID var variety: String var plantingDepth: Float? var daysToMaturity: Int = 0 var datePlanted = Date() var favorite: Bool = false var lastWateredOn = Date() var wateringFrequency: Int? var imageURL: URL? init( id: UUID, variety: String, plantingDepth: Float? = nil, daysToMaturity: Int = 0, datePlanted: Date = Date(), favorite: Bool = false, lastWateredOn: Date = Date(), wateringFrequency: Int? = 5 ) { self.id = id self.variety = variety self.plantingDepth = plantingDepth self.daysToMaturity = daysToMaturity self.datePlanted = datePlanted self.favorite = favorite self.lastWateredOn = lastWateredOn self.wateringFrequency = wateringFrequency } init() { self.init(id: UUID(), variety: "New Plant") } var harvestDate: Date { return datePlanted.addingTimeInterval(TimeInterval(daysToMaturity) * 24 * 60 * 60) } var needsWater: Bool { if let wateringFrequency = wateringFrequency { return lastWateredOn.timeIntervalSince(Date()) > TimeInterval(wateringFrequency) * 24 * 60 * 60 } else { return true } } } ``` ## Store+ReferenceFileDocument.swift ```swift /* Abstract: The various extensions to support file export. */ import SwiftUI import UniformTypeIdentifiers extension Store: ReferenceFileDocument { typealias Snapshot = [Garden] static var readableContentTypes = [UTType.commaSeparatedText] convenience init(configuration: ReadConfiguration) throws { self.init() } func snapshot(contentType: UTType) throws -> Snapshot { gardens } func fileWrapper(snapshot: Snapshot, configuration: WriteConfiguration) throws -> FileWrapper { var exportedData = Data() if let header = Bundle.main.localizedString(forKey: "CSV Header", value: nil, table: nil).data(using: .utf8) { exportedData.append(header) exportedData.append(newline) } for garden in snapshot { for plant in garden.plants { garden.append(to: &exportedData) plant.append(to: &exportedData) exportedData.append(newline) } } return FileWrapper(regularFileWithContents: exportedData) } } extension Garden { fileprivate func append(to csvData: inout Data) { if let data = name.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: year as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } } } extension Plant { fileprivate func append(to csvData: inout Data) { if let data = variety.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: (plantingDepth ?? 0) as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: daysToMaturity as NSNumber)?.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = dateFormatter.string(from: datePlanted).data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = favorite.description.data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = dateFormatter.string(from: lastWateredOn).data(using: .utf8) { csvData.append(data) csvData.append(comma) } else { csvData.append(comma) } if let data = numberFormatter.string(from: (wateringFrequency ?? 0) as NSNumber)?.data(using: .utf8) { csvData.append(data) } } } private let newline = "\n".data(using: .utf8)! private let comma = ",".data(using: .utf8)! private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .none formatter.hasThousandSeparators = false formatter.usesSignificantDigits = true return formatter }() private let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none return formatter }() ``` ## Store.swift ```swift /* Abstract: The data store for this sample. */ import Foundation final class Store: ObservableObject { @Published var gardens: [Garden] = [] @Published var selectedGarden: Garden.ID? @Published var mode: GardenDetail.ViewMode = .table private var applicationSupportDirectory: URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! } private var filename = "database.json" private var databaseFileUrl: URL { applicationSupportDirectory.appendingPathComponent(filename) } private func loadGardens(from storeFileData: Data) -> [Garden] { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return try decoder.decode([Garden].self, from: storeFileData) } catch { print(error) return [] } } init() { if let data = FileManager.default.contents(atPath: databaseFileUrl.path) { gardens = loadGardens(from: data) } else { if let bundledDatabaseUrl = Bundle.main.url(forResource: "database", withExtension: "json") { if let data = FileManager.default.contents(atPath: bundledDatabaseUrl.path) { gardens = loadGardens(from: data) } } else { gardens = [] } } } subscript(gardenID: Garden.ID?) -> Garden { get { if let id = gardenID { return gardens.first(where: { $0.id == id }) ?? .placeholder } return .placeholder } set(newValue) { if let id = gardenID { gardens[gardens.firstIndex(where: { $0.id == id })!] = newValue } } } func append(_ garden: Garden) { gardens.append(garden) } func save() { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = .prettyPrinted do { let data = try encoder.encode(gardens) if FileManager.default.fileExists(atPath: databaseFileUrl.path) { try FileManager.default.removeItem(at: databaseFileUrl) } try data.write(to: databaseFileUrl) } catch { //.. } } } extension Store { func gardens(in year: Int) -> [Garden] { gardens.filter({ $0.year == year }) } var currentYear: Int { 2021 } var previousYears: ClosedRange<Int> { (2018...2020) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view for this sample. */ import SwiftUI struct ContentView: View { @EnvironmentObject var store: Store @SceneStorage("selection") private var selectedGardenID: Garden.ID? var body: some View { NavigationView { Sidebar(selection: selection) GardenDetail(garden: selectedGarden) } } private var selection: Binding<Garden.ID?> { $selectedGardenID } private var selectedGarden: Binding<Garden> { $store[selection.wrappedValue] } } ``` ## GardenDetail.swift ```swift /* Abstract: The detail view for each garden. */ import SwiftUI struct GardenDetail: View { enum ViewMode: String, CaseIterable, Identifiable { var id: Self { self } case table case gallery } @EnvironmentObject var store: Store @Binding var garden: Garden @State var searchText: String = "" @SceneStorage("viewMode") private var mode: ViewMode = .table @State private var selection = Set<Plant.ID>() @State var sortOrder: [KeyPathComparator<Plant>] = [ .init(\.variety, order: SortOrder.forward) ] var table: some View { Table(plants, selection: $selection, sortOrder: $sortOrder) { TableColumn("Variety", value: \.variety) TableColumn("Days to Maturity", value: \.daysToMaturity) { plant in Text(plant.daysToMaturity.formatted()) } TableColumn("Date Planted", value: \.datePlanted) { plant in Text(plant.datePlanted.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Harvest Date", value: \.harvestDate) { plant in Text(plant.harvestDate.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Last Watered", value: \.lastWateredOn) { plant in Text(plant.lastWateredOn.formatted(date: .abbreviated, time: .omitted)) } TableColumn("Favorite", value: \.favorite, comparator: BoolComparator()) { plant in Toggle("Favorite", isOn: $garden[plant.id].favorite) .labelsHidden() } .width(50) } } var body: some View { Group { switch mode { case .table: table case .gallery: PlantGallery(garden: $garden, selection: $selection) } } .focusedSceneValue(\.garden, $garden) .focusedSceneValue(\.selection, $selection) .searchable(text: $searchText) .toolbar { DisplayModePicker(mode: $mode) Button(action: addPlant) { Label("Add Plant", systemImage: "plus") } } .navigationTitle(garden.name) .navigationSubtitle("(garden.displayYear)") } } extension GardenDetail { func addPlant() { let plant = Plant() garden.plants.append(plant) selection = Set([plant.id]) } var plants: [Plant] { return garden.plants .filter { searchText.isEmpty ? true : $0.variety.localizedCaseInsensitiveContains(searchText) } .sorted(using: sortOrder) } } private struct BoolComparator: SortComparator { typealias Compared = Bool func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult { switch (lhs, rhs) { case (true, false): return order == .forward ? .orderedDescending : .orderedAscending case (false, true): return order == .forward ? .orderedAscending : .orderedDescending default: return .orderedSame } } var order: SortOrder = .forward } ``` ## Sidebar.swift ```swift /* Abstract: The sample's side bar view. */ import SwiftUI struct Sidebar: View { @EnvironmentObject var store: Store @SceneStorage("expansionState") var expansionState = ExpansionState() @Binding var selection: Garden.ID? var body: some View { List(selection: $selection) { DisclosureGroup(isExpanded: $expansionState[store.currentYear]) { ForEach(store.gardens(in: store.currentYear)) { garden in SidebarLabel(garden: garden) .badge(garden.numberOfPlantsNeedingWater) } } label: { Label("Current", systemImage: "chart.bar.doc.horizontal") } Section("History") { GardenHistoryOutline(range: store.previousYears, expansionState: $expansionState) } } .frame(minWidth: 250) } } ``` ## ExpansionState.swift ```swift /* Abstract: The expansion state for the side bar. */ import Foundation struct ExpansionState: RawRepresentable { var ids: Set<Int> let current = 2021 init?(rawValue: String) { ids = Set(rawValue.components(separatedBy: ",").compactMap(Int.init)) } init() { ids = [] } var rawValue: String { ids.map({ "($0)" }).joined(separator: ",") } var isEmpty: Bool { ids.isEmpty } func contains(_ id: Int) -> Bool { ids.contains(id) } mutating func insert(_ id: Int) { ids.insert(id) } mutating func remove(_ id: Int) { ids.remove(id) } subscript(year: Int) -> Bool { get { // Expand the current year by default ids.contains(year) ? true : year == current } set { if newValue { ids.insert(year) } else { ids.remove(year) } } } } ``` ## FocusedValues+Garden.swift ```swift /* Abstract: The focused value definitions. */ import SwiftUI extension FocusedValues { var garden: Binding<Garden>? { get { self[FocusedGardenKey.self] } set { self[FocusedGardenKey.self] = newValue } } var selection: Binding<Set<Plant.ID>>? { get { self[FocusedGardenSelectionKey.self] } set { self[FocusedGardenSelectionKey.self] = newValue } } private struct FocusedGardenKey: FocusedValueKey { typealias Value = Binding<Garden> } private struct FocusedGardenSelectionKey: FocusedValueKey { typealias Value = Binding<Set<Plant.ID>> } } ``` ## AddPlantButton.swift ```swift /* Abstract: The plant button view. */ import SwiftUI struct AddPlantButton: View { @Binding var garden: Garden? var body: some View { Button { garden?.plants.append(Plant()) } label: { Label("Add Plant", systemImage: "plus") } .keyboardShortcut("N", modifiers: [.command, .shift]) .disabled(garden == nil) } } ``` ## DisplayModePicker.swift ```swift /* Abstract: The garden display mode picker found in the toolbar. */ import SwiftUI struct DisplayModePicker: View { @Binding var mode: GardenDetail.ViewMode var body: some View { Picker("Display Mode", selection: $mode) { ForEach(GardenDetail.ViewMode.allCases) { viewMode in viewMode.label } } .pickerStyle(SegmentedPickerStyle()) } } extension GardenDetail.ViewMode { var labelContent: (name: String, systemImage: String) { switch self { case .table: return ("Table", "tablecells") case .gallery: return ("Gallery", "photo") } } var label: some View { let content = labelContent return Label(content.name, systemImage: content.systemImage) } } ``` ## GardenHistoryOutline.swift ```swift /* Abstract: The garden history outline view. */ import SwiftUI struct GardenHistoryOutline: View { @EnvironmentObject var store: Store var range: ClosedRange<Int> @Binding var expansionState: ExpansionState struct CurrentLabel: View { var body: some View { Label("Current", systemImage: "chart.bar.doc.horizontal") } } struct PastLabel: View { var year: Int var body: some View { Label(String(year), systemImage: "clock") } } var body: some View { ForEach(range.reversed(), id: \.self) { year in DisclosureGroup(isExpanded: $expansionState[year]) { ForEach(store.gardens(in: year)) { garden in SidebarLabel(garden: garden) } } label: { Group { if store.currentYear == year { CurrentLabel() } else { PastLabel(year: year) } } } } } } ``` ## PlantGallery.swift ```swift /* Abstract: The plant gallery view. */ import SwiftUI import Foundation struct PlantGallery: View { @State private var itemSize: CGFloat = 250 @Binding var garden: Garden @Binding var selection: Set<Plant.ID> var body: some View { ScrollView { LazyVGrid(columns: columns, spacing: 40) { ForEach(garden.plants) { GalleryItem(plant: $0, size: itemSize, selection: $selection) } } } .padding([.horizontal, .top]) .safeAreaInset(edge: .bottom, spacing: 0) { ItemSizeSlider(size: $itemSize) } .onTapGesture { selection = [] } } var columns: [GridItem] { [GridItem(.adaptive(minimum: itemSize, maximum: itemSize), spacing: 40)] } private struct GalleryItem: View { var plant: Plant var size: CGFloat @Binding var selection: Set<Plant.ID> var body: some View { VStack { GalleryImage(plant: plant, size: size) .background(selectionBackground) Text(verbatim: plant.variety) .font(.callout) } .frame(width: size) .onTapGesture { selection = [plant.id] } } var isSelected: Bool { selection.contains(plant.id) } @ViewBuilder var selectionBackground: some View { if isSelected { RoundedRectangle(cornerRadius: 8) .fill(.selection) } } } private struct GalleryImage: View { var plant: Plant var size: CGFloat var body: some View { AsyncImage(url: plant.imageURL) { image in image .resizable() .aspectRatio(contentMode: .fit) .background(background) .frame(width: size, height: size) } placeholder: { Image(systemName: "leaf") .symbolVariant(.fill) .font(.system(size: 40)) .foregroundColor(Color.green) .background(background) .frame(width: size, height: size) } } var background: some View { RoundedRectangle(cornerRadius: 8) .fill(.quaternary) .frame(width: size, height: size) } } private struct ItemSizeSlider: View { @Binding var size: CGFloat var body: some View { HStack { Spacer() Slider(value: $size, in: 100...500) .controlSize(.small) .frame(width: 100) .padding(.trailing) } .frame(maxWidth: .infinity) .background(.bar) } } } ``` ## SettingsView.swift ```swift /* Abstract: The settings view for the app's preferences window. */ import SwiftUI struct SettingsView: View { var body: some View { Color.clear .frame(width: 400, height: 200, alignment: .top) } private struct GeneralSettings: View { @EnvironmentObject var store: Store var body: some View { Color.clear } } private struct ViewingSettings: View { var body: some View { Color.clear } } } ``` ## SidebarLabel.swift ```swift /* Abstract: The side bar label view. */ import SwiftUI struct SidebarLabel: View { var garden: Garden var body: some View { Label(garden.name, systemImage: "leaf") } } ``` ## WaterPlantsButton.swift ```swift /* Abstract: The water plants button view. */ import SwiftUI struct WaterPlantsButton: View { @Binding var garden: Garden? @Binding var plants: Set<Plant.ID>? var body: some View { Button { if let plants = plants { garden?.water(plants) } } label: { Label("Water Plants", systemImage: "drop") } .keyboardShortcut("U", modifiers: [.command, .shift]) .disabled(garden == nil || plants!.isEmpty) } } ``` ## AppDelegate.swift ```swift /* Abstract: The application delegate. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if let activity = options.userActivities.first, activity.activityType == DetailSceneDelegate.activityType { let config = UISceneConfiguration(name: "DetailViewer", sessionRole: connectingSceneSession.role) return config } return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } } ``` ## BrowserSplitViewController.swift ```swift /* Abstract: Coordinates selection changes across the split view controller's various columns. */ import UIKit class BrowserSplitViewController: UISplitViewController { private(set) var selectedItemsCollection = ModelItemsCollection() private var supplementarySelectionChangeObserver: Any? var selectedItems: [AnyModelItem] { selectedItemsCollection.modelItems } var detailItem: AnyModelItem? { didSet { updateDueToDetailItemChange() } } let model = SampleData.data override func viewDidLoad() { super.viewDidLoad() primaryBackgroundStyle = .sidebar setViewController(emptyNavigationController(), for: .secondary) setViewController(emptyNavigationController(), for: .supplementary) supplementarySelectionChangeObserver = NotificationCenter .default .addObserver(forName: .modelItemsCollectionDidChange, object: selectedItemsCollection, queue: nil) { [weak self] note in self?.updateDueToSelectedItemsChange() } updateDueToSelectedItemsChange() updateDueToDetailItemChange() } deinit { supplementarySelectionChangeObserver.map(NotificationCenter.default.removeObserver(_:)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) show(.primary) } private func postBrowserStateChangeNotification() { NotificationCenter.default.post(name: .browserStateDidChange, object: self) } private func updateDueToSelectedItemsChange() { if let navigationController = viewController(for: .supplementary) as? UINavigationController, navigationController.viewControllers.isEmpty { let viewController = SupplementaryViewController(selectedItemsCollection: selectedItemsCollection) navigationController.viewControllers = [viewController] } show(.supplementary) if selectedItemsCollection.modelItems.isEmpty { view.window?.windowScene?.subtitle = "" } postBrowserStateChangeNotification() } private func updateDueToDetailItemChange() { let subtitleKeyPath: ReferenceWritableKeyPath<UIScene, String>? if view.window?.windowScene != nil { // Using a writable keypath here helps us to not litter the code below with the target conditional (#if targetEnvironment...) #if targetEnvironment(macCatalyst) subtitleKeyPath = \UIScene.subtitle #else subtitleKeyPath = \UIScene.title #endif } else { subtitleKeyPath = nil } if let detailItem = detailItem { if let navigationController = viewController(for: .secondary) as? UINavigationController { let detailViewController = DetailViewController(modelItem: detailItem) if let keyPath = subtitleKeyPath { view.window?.windowScene?[keyPath: keyPath] = detailItem.name } navigationController.viewControllers = [detailViewController] } } else { setViewController(emptyNavigationController(), for: .secondary) if selectedItemsCollection.modelItems.isEmpty { if let keyPath = subtitleKeyPath, let scene = view.window?.windowScene { scene[keyPath: keyPath] = "" } } else { if let keyPath = subtitleKeyPath, let scene = view.window?.windowScene { scene[keyPath: keyPath] = selectedItemsCollection.subtitle(forMostRecentlySelected: nil) } } } NotificationCenter.default.post(name: .browserStateDidChange, object: self) } private func emptyNavigationController() -> UINavigationController { let emptyNavigationController = UINavigationController() #if targetEnvironment(macCatalyst) emptyNavigationController.isNavigationBarHidden = true #endif return emptyNavigationController } var sidebarViewController: SidebarViewController { (viewController(for: .primary) as! UINavigationController).viewControllers.first as! SidebarViewController } var detailViewController: DetailViewController? { (viewController(for: .secondary) as? UINavigationController)?.viewControllers.first as? DetailViewController } var supplementaryViewController: SupplementaryViewController? { (viewController(for: .supplementary) as? UINavigationController)?.viewControllers.first as? SupplementaryViewController } override func target(forAction action: Selector, withSender sender: Any?) -> Any? { switch action { case #selector(UIResponder.printContent(_:)): if supplementaryViewController?.selectedItems.count == 1, let specificDetailChild = detailViewController?.children.first { // Direct the responder chain to the detail view controller if the user only has a single item selected. return specificDetailChild } else { // Otherwise, print all of the selected items return self } default: return super.target(forAction: action, withSender: sender) } } // MARK: State restoration func restoreSelections(selectedItems: [AnyModelItem], detailItem: AnyModelItem?) { selectedItemsCollection.modelItems = selectedItems self.detailItem = detailItem } // MARK: Printing private var itemsToPrint: [AnyModelItem] { if let supplementaryViewController = supplementaryViewController, !supplementaryViewController.selectedItems.isEmpty { return supplementaryViewController.selectedItems } else { return selectedItems } } // This action will be used whenever any UIResponder within the BrowserSplitView is first responder, except if the // RewardsProgramDetailViewController or the LocatedItemDetailViewController are first responder. override func printContent(_ sender: Any?) { let printItems = itemsToPrint guard !printItems.isEmpty else { return } let renderer = ItemPrintPageRenderer(items: printItems) let info = UIPrintInfo.printInfo() info.outputType = .general info.orientation = .portrait if printItems.count == 1 { info.jobName = printItems.first!.name } else { info.jobName = "Multiple Items" } let printInteractionController = UIPrintInteractionController.shared printInteractionController.printPageRenderer = renderer printInteractionController.printInfo = info printInteractionController.present(from: .zero, in: self.view, animated: true) {controller, completed, error in if error != nil { Swift.debugPrint("Error while printing: (String(describing: error))") } } } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(self.printContent(_:)) { return ItemPrintPageRenderer.canPrint(items: itemsToPrint) } else { return super.canPerformAction(action, withSender: sender) } } } extension NSNotification.Name { static let browserStateDidChange = NSNotification.Name("browserStateDidChange") } ``` ## DetailSceneDelegate.swift ```swift /* Abstract: The delegate for scenes created by "drilling-down" to view detail items. On iPad this is typically a drag interaction to create a new scene, on Mac Catalyst, a double-click of a collection view cell. */ import UIKit class DetailSceneDelegate: UIResponder, UIWindowSceneDelegate { static let activityType: String = "com.example.TripPlanner.detailScene" // The `window` property will automatically be loaded with the storyboard's initial view controller. var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity { configure(with: userActivity) } if let windowScene = scene as? UIWindowScene { #if targetEnvironment(macCatalyst) configureToolbar(windowScene: windowScene) #endif } } func configure(with userActivity: NSUserActivity) { var newUserActivity: NSUserActivity? = nil if let itemId = userActivity.userInfo?["itemID"] as? ItemIdentifierProviding.ItemID, let item = SampleData.data.item(withID: itemId) { let detailViewController = DetailViewController(modelItem: item) window?.windowScene?.title = item.name if let navigationController = window?.rootViewController as? UINavigationController { #if targetEnvironment(macCatalyst) navigationController.isNavigationBarHidden = true #endif navigationController.viewControllers = [detailViewController] newUserActivity = userActivity } } self.userActivity = newUserActivity newUserActivity?.becomeCurrent() } func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { return userActivity } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { configure(with: userActivity) } #if targetEnvironment(macCatalyst) private var toolbarModel = DetailToolbarModel() func configureToolbar(windowScene: UIWindowScene) { let toolbar = NSToolbar(identifier: "detail") toolbar.delegate = toolbarModel windowScene.titlebar?.toolbar = toolbar windowScene.titlebar?.toolbarStyle = .unifiedCompact } #endif } #if targetEnvironment(macCatalyst) private class DetailToolbarModel: NSObject, NSToolbarDelegate { var shareItem = NSSharingServicePickerToolbarItem(itemIdentifier: .init("share")) func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [shareItem.itemIdentifier] } func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [shareItem.itemIdentifier] } func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { switch itemIdentifier { case shareItem.itemIdentifier: return shareItem default: return nil } } } #endif ``` ## DetailViewController.swift ```swift /* Abstract: A container view controller for displaying `AnyModelItem`s. This view controller encapsulates the logic for determining which view controller subclass to use to represent the various specific model items `AnyModelItem` can wrap. */ import UIKit class DetailViewController: UIViewController { private let modelItem: AnyModelItem init(modelItem: AnyModelItem) { self.modelItem = modelItem super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground title = modelItem.name installChildDetailViewController() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override var activityItemsConfiguration: UIActivityItemsConfigurationReading? { get { modelItem } set { super.activityItemsConfiguration = newValue Swift.debugPrint("Cannot set activityItemsConfiguration") } } lazy var shareButtonItem: UIBarButtonItem = { UIBarButtonItem(image: UIImage(systemName: "square.and.arrow.up"), style: .plain, target: self, action: #selector(share(_:))) }() #if os(iOS) lazy var printButtonItem: UIBarButtonItem = { let target: Any? if splitViewController == nil { target = children.first } else { target = nil } return UIBarButtonItem(image: UIImage(systemName: "printer"), style: .plain, target: target, action: #selector(printContent(_:))) }() #endif @objc func share(_ sender: Any) { if let buttonItem = sender as? UIBarButtonItem, let activityItemsConfiguration = activityItemsConfiguration { let activityViewController = UIActivityViewController(activityItemsConfiguration: activityItemsConfiguration) activityViewController.popoverPresentationController?.barButtonItem = buttonItem present(activityViewController, animated: true, completion: nil) } } private func installChildDetailViewController() { var childViewController: UIViewController? = nil var barButtonItems = [UIBarButtonItem]() if let location = modelItem.locatedItem { let locatedItemViewController = LocatedItemDetailViewController(modelItem: location) childViewController = locatedItemViewController if let imageBarItem = locatedItemViewController.specialBarButtonImage { let imageView = UIImageView(image: imageBarItem) let iconItem = UIBarButtonItem(customView: imageView) barButtonItems = [iconItem] } } else if let rewardsProgram = modelItem.rewardsProgram { let storyboard = UIStoryboard(name: "RewardsDetail", bundle: nil) childViewController = storyboard.instantiateInitialViewController { coder in RewardsProgramDetailViewController(coder: coder, program: rewardsProgram) } } if let childViewController = childViewController { addChild(childViewController) self.view.addSubview(childViewController.view) childViewController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ childViewController.view.leftAnchor.constraint(equalTo: view.leftAnchor), childViewController.view.rightAnchor.constraint(equalTo: view.rightAnchor), childViewController.view.topAnchor.constraint(equalTo: view.topAnchor), childViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) childViewController.didMove(toParent: self) barButtonItems.insert(shareButtonItem, at: 0) #if os(iOS) // On Mac Catalyst, it is sufficient to have the "Print" Menu Item only. Without the promise of a physical keyboard (for ?P key commands) // or an app menu bar, printing should be available prominently. barButtonItems.insert(printButtonItem, at: 1) #endif self.navigationItem.rightBarButtonItems = barButtonItems } } } ``` ## ImageCollectionViewConfigurationCell.swift ```swift /* Abstract: A UICollectionViewCell subclass that provides two main behaviors on top of `UICollectionViewCell`: 1. On catalyst, allows double taps to be recognized on the cell to open a new window of the item that cell represents. 2. On iOS and Catalyst, update the cell's background configuration to style the cell differently for selected and non-selected states. */ import UIKit class ImageCollectionViewConfigurationCell: UICollectionViewCell { #if targetEnvironment(macCatalyst) private let doubleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer() var doubleTapCallback: (() -> Void)? = nil override init(frame: CGRect) { super.init(frame: frame) addGestureRecognizers() } required init?(coder: NSCoder) { super.init(coder: coder) addGestureRecognizers() } private func addGestureRecognizers() { guard doubleTapGestureRecognizer.view == nil else { return } doubleTapGestureRecognizer.numberOfTapsRequired = 2 doubleTapGestureRecognizer.cancelsTouchesInView = false doubleTapGestureRecognizer.delaysTouchesEnded = false doubleTapGestureRecognizer.addTarget(self, action: #selector(doubleTap(_:))) addGestureRecognizer(doubleTapGestureRecognizer) } @objc func doubleTap(_ sender: UITapGestureRecognizer) { doubleTapCallback?() } #endif override func updateConfiguration(using state: UICellConfigurationState) { var backgroundConfig = UIBackgroundConfiguration.listPlainCell().updated(for: state) backgroundConfig.cornerRadius = 3.0 if state.isSelected { backgroundConfig.backgroundColor = self.tintColor backgroundConfig.strokeWidth = 1 backgroundConfig.strokeColor = self.tintColor } else { backgroundConfig.backgroundColor = .clear backgroundConfig.strokeColor = .clear } backgroundConfiguration = backgroundConfig } override func prepareForReuse() { super.prepareForReuse() #if targetEnvironment(macCatalyst) doubleTapCallback = nil #endif contentView.subviews.forEach { $0.removeFromSuperview() } } } ``` ## LocatedItemDetailViewController.swift ```swift /* Abstract: A View Controller for representing any model item with a location and image. */ import UIKit import MapKit class LocatedItemDetailViewController: UIViewController { let modelItem: LocatedItem init(modelItem: LocatedItem) { self.modelItem = modelItem super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() installImageView() installDynamicStack() installButtons() installSubtextAndMapView() installPriceRangeIfNeeded() } lazy var specialBarButtonImage: UIImage? = { if let restaurant = modelItem as? Restaurant, let iconImage = restaurant.iconImage { return iconImage } else { return nil } }() override func loadView() { view = UIView() // The image goes behind everything else, and will be blurred let imageBackground = makeImageView(shareEnabled: false) view.addSubview(imageBackground) imageBackground.contentMode = .scaleToFill imageBackground.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageBackground.leftAnchor.constraint(equalTo: view.leftAnchor), imageBackground.rightAnchor.constraint(equalTo: view.rightAnchor), imageBackground.topAnchor.constraint(equalTo: view.topAnchor), imageBackground.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) view.tintColor = modelItem.downsampledColor // The visual effect view goes directly on top of the image view.addSubview(visualEffect) NSLayoutConstraint.activate([ visualEffect.topAnchor.constraint(equalTo: view.topAnchor), visualEffect.leadingAnchor.constraint(equalTo: view.leadingAnchor), visualEffect.trailingAnchor.constraint(equalTo: view.trailingAnchor), visualEffect.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) // Everything else is an ancestor of the visual effect view's content view visualEffect.contentView.addSubview(scroll) NSLayoutConstraint.activate([ scroll.topAnchor.constraint(equalTo: visualEffect.safeAreaLayoutGuide.topAnchor), scroll.leadingAnchor.constraint(equalTo: visualEffect.safeAreaLayoutGuide.leadingAnchor), scroll.trailingAnchor.constraint(equalTo: visualEffect.safeAreaLayoutGuide.trailingAnchor), scroll.bottomAnchor.constraint(equalTo: visualEffect.safeAreaLayoutGuide.bottomAnchor) ]) scroll.addSubview(rootVStack) rootVStack.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ rootVStack.leadingAnchor.constraint(equalTo: scroll.leadingAnchor), rootVStack.trailingAnchor.constraint(equalTo: scroll.trailingAnchor), rootVStack.topAnchor.constraint(equalTo: scroll.topAnchor), rootVStack.bottomAnchor.constraint(equalTo: scroll.bottomAnchor), rootVStack.widthAnchor.constraint(equalTo: scroll.widthAnchor) ]) } // MARK: Subviews private var rootVStack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.alignment = .center stack.translatesAutoresizingMaskIntoConstraints = false stack.spacing = UIStackView.spacingUseSystem stack.isLayoutMarginsRelativeArrangement = true stack.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) return stack }() private var dynamicStack: UIStackView = { let stack = UIStackView() stack.axis = .horizontal stack.alignment = .top stack.translatesAutoresizingMaskIntoConstraints = false stack.spacing = 10 return stack }() private let buttonStack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.alignment = .center stack.translatesAutoresizingMaskIntoConstraints = false stack.spacing = UIStackView.spacingUseSystem return stack }() private var buttonCompactConstraints: [NSLayoutConstraint] = [] private var buttonRegularConstraints: [NSLayoutConstraint] = [] private let mapAndSubtextStack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.alignment = .center stack.translatesAutoresizingMaskIntoConstraints = false stack.spacing = UIStackView.spacingUseSystem return stack }() private var scroll: UIScrollView = { let scroll = UIScrollView() scroll.translatesAutoresizingMaskIntoConstraints = false scroll.alwaysBounceVertical = true return scroll }() private var visualEffect: UIVisualEffectView = { let vev = UIVisualEffectView(effect: UIBlurEffect(style: .systemThickMaterial)) vev.translatesAutoresizingMaskIntoConstraints = false return vev }() private lazy var heroImageView: UIView = { let imageView = makeImageView(shareEnabled: true) imageView.contentMode = .scaleAspectFill let interaction = UIToolTipInteraction(defaultToolTip: modelItem.altText) imageView.addInteraction(interaction) return imageView }() private let buttons: [UIButton] = { var config = UIButton.Configuration.filled() let transforms = (-2...1).map { alphaStep in UIConfigurationColorTransformer { color in var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0 color.getRed(&r, green: &g, blue: &b, alpha: nil) let increasedWhite: CGFloat = (CGFloat(alphaStep) * 0.07) + 1 return UIColor(red: increasedWhite * r, green: increasedWhite * g, blue: increasedWhite * b, alpha: 1.0) } } let directions = UIButton(type: .system) config.title = "Get Directions" config.image = UIImage(systemName: "arrow.triangle.turn.up.right.circle") config.background.backgroundColorTransformer = transforms[0] directions.configuration = config let tripPlan = UIButton(type: .system) config.title = "ML Trip Planner" config.image = UIImage(systemName: "person.circle") config.background.backgroundColorTransformer = transforms[1] tripPlan.configuration = config let podcast = UIButton(type: .system) config.title = "Site Audio Tour" config.image = UIImage(systemName: "headphones.circle") config.background.backgroundColorTransformer = transforms[2] podcast.configuration = config let arTour = UIButton(type: .system) config.title = "AR Walkthrough" config.image = UIImage(systemName: "viewfinder.circle") config.background.backgroundColorTransformer = transforms[3] arTour.configuration = config return [directions, tripPlan, podcast, arTour] }() private func makeImageView(shareEnabled: Bool) -> UIImageView { guard let image = modelItem.image else { Swift.debugPrint("Missing image for (modelItem)") return UIImageView() } let imageView = shareEnabled ? SharingImageView(image: image) : UIImageView(image: image) return imageView } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [self] context in updateDynamicStack(using: size) dynamicStack.setNeedsLayout() dynamicStack.layoutIfNeeded() }, completion: nil) } private func updateDynamicStack(using size: CGSize?) { let currentButtonWidth = buttonStack.subviews.first?.sizeThatFits(UIView.layoutFittingCompressedSize).width ?? .zero let minimumRequiredTextWidth: CGFloat = 300 let workingSize: CGSize = size ?? view.frame.size if workingSize.width < currentButtonWidth + minimumRequiredTextWidth { dynamicStack.axis = .vertical buttonRegularConstraints.forEach { $0.isActive = false } buttonCompactConstraints.forEach { $0.isActive = true } } else { dynamicStack.axis = .horizontal buttonCompactConstraints.forEach { $0.isActive = false } buttonRegularConstraints.forEach { $0.isActive = true } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateDynamicStack(using: nil) } // MARK: Printing fileprivate func itemsToPrint() -> [AnyModelItem] { let itemsToPrint = [AnyModelItem(modelItem)] return itemsToPrint } // This action will only be used when the LocatedItemDetailViewController is firstResponder. This mainly happens if it has been opened in // its own window scene. override func printContent(_: Any?) { let renderer = ItemPrintPageRenderer(items: itemsToPrint()) let info = UIPrintInfo.printInfo() info.outputType = .general info.orientation = .portrait info.jobName = modelItem.name let printInteractionController = UIPrintInteractionController.shared printInteractionController.printPageRenderer = renderer printInteractionController.printInfo = info printInteractionController.present(animated: true) } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(self.printContent(_:)) { return ItemPrintPageRenderer.canPrint(items: itemsToPrint()) } else { return super.canPerformAction(action, withSender: sender) } } } extension LocatedItemDetailViewController: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions -> UIMenu? in return UIMenu(title: "main", image: nil, identifier: nil, options: [], children: suggestedActions) }) } } // MARK: View Layout extension LocatedItemDetailViewController { private func installImageView() { heroImageView.layer.cornerRadius = 6.0 heroImageView.layer.masksToBounds = true rootVStack.addArrangedSubview(heroImageView) heroImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 350.0).isActive = true } private func installDynamicStack() { rootVStack.addArrangedSubview(dynamicStack) } private func installSubtextAndMapView() { let textView = UITextView() textView.text = modelItem.caption textView.font = UIFont.preferredFont(forTextStyle: .subheadline) textView.isEditable = false textView.isScrollEnabled = false textView.backgroundColor = .clear textView.translatesAutoresizingMaskIntoConstraints = false let labelWrapper = UIView() labelWrapper.addSubview(textView) NSLayoutConstraint.activate([ textView.leadingAnchor.constraint(equalToSystemSpacingAfter: labelWrapper.leadingAnchor, multiplier: 1.0), labelWrapper.trailingAnchor.constraint(equalToSystemSpacingAfter: textView.trailingAnchor, multiplier: 1.0), textView.topAnchor.constraint(equalToSystemSpacingBelow: labelWrapper.topAnchor, multiplier: 1.0), labelWrapper.bottomAnchor.constraint(equalToSystemSpacingBelow: textView.bottomAnchor, multiplier: 1.0) ]) labelWrapper.backgroundColor = .systemGroupedBackground.withAlphaComponent(0.6) labelWrapper.layer.cornerRadius = 3.0 labelWrapper.clipsToBounds = true let mapView = MKMapView() mapView.layer.cornerRadius = 4.0 mapView.isScrollEnabled = false mapView.isZoomEnabled = true // default #if targetEnvironment(macCatalyst) mapView.showsPitchControl = true mapView.showsZoomControls = true #endif mapAndSubtextStack.addArrangedSubview(labelWrapper) mapAndSubtextStack.addArrangedSubview(mapView) mapView.region = MKCoordinateRegion(center: modelItem.location.coordinate, latitudinalMeters: 1600, longitudinalMeters: 1600) let isLeftToRight = view.effectiveUserInterfaceLayoutDirection == .leftToRight dynamicStack.insertArrangedSubview(mapAndSubtextStack, at: isLeftToRight ? 0 : 1) // Stretch the label and map as wide as they'll go without interfering with the buttons let optionalWidthMap = mapView.widthAnchor.constraint(equalTo: view.widthAnchor) optionalWidthMap.priority = .defaultHigh + 100 optionalWidthMap.isActive = true labelWrapper.widthAnchor.constraint(equalTo: mapView.widthAnchor).isActive = true let labelAndMap = mapAndSubtextStack.widthAnchor.constraint(equalTo: view.widthAnchor) labelAndMap.priority = .defaultHigh labelAndMap.isActive = true // Give the map a somewhat arbitrary aspect ratio mapView.heightAnchor.constraint(equalTo: mapView.widthAnchor, multiplier: 0.7).isActive = true } private func installButtons() { let maxWidth: CGFloat = buttons.reduce(0) { result, button in button.sizeToFit() return max(result, button.frame.size.width) } buttons.forEach { button in buttonStack.addArrangedSubview(button) } buttonCompactConstraints = buttons.map { button in button.widthAnchor.constraint(equalTo: dynamicStack.widthAnchor) } buttonRegularConstraints = buttons.map { button in let equalWidthsConstraint = button.widthAnchor.constraint(equalToConstant: maxWidth) equalWidthsConstraint.priority = .defaultHigh + 200 equalWidthsConstraint.isActive = true return equalWidthsConstraint } dynamicStack.addArrangedSubview(buttonStack) } private func installPriceRangeIfNeeded() { guard let price = (modelItem as? Lodging)?.priceRange ?? (modelItem as? Restaurant)?.priceRange else { return } let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale(identifier: price.localeIdentifier) let priceLabel = UILabel() priceLabel.showsExpansionTextWhenTruncated = true priceLabel.text = "(formatter.string(for: price.lower)!)...(formatter.string(for: price.upper)!)" buttonStack.insertArrangedSubview(priceLabel, at: 0) } } ``` ## RewardsProgramDetailViewController.swift ```swift /* Abstract: Intended for use as a child view controller of DetailViewController. Represents the `RewardsProgram` model object. */ import UIKit /// The `EmojiKnobSlider` assumes its knob will alternate between an emoji and the standard UISlider knob artwork. It overrides methods to ensure its /// layout attributes don't change � thus the slider won't shift � when the knob size changes. class EmojiKnobSlider: UISlider { override func trackRect(forBounds bounds: CGRect) -> CGRect { return super.trackRect(forBounds: CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 23))) } override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { if currentThumbImage == nil { return super.thumbRect( forBounds: CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 23)), trackRect: rect, value: value) } else { let skinnyKnobShift: CGFloat = CGFloat((1 - value / maximumValue) * -10 + 4) var rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value) rect.origin.x += skinnyKnobShift return rect } } } class RewardsProgramDetailViewController: UIViewController { static private let sliderPatternColor = UIColor(patternImage: #imageLiteral(resourceName: "slider_pattern")) @IBOutlet weak var topLeft: UIButton! @IBOutlet weak var topRight: UIButton! @IBOutlet weak var bottomLeft: UIButton! @IBOutlet weak var bottomRight: UIButton! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var multiplierToggleButton: UIButton! @IBOutlet weak var sliderLabelAndMultiplierStack: UIStackView! @IBOutlet weak var slider: UISlider! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var rootStack: UIStackView! @IBOutlet weak var bottomButtonsStack: UIStackView! @IBOutlet weak var pointsCount: UILabel! let program: RewardsProgram init(program: RewardsProgram) { self.program = program super.init(nibName: nil, bundle: nil) } init?(coder: NSCoder, program: RewardsProgram) { self.program = program super.init(coder: coder) } @available(*, unavailable, renamed: "init(coder:program:)") required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 10, leading: 8, bottom: 8, trailing: 10) bottomButtonsStack.isLayoutMarginsRelativeArrangement = true imageView.image = UIImage(systemName: program.imageName)! slider.preferredBehavioralStyle = .pad self.title = program.name self.titleLabel.text = program.name slider.minimumValue = 0 slider.maximumValue = Float(program.points) pointsCount.text = String(slider.value) configureMenu() styleButtons() multiplierToggleButton.configuration?.baseBackgroundColor = UIColor.tintColor slider.value = Float(program.points / 2) updatePointsLabel() } @IBAction func pointsMultiplierToggled(_ sender: Any) { guard let toggleButton = sender as? UIButton else { return } if toggleButton.isSelected { selectedMultiplierIndex = 0 } else { selectedMultiplierIndex = nil } } @IBAction func sliderAction(_ sender: Any) { updatePointsLabel() } @IBAction func redeemOption(_ sender: Any) { } @IBAction func donateOption(_ sender: Any) { } @IBAction func cashOutOption(_ sender: Any) { } // MARK: - View State private func updateState() { configureMenu() if let index = selectedMultiplierIndex { multiplierToggleButton.isSelected = true slider.setThumbImage("??".image(textStyle: .title2), for: .normal) slider.minimumTrackTintColor = RewardsProgramDetailViewController.sliderPatternColor if index == 2 { // Activate "Mega Extreme Mode" if the user selects to 6* their points! view.tintColor = .systemRed } else { view.tintColor = nil } } else { multiplierToggleButton.isSelected = false slider.setThumbImage(nil, for: .normal) slider.minimumTrackTintColor = nil view.tintColor = nil } updatePointsLabel() } private let formatter: NumberFormatter = { let thousandsSeparatorNoDecimal = NumberFormatter() thousandsSeparatorNoDecimal.allowsFloats = false thousandsSeparatorNoDecimal.usesGroupingSeparator = true thousandsSeparatorNoDecimal.groupingSize = 3 thousandsSeparatorNoDecimal.groupingSeparator = "," return thousandsSeparatorNoDecimal }() private func updatePointsLabel() { let multiplier: Float switch selectedMultiplierIndex { case 0: multiplier = 2 case 1: multiplier = 3 case 2: multiplier = 6 default: multiplier = 1 } pointsCount.text = formatter.string(from: NSNumber(value: slider.value * multiplier)) } private func configureMenu() { multiplierActions.forEach { $0.state = .off } if let selectedMultiplierIndex = selectedMultiplierIndex { multiplierActions[selectedMultiplierIndex].state = .on } let menu = UIMenu(options: [], children: multiplierActions) multiplierToggleButton.menu = menu } /// These UIActions are reused each time the button's menu has to be recreated. We simply set the selection state on the selected item, if any, /// then they are copied as part of the button's menu copy when it is set. private lazy var multiplierActions: [UIAction] = { let children = ["2*", "3*", "6*"].map { title -> UIAction in UIAction(title: title, state: .off) { [weak self] action in switch action.title { case "2*": self?.selectedMultiplierIndex = 0 case "3*": self?.selectedMultiplierIndex = 1 case "6*": self?.selectedMultiplierIndex = 2 default: self?.selectedMultiplierIndex = nil } } } return children }() private var selectedMultiplierIndex: Int? { didSet { updateState() } } private func styleButtons() { var buttonConfig = UIButton.Configuration.filled() buttonConfig.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 60) // Adjusts the background color for any button configuration to reflect the selected state. let colorUpdateHandler: (UIButton) -> Void = { button in button.configuration?.baseBackgroundColor = button.isSelected ? UIColor.tintColor : UIColor.tintColor.withAlphaComponent(0.4) } zip([bottomLeft, bottomRight, topLeft, topRight], ["bed.double", "bag", "leaf", "bus.doubledecker"]).forEach { button, symbolName in buttonConfig.image = UIImage(systemName: symbolName) button!.configuration = buttonConfig button!.changesSelectionAsPrimaryAction = true button!.configurationUpdateHandler = colorUpdateHandler button?.preferredBehavioralStyle = .pad } } // MARK: Printing private func itemsToPrint() -> [AnyModelItem] { let itemsToPrint = [AnyModelItem(program)] return itemsToPrint } // This action will only be used when the RewardsProgramDetailViewController is firstResponder. This mainly happens if it has been opened in its // own window scene. override func printContent(_: Any?) { let renderer = ItemPrintPageRenderer(items: itemsToPrint()) let info = UIPrintInfo.printInfo() info.outputType = .general info.orientation = .portrait info.jobName = program.name let printInteractionController = UIPrintInteractionController.shared printInteractionController.printPageRenderer = renderer printInteractionController.printInfo = info printInteractionController.present(animated: true) } } ``` ## SharingImageView.swift ```swift /* Abstract: Attaching a context menu interaction to this image allows a secondary-click on Mac Catalyst to display a menu for sharing specifically the image. */ import UIKit /// An image view that can share its contents class SharingImageView: UIImageView, UIContextMenuInteractionDelegate { override var activityItemsConfiguration: UIActivityItemsConfigurationReading? { get { if let image = image { } else { // Return a non-nil value with no sharable objects, so that the framework will not // use a parent responder's activity items configuration. return UIActivityItemsConfiguration(objects: []) } } set { super.activityItemsConfiguration = newValue Swift.debugPrint("Cannot set activity items configuration") } } lazy var contextMenuInteraction = UIContextMenuInteraction(delegate: self) override func willMove(toWindow newWindow: UIWindow?) { removeInteraction(contextMenuInteraction) super.willMove(toWindow: newWindow) } override func didMoveToWindow() { addInteraction(contextMenuInteraction) isUserInteractionEnabled = true } func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { defaultMenuItems in return UIMenu(title: "Share to:", image: nil, identifier: nil, options: [], children: defaultMenuItems) }) } } ``` ## DataModel.swift ```swift /* Abstract: A smattering of model objects and a type-erased form, `AnyModelObjects` to use when collections are required to be homogeneous. */ import Foundation import CoreLocation /// A data model protocol. Model objects must implement this protocol to be displayed in the app sidebar protocol Model { var countries: [Country] { get } var rewardsPrograms: [RewardsProgram] { get } } protocol ItemIdentifierProviding { typealias ItemID = String var itemID: ItemID { get } } protocol ImageProviding { var imageName: String { get } var altText: String { get } var caption: String { get } } protocol LocationProviding { var location: CLLocation { get } } protocol IconNameProviding { var iconName: String { get } } typealias LocatedItem = ModelItem & ImageProviding & LocationProviding struct Country: ModelItem, IconNameProviding { let itemID: ItemID let name: String let lodgings: [Lodging] let restaurants: [Restaurant] let sights: [Sight] let iconName: String } struct Lodging: LocatedItem, IconNameProviding { let itemID: ItemID let name: String let location: CLLocation let priceRange: PriceRange let iconName: String let imageName: String let altText: String let caption: String } struct Restaurant: LocatedItem, IconNameProviding { let itemID: ItemID let name: String let location: CLLocation let priceRange: PriceRange let iconName: String let imageName: String let altText: String let caption: String } struct PriceRange { let lower: Int let upper: Int let localeIdentifier: String } struct Sight: LocatedItem, IconNameProviding { let itemID: ItemID let name: String let location: CLLocation let iconName: String let imageName: String let altText: String let caption: String } struct RewardsProgram: ModelItem, IconNameProviding, ImageProviding { let itemID: ItemID let name: String let points: Int let iconName: String let imageName: String var altText: String = "" var caption: String = "" } protocol ModelItem: ItemIdentifierProviding { var name: String { get } } extension ModelItem { var userActivity: NSUserActivity { let userActivity = NSUserActivity(activityType: DetailSceneDelegate.activityType) userActivity.userInfo = ["itemID": itemID] userActivity.title = name return userActivity } } class AnyModelItem: NSObject, ModelItem { typealias ItemID = ItemIdentifierProviding.ItemID private let wrapped: ModelItem var itemID: ItemID { wrapped.itemID } var name: String { wrapped.name } var imageName: String? { (wrapped as? ImageProviding)?.imageName } var altText: String? { (wrapped as? ImageProviding)?.altText } var caption: String? { (wrapped as? ImageProviding)?.caption } var iconName: String? { (wrapped as? IconNameProviding)?.iconName } var location: CLLocation? { (wrapped as? LocationProviding)?.location } var country: Country? { wrapped as? Country } var lodging: Lodging? { wrapped as? Lodging } var restaurant: Restaurant? { wrapped as? Restaurant } var locatedItem: LocatedItem? { restaurant ?? lodging ?? sight } var sight: Sight? { wrapped as? Sight } var rewardsProgram: RewardsProgram? { wrapped as? RewardsProgram } var isFavorite = false init(_ modelItem: ModelItem) { wrapped = modelItem } override var hash: Int { wrapped.itemID.hash } override func isEqual(_ object: Any?) -> Bool { guard let object = object as? AnyModelItem else { return false } return wrapped.itemID == object.itemID } } extension Model { func item(withID itemID: ItemIdentifierProviding.ItemID) -> AnyModelItem? { func findItem(in items: [ModelItem]) -> ModelItem? { for item in items { if item.itemID == itemID { return item } if let country = item as? Country { if let found = findItem(in: country.lodgings) ?? findItem(in: country.restaurants) ?? findItem(in: country.sights) { return found } } } return nil } return (findItem(in: countries) ?? findItem(in: rewardsPrograms)).map(AnyModelItem.init) } } ``` ## ModelItemsCollection.swift ```swift /* Abstract: Manages a collection of selected model items and posts notifications when it changes. */ import Foundation /// A collection of model items selected by the user class ModelItemsCollection { // We use an Array to preserve ordering var modelItems: [AnyModelItem] = [] { didSet { NotificationCenter.default.post(name: .modelItemsCollectionDidChange, object: self) } } func add(modelItems: [AnyModelItem]) { self.modelItems += modelItems.filter { !self.modelItems.contains($0) } } func remove(modelItems: [AnyModelItem]) { self.modelItems.removeAll { item in modelItems.contains { $0.itemID == item.itemID } } } /// Provides a human readable subtitle describing the collection of selected items /// - Parameter itemIdentifier The most recently selected item /// - Returns: A name describing the selected items func subtitle(forMostRecentlySelected itemIdentifier: SidebarItemIdentifier?) -> String { let newSelection: Set<AnyModelItem> let alreadySelected = Set(modelItems) switch itemIdentifier?.kind { case .leafModelItem(let modelItem)?: return modelItem.name case .expandableModelSection?, .expandableSection?, .expandableModelItem?: newSelection = Set(itemIdentifier!.kind.children) case nil: newSelection = [] } // If we're heterogeneous, exit with the most general title: let union = alreadySelected.union(newSelection) if union.contains(where: { $0.rewardsProgram == nil }) && union.contains(where: { $0.rewardsProgram != nil }) { return "Countries & Rewards Programs" } if union.isEmpty { return "" } if let itemIdentifier = itemIdentifier, alreadySelected.allSatisfy(newSelection.contains(_:)) { // All selected items are members of the new selection -> use the title of the new selection return itemIdentifier.name } else if newSelection.first?.rewardsProgram != nil || alreadySelected.first?.rewardsProgram != nil { return "Rewards Programs" } else { return "Countries" } } } extension NSNotification.Name { static let modelItemsCollectionDidChange = Notification.Name("ModelItemsCollectionDidChange") } ``` ## SampleData.swift ```swift /* Abstract: Could have been a plist */ import Foundation import CoreLocation class SampleData: Model { static let data: Model = SampleData(countries: Country.countries, rewardsPrograms: RewardsProgram.programs) let countries: [Country] let rewardsPrograms: [RewardsProgram] init(countries: [Country], rewardsPrograms: [RewardsProgram]) { self.countries = countries self.rewardsPrograms = rewardsPrograms } } extension Country { static let countries: [Country] = [japan, spain, brazil, tanzania] private static let japan = Country(itemID: "country.japan", name: "Japan", lodgings: [.tokyoTowerHotel, .sakuraRyokan, .okinawaResort], restaurants: [.mushiSushi, .lotusBento, .extremeMatcha], sights: [.fuji, .goldenPavilion, .nara], iconName: "??") private static let spain = Country(itemID: "country.spain", name: "Spain", lodgings: [.barcelonaHotel, .hotelCordoba, .meridien], restaurants: [.lasRamblas, .charcuterie], sights: [.alhambra, .parqueG�ell, .sagrada, .cordoba], iconName: "??") private static let brazil = Country(itemID: "country.brazil", name: "Brazil", lodgings: [.villaParaiso, .sugarloafMountainResort, .villaIsabel], restaurants: [.pratosPetite, .rioCantina, .mercadoCafe], sights: [.redeemer, .iguazuFalls, .copacabana], iconName: "??") private static let tanzania = Country(itemID: "country.tanzania", name: "Tanzania", lodgings: [.resortZanzibar, .glampKilimajaro, .nalaNalaReserve], restaurants: [.cafeChipsi, .onTheRocks, .cafeSafari], sights: [.serengeti, .kilimanjaro, .stoneTown], iconName: "??") } extension Lodging { // MARK: Japan fileprivate static let tokyoTowerHotel = Lodging(itemID: "lodging.japan.tokyotower", name: "???????? Tokyo Tower Hotel", location: CLLocation(latitude: 35.65, longitude: 139.75), priceRange: PriceRange(lower: 29_000, upper: 36_000, localeIdentifier: "en_JP"), iconName: "?", imageName: "tokyo_tower", altText: "A view of Tokyo Tower glowing with a vibrant orange color", caption: """ Enjoy the hospitality of this city escape while never leaving the city. Experience tradition and innovation all at once with classic and modern Japanese architecture and easy access to Tokyo�s train system beneath the lobby of the hotel. Tokyo Tower Hotel is a short walk from many of the cities temples and parks. You�re guaranteed the perfect rest over a panoramic view of the cityscape. """) fileprivate static let sakuraRyokan = Lodging(itemID: "lodging.japan.sakura", name: "??? Sakura Ryokan", location: CLLocation(latitude: 35.01, longitude: 135.77), priceRange: PriceRange(lower: 12_000, upper: 20_000, localeIdentifier: "en_JP"), iconName: "?", imageName: "cherry_blossoms", altText: "Gion cherry blossoms and wooden buildings line a river in Kyoto", caption: """ To be dropped into the heart of Japanese culture, start your trip at Sakura Ryokan ��a beautiful a and quaint family-run inn. A ryokan is more generally a traditional Japanese inn. They are one to two story wooden structures with sliding paper-paneled walls. When you walk in, remember to take off your shoes and slip right into your slippers. You may not see a bed at first. It is likely tucked nearly away in a closet to be rolled out in the evening. If you paid the big yen for your room, it may include a private bath heated by none other than the author�s favorite source of energy: geothermal. This is an onsen. Be sure to heed the etiquette on the onsen ��don�t get soap in the tub! You won�t want to take off your cozy yukata, and don�t worry, you don�t have to. Other people will be walking around in them too. """) fileprivate static let okinawaResort = Lodging(itemID: "lodging.japan.okinawa", name: "?????? Okinawa Slippers Resort", location: CLLocation(latitude: 26.333, longitude: 127.856), priceRange: PriceRange(lower: 7_000, upper: 13_000, localeIdentifier: "en_JP"), iconName: "?", imageName: "okinawa", altText: "An aerial view of the Sea of Okinawa", caption: """ Stay at Okinawa Slippers Resort as you island hop outside Okinawa Honto between the clusters of islands. Okinawa has its own spirit as a very unique part of Japan. There�s sailing, fishing, kayaking, and of course whale watching to be done. If you have any energy left by the evening, venture over to Hateruma to listen to the music of the sanshin, a three-stringed Japanese banjo-like instrument. """) // MARK: Brazil fileprivate static let villaParaiso = Lodging(itemID: "lodging.brazil.paraiso", name: "Villa Para�so", location: CLLocation(latitude: -7.13674, longitude: -34.836), priceRange: PriceRange(lower: 240, upper: 400, localeIdentifier: "pt_BR"), iconName: "?", imageName: "villa_paraiso", altText: "The cove behind Villa Para�so is a great place for a quiet lunch", caption: """ Sitting right on the coast, Villa Para�so welcomes all visitors with a beautiful beachside ambiance. Perfect for relaxing after a day at the beach, their resident pool is the best place for a hotel cocktail and a decompress from the sun. Enjoy their complimentary breakfast paired with their house-made coffee. """) fileprivate static let sugarloafMountainResort = Lodging(itemID: "lodging.brazil.sugarloaf", name: "Sugarloaf Mountain Restort", location: CLLocation(latitude: -22.951715, longitude: -43.15544), priceRange: PriceRange(lower: 400, upper: 800, localeIdentifier: "pt_BR"), iconName: "?", imageName: "sugarloaf", altText: "A serene pool nestled away in the foothills of the mountains", caption: """ Named after the gorgeous Brazilian rock formation, Sugarloaf Mountain Resort treats residents to a beautiful sunset scene overlooking the surrounding mountain ranges. Sugarloaf Mountain Resort is only minutes away from the city, but maintains the feel of a secluded nature resort scene overlooking the surrounding mountain ranges. Sugarloaf Mountain Resort is only minutes away from the city, but maintains the feel of a secluded nature resort. """) fileprivate static let villaIsabel = Lodging(itemID: "lodging.brazil.isabel", name: "Villa Isabel", location: CLLocation(latitude: -0.175514, longitude: -50.881646), priceRange: PriceRange(lower: 140, upper: 320, localeIdentifier: "pt_BR"), iconName: "?", imageName: "villa_isabel", altText: "A tiny hotel surrounded by palm trees with nothing else in sight", caption: """ If you are looking for a cozy, secluded hostel, book your stay at Villa Isabel. This community living house makes your vacation in Northern Brazil feel more like a second home. Surrounded by Brazil's own myriad palm trees, this little slice of paradise creates an unmatched relaxing ambiance � perfect to wind down after an active day in the city. """) // MARK: Tanzania fileprivate static let resortZanzibar = Lodging(itemID: "lodging.tanzania.oceanside", name: "Resort Zanzibar", location: CLLocation(latitude: -6.160475, longitude: 39.188564), priceRange: PriceRange(lower: 37_500, upper: 45_000, localeIdentifier: "sw_TZ"), iconName: "?", imageName: "oceanside_villa", altText: "A beachfront with huts atop volcanic rock", caption: """ Put your feet up and relax in your oceanside villa at Resort Zanzibar located on scenic Nakupenda Beach. Nakupenda translates to �I love you� in Swahili, and you will soon feel that sentiment. Take in the sweeping ocean views as you walk along the white sand beach. The gentle waves and clear water make for world-class snorkeling. """) fileprivate static let glampKilimajaro = Lodging(itemID: "lodging.tanzania.glamp", name: "Glamp Kilimanjaro", location: CLLocation(latitude: -2.892899, longitude: 37.295380), priceRange: PriceRange(lower: 49_000, upper: 80_000, localeIdentifier: "sw_TZ"), iconName: "??", imageName: "kilimanjaro_tent", altText: "A spacious tent on the Savannah with a setting sun in the background", caption: """ Untie your hiking boots and put your feet up after a long day on the mountain. You won�t have to lift a finger � your friendly porters will be ready for your arrival and will set up camp, provide food and water, perform health screens, and maintain a high level of cleanliness at the campsite. After dinner, get cozy on your sleeping pad and prepare for a midnight wakeup call to begin the final climb to the summit. """) fileprivate static let nalaNalaReserve = Lodging(itemID: "loding.tanzania.nala", name: "Nala Nala Game Reserve", location: CLLocation(latitude: -2.459298, longitude: 34.898963), priceRange: PriceRange(lower: 104_000, upper: 140_000, localeIdentifier: "sw_TZ"), iconName: "?", imageName: "safari_camp", altText: "A herd of elephants right outside one of the Nala Nala huts", caption: """ After a day on the Serengeti, your safari guide will drop you in a scenic clearing with small huts. Enjoy a family style dinner with the other members of your safari group and then unwind on the patio while taking in the sights and sounds of the wildlife. The Nala Nala Game Reserve is a hotspot for elephants. Target dawn or dusk for the best viewing of the herd. """) // MARK: Spain fileprivate static let barcelonaHotel = Lodging(itemID: "lodging.spain.barcelonahotel", name: "Barcelona Hotel", location: CLLocation(latitude: 41.390213, longitude: 2.16992), priceRange: PriceRange(lower: 74, upper: 100, localeIdentifier: "en_ES"), iconName: "?", imageName: "barcelona_hotel", altText: "A vibrant front facade of a multistory hotel against a blue evening sky, decorated with stained glass and roses", caption: """ Located in the heart of the city, Barcelona Hotel is the perfect destination for the romantics. Not star-crossed lovers, but enthusiasts of the era of Romanticism. Explore existentialism, individualism, glorifying nature, and subjective beauty as you spend time with others guests of the hotel who are more than willing to bikeshed your API proposals find what is in a name. """) fileprivate static let hotelCordoba = Lodging(itemID: "lodging.spain.cordoba", name: "Hotel C�rdoba", location: CLLocation(latitude: 37.878, longitude: -4.7968), priceRange: PriceRange(lower: 100, upper: 150, localeIdentifier: "en_ES"), iconName: "?", imageName: "hotel_cordoba", altText: "An upward looking angle of a hotel built with a modern architectural style", caption: """ Hotel Cordoba is the flagship hotel in Cordoba. Physically, It reminds one of the Plaza Hotel in New York or the Hotel Mumbai in Bombay. You could save a lot on airfare by contenting yourself with Hotel C�rdoba. If you can manage it, ask to see an photo of the room you have reserved. Many landmark hotels are tricksy and stack unwary guests in relatively generic �tower rooms�. """) fileprivate static let meridien = Lodging(itemID: "lodging.spain.hotelmeridien", name: "Hotel Le Meridien", location: CLLocation(latitude: 42.025, longitude: 0), priceRange: PriceRange(lower: 60, upper: 85, localeIdentifier: "en_ES"), iconName: "?", imageName: "hotel_le_meridien", altText: "A hotel on a street corner painted pink with four flags mounted over the front entrance. The image makes the place look very walkable.", caption: """ At Eurostars Patios you will feel as if you had hidden away as they closed the mosque/basilica/museum, so that you could spend the night in solitary appreciation of two different artistic cultures. Hotel Le Meridien is an instance of hotel suffused with period and cultural art and architecture, that succeeds in elevating the lodging transaction beyond the typical 5-star experience """) } extension Restaurant { // MARK: Japan fileprivate static let mushiSushi = Restaurant(itemID: "restaurant.japan.mushi", name: "???? Mushi Sushi", location: CLLocation(latitude: 35.46, longitude: 139.619), priceRange: PriceRange(lower: 1_200, upper: 2_000, localeIdentifier: "en_JP"), iconName: "?", imageName: "sushi", altText: "A pair of chopsticks grabbing one of 4 nigiri sushi rolls, wrapped in salmon.", caption: """ Though its name doesn't translate well, it has a nice ring to it. Located right along the harbor in Yokohama, this is where the local fishermen and dedicated entomologists go to sell their fresh catch to be rolled and crunched into the finest rolls and later, consumed by the adventurous tourist. Remember, sushi actually refers to anything ��not just raw fish ��served on or in vinegared rice. """) fileprivate static let lotusBento = Restaurant(itemID: "restaurant.japan.lotus", name: "??? Lotus Bento", location: CLLocation(latitude: 35.6688, longitude: 139.698), priceRange: PriceRange(lower: 500, upper: 900, localeIdentifier: "en_JP"), iconName: "?", imageName: "bento", altText: "A very fancy bento box arrangement served alongside tea. In one of the boxes is pork and rice, and in the other, tempura vegetables", caption: """ Grab a Bento Box on the go as you head toward Meiji Jingu. Bento is meant to be taken and eaten on the move, but not too on the move. In Japan it is not very socially acceptable to eat while walking, or on short train rides. That's the answer to how they keep the streets so clean in Tokyo! Never fear, like many foods, bento can also be enjoyed as picnic food in the park. """) fileprivate static let extremeMatcha = Restaurant(itemID: "restaurant.japan.matcha", name: "Extreme Matcha", location: CLLocation(latitude: 34.698, longitude: 135.188), priceRange: PriceRange(lower: 400, upper: 2_000, localeIdentifier: "en_JP"), iconName: "?", imageName: "matcha", altText: "An aesthetic matcha latte on a smooth wooden table", caption: """ The matcha count in the air is over 100,000 parts per million in this happening cafe in Kobe. Their offerings include cakes, mochi, lattes, and cookies. It's a great place to take a break from a long day of walking, recharge and get that green-tea boost to post the perfect matcha picture to your social media, #matchaMadeInHeaven. """) // MARK: Brazil fileprivate static let pratosPetite = Restaurant(itemID: "restaurant.brazil.pratospetit", name: "Pratos Petit", location: CLLocation(latitude: -22.8986, longitude: -43.17896), priceRange: PriceRange(lower: 21, upper: 31, localeIdentifier: "pt_BR"), iconName: "?", imageName: "grandes_pratos", altText: "Tamales, tamales, tamales", caption: """ Enjoy a tasty breakfast in Brazil at Pratos Petit. Fill your small plate with homemade jams, fresh espresso, and delicious P�o de queijo before the sun rises. Return for lunch or dinner to grab their signature pamonha and pasteles that will satisfy all your cravings after a day of adventure in Rio. """) fileprivate static let rioCantina = Restaurant(itemID: "restaurant.brazil.riocantina", name: "Rio Cantina", location: CLLocation(latitude: -22.9033, longitude: -43.1722), priceRange: PriceRange(lower: 25, upper: 45, localeIdentifier: "pt_BR"), iconName: "?", imageName: "rio_cantina", altText: "A dining room nestled surrounded by bright green trees that embodies indoor/outdoor seating", caption: """ Be sure to snag a reservation at the famous Rio Cantina in Northern Brazil. This cozy restaurant is home to delicious traditional Brazilian cuisine, serving its customers the national dish feijoada (stew and beans). Pair your dinner with Rio Cantina�s signature cocktails, including the infamous caipirinha, garnished with refreshing sugarcane and lime. """) fileprivate static let mercadoCafe = Restaurant(itemID: "restaurant.brazil.mercado", name: "Mercado Caf�", location: CLLocation(latitude: -22.898290, longitude: -43.181501), priceRange: PriceRange(lower: 10, upper: 20, localeIdentifier: "pt_BR"), iconName: "??", imageName: "mercado_cafe", altText: "Small cafe seating with natural light coming through the archway entrance to this restaurant.", caption: """ Need a relaxing start to your day? Be sure to stop by the world famous Mercado Caf�. The peaceful ambiance and delicious coffee creates the perfect place for visitors and locals to enjoy a quick bite and a calming start to the day. """) // MARK: Tanzania fileprivate static let cafeChipsi = Restaurant(itemID: "restaurant.tanzania.chipsi", name: "Cafe Chipsi", location: CLLocation(latitude: -6.820995, longitude: 39.272121), priceRange: PriceRange(lower: 900, upper: 2_300, localeIdentifier: "sw_TZ"), iconName: "??", imageName: "city_cafe", altText: "A quiet looking cafe with wooden tables and a vibrant painting of a woman's face in the background", caption: """ You will find Cafe Chipsi tucked away on a quiet street in Tanzania�s largest city, Dar es Salaam. Cafe Chipsi serves Tanzania�s traditional cuisines with a twist. Try their chipsi mayai, literally �chips and eggs,� a classic Tanzanian comfort food. You can enjoy this meal like the locals might, with a splash of ketchup, or get it �California Style� with pea sprouts, avocado, and feta cheese. """) fileprivate static let onTheRocks = Restaurant(itemID: "restaurant.tanzania.ontherocks", name: "On the Rocks", location: CLLocation(latitude: -6.1376, longitude: 39.2092), priceRange: PriceRange(lower: 4_000, upper: 10_000, localeIdentifier: "sw_TZ"), iconName: "?", imageName: "on_the_rock", altText: "A restaurant on a rock located behind the incoming tide. You'll have to get your feet wet to get here at certain times of day!", caption: """ Try out On the Rocks for your fix of traditional Zanzibari cuisine while on the island. The restaurant is only accessible by foot at low tide, so plan your trip accordingly. Enjoy a local favorite, the Pepper Shark, featuring fresh-caught shark seasoned with pepper. Or try the world-famous Pweza Wa Nazi, or octopus in coconut milk. Not feeling like seafood? Some might say you came to the wrong restaurant, but we recommend the Zanzibar Pizza, a fried dough pocket filled with meat, cheese, veggies, and an egg. """) fileprivate static let cafeSafari = Restaurant(itemID: "restaurant.tanzania.cafesafari", name: "Cafe Safari", location: CLLocation(latitude: -2.193922, longitude: 33.9683), priceRange: PriceRange(lower: 5_000, upper: 12_000, localeIdentifier: "sw_TZ"), iconName: "?", imageName: "safari_lunch", altText: "Elephants are literally sharing your lunch at this one-of-a-kind dining experience", caption: """ Get your camera ready for this magical dinner experience. Dine al fresco with your favorite safari characters after a long day out on the Serengeti. Safari Lodge serves up many of Tanzania�s traditional dishes. It wouldn�t be a trip to Tanzania without trying ugali, a porridge made from maize, similar to polenta. To eat, break off a small piece of ugali, roll it into a ball, and make a small depression in the ball using your thumb to fashion it into a spoon. Then, use your ugali spoon to scoop up your stew. Be warned, elephants need up to 375 lbs. of food per day and spend about 80% of their day feeding, so keep your plate under close watch! """) // MARK: Spain fileprivate static let lasRamblas = Restaurant(itemID: "restaurant.spain.lasramblas", name: "Las Ramblas Market", location: CLLocation(latitude: 41.3567, longitude: 2.1368), priceRange: PriceRange(lower: 3, upper: 20, localeIdentifier: "en_ES"), iconName: "?", imageName: "barcelona_market", altText: "A wide assortment of perfectly ripened fruits and vegetables", caption: """ Las Ramblas is (are?) a boulevard about 1 mile long running up from the Port (near the cruise ship terminal) at its southern end to La Pla�a de Catalunya and continuing unofficially through the downtown�s fine hotel and ($$$) shopping district at the northern end. Las Ramblas may be the first and greatest car-free pedestrian mall (dating back to when everybody was a pedestrian). Looking up towards Catalunya from the port along the Ramblas on your left is the Raval (contemporary tourist) area and on your right is the Barri G�tic (or Gothic Quarter). Las Ramblas attracts as many Barcelonians as tourists. This distinction becomes a lot clearer at night time when the the latter south end of the Rambla typically sit down to dinner an hour or two before the former do. Past Catalunya, the restaurants on each side of the boulevard also set up service in its middle � very similar to arrangements some cities and restaurants have made recently in 2020/2021. The food is both very "typical" and innovative � Catalan cuisine was "le mode" in the nineties; no need torture yourselves about which restaurant to pick. """) fileprivate static let charcuterie = Restaurant(itemID: "restaurant.spain.charcuterie", name: "Charcuterie Bored", location: CLLocation(latitude: 39.857, longitude: -4.018), priceRange: PriceRange(lower: 10, upper: 20, localeIdentifier: "en_ES"), iconName: "?", imageName: "charcuterie", altText: "A closeup of a charcuterie plate, including salami, and what are likely mozarella poppers ", caption: "Have you ever considered the difference between tapas and charcuterie? Charcutuerie Bored promises to keep you waiting on small plates long enough that you begin to ask yourself these questions ��the kind that matter. Is this a squares-versus-rectangles situation? Or more of a Venn Diagram? Are charcuterie plural or singular? Or is it? Be sure to add Brazil's Pratos Petit to your bucket list so that you can ask yourself these same questions, but in reverse. When your adult-snacks do eventually arrive, don't forget to snap that bird's eye picture of the plate from above. Ca-caw!!") } extension Sight { // MARK: Japan fileprivate static let fuji = Sight(itemID: "sight.japan.fuji", name: "??? Mount Fuji", location: CLLocation(latitude: 35.3626, longitude: 138.7301), iconName: "?", imageName: "fuji", altText: "A snowcapped Fujisan with a branch of small blooming white flowers in the foreground.", caption: """ Mount Fuji is the perfect side-trip from Tokyo for the travelers who want to see the outdoors, and be challenged by them. Don't make the mistake of thinking Fuji is a day-hike. It's a dormant volcano rising up 12,388 feet and most hikers who summit from the bottom spend at least one night on the mountain to see the Coming of the Light as the sun rises across the mountain. """) fileprivate static let goldenPavilion = Sight(itemID: "sight.japan.golden", name: "??? Golden Pavilion", location: CLLocation(latitude: 35.0395, longitude: 135.73), iconName: "?", imageName: "golden_pavilion", altText: "The classic view of Kinkaku-ji ��the three story gilded pavilion from across the water", caption: """ Even back in 1393, people knew how to retire in style. In this case, it was Shogun Yoshimitsu Ashikaga who commissioned this villa to be converted to a temple upon his passing. The version of the building you see today was the same until a rare case of monastic arson in 1950. Enjoy a tranquil walk through the gardens surrounding the temple, then take the bus back to Kyoto and get yourself some crab legs as a reward for your day of sightseeing. """) fileprivate static let nara = Sight(itemID: "sight.japan.nara", name: "Nara", location: CLLocation(latitude: 34.6889, longitude: 135.84), iconName: "?", imageName: "nara", altText: "A fierce, majestic deer standing alone against the backdrop of To�dai-ji temple", caption: """ A short walk from the urban center of the city will get you to Nara park. The deer turn to 13 million annual visitors. Bowing for crackers brings tasty rewards. Rice bran crackers for X Yen are breakfast, lunch, and dinner for these guys. gluten free. Do your part and pick up any trash left behind by the hordes of tourism. """) // MARK: Brazil fileprivate static let redeemer = Sight(itemID: "sight.brazil.redeemer", name: "Cristo Redentor (Christ the Redeemer)", location: CLLocation(latitude: -22.9518, longitude: -43.2109), iconName: "??", imageName: "redeemer", altText: "The monumental statue of Jesus Christ rising above the clouds of Rio.", caption: """ Standing almost 30 meters tall, Christ the Redeemer welcomes all tourists with open arms. This statue, built by Brazilian engineer Heitor da Silva Costa, is one of the most monumental Art Deco statues in the world and deemed one of the seven wonders of the world. The open arms of the statue symbolizes peace and prosperity, something you may not be able to achieve on the 220 stairway hike up to view this wonder. """) fileprivate static let iguazuFalls = Sight(itemID: "sight.brazil.iguazu", name: "Igua�u Falls", location: CLLocation(latitude: -25.6925, longitude: -54.4331), iconName: "?", imageName: "iguazu_falls", altText: "A lush, deep green forest surrounds the roaring Igua�u falls on an overcast day.", caption: """ Enjoy the beautiful panoramic views of Igua�u Falls, bordering Brazil and Argentina. The shared falls signify the strength and unity of the bond between Brazil and Argentina. Residents and tourists experience breathtaking sights in Igua�u National Park. Take the one kilometer hike to the top of the falls to close your activity rings. """) fileprivate static let copacabana = Sight(itemID: "sight.brazil.ipanema", name: "Copacabana", location: CLLocation(latitude: -22.972123, longitude: -43.184477), iconName: "??", imageName: "ipanema", altText: "Two palms with a mountainside and a hint of a city behind them", caption: """ Your name doesn�t have to be named Lola to take a stroll down the beautiful Brazilian coast in Copacabana Beach. Famous for its 4 kilometer long coastline, Copacabana is home to over 60 beachside resorts all overlooking the breathtaking sunsets. Don�t forget to bring your yellow feathers for your hair and your favorite dress cut down to there. """) // MARK: Tanzania fileprivate static let kilimanjaro = Sight(itemID: "sight.tanzania.kilimajaro.", name: "Mount Kilimanjaro", location: CLLocation(latitude: -3.0994, longitude: 37.3557), iconName: "?", imageName: "kilimanjaro", altText: "TODO", caption: """ Not only is Kilimanjaro the highest mountain in Africa at 19,341 ft above sea level, it is the highest single free-standing mountain on earth! With an average summit success rate of 65%, you might consider Kilimanjaro as a relaxing alternative to Everest. Not so fast. Be warned, Kibo, Kilimanjaro�s highest crater, is dormant meaning an eruption is not out of the realm of possibility, . There are 7 established routes to the summit to choose from. Are cooking facilities, bathrooms, and electricity important to you? You might want to choose the Marangu Route. Enjoyed your climb? Let the other trekkers know by leaving your review in the summit book which can be found at the top of the mountain. """) fileprivate static let serengeti = Sight(itemID: "sight.tanzania.serengeti", name: "Serengeti National Park", location: CLLocation(latitude: -2.5153, longitude: 34.871), iconName: "?", imageName: "serengeti", altText: "TODO", caption: """ See Serengeti National Park, which is said to be one of the Seven Natural Wonders of Africa. The Serengeti is known for its large populations of the crowd-pleasing predators like lions, African leopards, hyenas, East African cheetahs, and even crocodiles. With this many predators, you might wonder how the prey can catch a break. The grazing mammals have a solution � strength in numbers � just take a leaf out of the wildebeests� book. Clocking in at 1.7 million herd members, the wildebeests migrate in a clockwise direction from the South, North to Kenya, and then back again. Go on safari to channel your inner-Simba as you witness the Great Wildebeest Migration as the herd searches for the greenest grazing pastures in Eastern Africa. """) fileprivate static let stoneTown = Sight(itemID: "sight.tanzania.stonetown", name: "Stone Town", location: CLLocation(latitude: -6.162, longitude: 39.192), iconName: "?", imageName: "stone_town", altText: "TODO", caption: """ You might wonder why Stone Town located on Tanzania�s Zanzibar Island is on UNESCO�s list of World Heritage sites, and it is not because it is the birthplace of Freddie Mercury. During the 19th century, Stone Town was a buzzing commercial center and immigration from frequent trading communities was encouraged by the Sultan. This immigration resulted in a unique blend of architectural elements of Arab, Persian, Indian, and European influence. Work your way through the narrow streets on foot to visit shops, bazaars, and mosques, or stroll along the scenic seafront to see the popular tourist attractions like the Sultan�s Palace, Forodhani Gardens, and St. Joseph�s Cathedral. """) // MARK: Spain fileprivate static let alhambra = Sight(itemID: "sight.spain.alhambra", name: "Alhambra", location: CLLocation(latitude: 38.898, longitude: -3.05355), iconName: "?", imageName: "alhambra", altText: "A view of the hillsides from under an archway of the Alhambra palace", caption: """ It is recommended you 'conquer' the city of Granada while in Spain, though you don't have to build a cathedral afterwards like Queen Isabella chose to do in 1523. Alhambra Palace was constructed between the XIII and XIV centuries from mostly stone and plaster (for the more ornate parts). Alhambra is not only a palace ��it includes the town, gardens, and some of the surrounding areas as well. If you are traveling with children, you'll want to check out the nearby water park, constructed in the XXI century from mostly steel and plastic (for the more slippery parts). """) fileprivate static let parqueG�ell = Sight(itemID: "sight.spain.guell", name: "Parque G�ell", location: CLLocation(latitude: 41.41428, longitude: 2.151571), iconName: "?", imageName: "park_guell", altText: "Looking out over the Pla�a de la Natura and low walls finished will a mosaic of ceramic shards", caption: """ Possibly the most intriguing and difficult-to-maintain strolling park in Europe, this early 20th century garden featured buildings, passages and sculptural figures and tiles designed by Antonio Gaudi. The celebrated artist/architect who was definitely on a different wavelength than his contemporaries if not on another planet. Allow 2 hours for a visit including seat-time overlooking the city from the curvaceous plaza at the top of the Parque. (The G�ell�s were one of Gaudi�s patient patrons.) """) fileprivate static let sagrada = Sight(itemID: "sight.spain.sagrada.familia", name: "La Sagrada Fam�lia", location: CLLocation(latitude: 41.40269, longitude: 2.17306), iconName: "??", imageName: "sagrada_familia", altText: "The pink and orange glow of the sunset illuminates the impressively striking facade of the cathedral", caption: """ Yes, it is possible to build a High Gothic (13th Century) Cathedral in the middle of a bustling, 20th/21st Century metropolis. This church, Gaudi�s obsession and masterpiece is ASTONISHING. This picture shows the building being worked on a few decades ago; it�s much taller and has many additional towers, now. You may judge the scale of the Church by the size of the trucks that appear near the bottom of the picture. Caution! Be careful walking in the Cathedral�s vicinity! Transfixed pedestrians are at risk from Barcelona�s zippy drivers. """) fileprivate static let cordoba = Sight(itemID: "sight.spain.cordoba", name: "Mosque of C�rdoba", location: CLLocation(latitude: 37.8788, longitude: -4.77953), iconName: "?", imageName: "cordoba", altText: "", caption: """ The Great Mosque of Cordoba was constructed in 785 CE, when C�rdoba was the capital of the Muslim-controlled region of Andalusia. It was expanded multiple times afterwards under his successors up to the late 10th century. The mosque was converted to a cathedral in 1236 when C�rdoba was captured by the Christian forces of Castile during the Reconquista. The structure itself underwent only minor modifications until a major building project in the 16th century inserted a new Renaissance cathedral nave and transept into the center of the building. Today, the building continues to serve as the city's cathedral and Mass is celebrated daily. The mosque, which covers many times the area of the church, is now a museum. Both are beautiful and discovering the Cathedral all of a sudden in the middle of the vast mosque is a thrill. The Whole Cathedral-in-Mosque is a tight fit with restaurants surrounding the other wall of it. There�s one at least that serves asparagus, tomato and roquefort ice cream echoing the melding of cultures within the walls. """) } extension RewardsProgram { fileprivate static var semiregularSoarer = RewardsProgram(itemID: "rewards.semiregularsoarer", name: "Semi-Regular Soarer", points: 65_536, iconName: "airplane", imageName: "airplane.circle") fileprivate static var diamondDubloon = RewardsProgram(itemID: "rewards.diamonddubloon", name: "Diamond Dubloon", points: 10_000, iconName: "seal", imageName: "seal.fill") fileprivate static var skyFurlongs = RewardsProgram(itemID: "rewards.skyfurlong", name: "Sky Furlongs", points: 10_696, iconName: "ruler", imageName: "ruler.fill") static let programs: [RewardsProgram] = [.semiregularSoarer, .diamondDubloon, .skyFurlongs] } ``` ## ItemPrintPageRenderer.swift ```swift /* Abstract: Uses an `AnyModelObject`'s data layout and draw a custom print representation. */ import UIKit import CoreGraphics class ItemPrintPageRenderer: UIPrintPageRenderer { let items: [AnyModelItem] class func canPrint(items: [AnyModelItem]) -> Bool { // We can only print if any of the items are printable. !printableItems(items: items).isEmpty } private class func printableItems(items: [AnyModelItem]) -> [AnyModelItem] { let result: [AnyModelItem] = items.reduce(into: []) { result, item in // If the item has any of the properties we know how to print, add it to the list if !item.name.isEmpty { result.append(item) } else if let caption = item.caption, !caption.isEmpty { result.append(item) } else if let imageName = item.imageName, !imageName.isEmpty { if UIImage(named: imageName) != nil { result.append(item) } } } return result } init(items: [AnyModelItem]) { let printableItems = ItemPrintPageRenderer.printableItems(items: items) self.items = printableItems super.init() } override var numberOfPages: Int { return items.count } override func drawContentForPage(at pageIndex: Int, in contentRect: CGRect) { // MARK: - Printer Helpers /// Draws `title` into `printingArea` /// - Parameters: /// - title: The `String` to draw /// - printingArea: The total area available for drawing. Drawing will occur in a rect contained by `printingArea`, /// or possibly be clipped depending on the configuration of the drawing context. /// - Returns: The rect now occupied by the drawn `title` string and its margins in `printingArea` coordinates. func draw(title: String, into printingArea: CGRect) -> CGRect { var titleTextFrame: CGRect let titleTopMargin = 40.0 if !title.isEmpty { let titleFontSize = 24.0 let titleBottomMargin = 30.0 let titleFont = UIFont(name: "Helvetica", size: titleFontSize) let titleParagraphStyle = NSMutableParagraphStyle() titleParagraphStyle.alignment = .center let titleAttributes = [NSAttributedString.Key.font: titleFont!, NSAttributedString.Key.paragraphStyle: titleParagraphStyle] let titleTextBounds = title.boundingRect(with: printingArea.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: titleAttributes, context: nil) titleTextFrame = CGRect(x: printingArea.midX - (titleTextBounds.width / 2.0), y: printingArea.origin.y + titleTopMargin, width: titleTextBounds.width, height: titleTextBounds.height + titleBottomMargin) title.draw(in: titleTextFrame, withAttributes: titleAttributes) titleTextFrame.origin.y = printingArea.origin.y titleTextFrame.size.height = titleTopMargin + titleTextBounds.height + titleBottomMargin } else { titleTextFrame = CGRect(origin: printingArea.origin, size: CGSize(width: printingArea.width, height: titleTopMargin)) } return titleTextFrame } /// Draws `caption` into `printingArea` /// - Parameters: /// - caption: The `String` to draw /// - printingArea: The total area available for drawing. Drawing will occur in a rect contained by `printingArea`, /// or possibly be clipped depending on the configuration of the drawing context. /// - Returns: The rect now occupied by the drawn `caption` string and its margins in `printingArea` coordinates. func draw(caption: String?, into printingArea: CGRect) -> CGRect { guard let caption = caption, !caption.isEmpty else { return .zero } let captionFontSize = 13.0 let captionSideMargins = 50.0 let captionBottomMargin = 20.0 var captionArea = printingArea captionArea.origin.x += captionSideMargins captionArea.size.width -= 2.0 * captionSideMargins let captionFont = UIFont(name: "Helvetica", size: captionFontSize) let captionAttributes = [NSAttributedString.Key.font: captionFont!] let captionTextBounds = caption.boundingRect(with: captionArea.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: captionAttributes, context: nil) captionArea.size.height = captionTextBounds.height + captionBottomMargin caption.draw(in: captionArea, withAttributes: captionAttributes) return captionArea } /// Draws `image` into `printingArea` /// - Parameters: /// - image: The `String` to draw /// - printingArea: The total area available for drawing. Drawing will occur in a rect contained by `printingArea`, /// or possibly be clipped depending on the configuration of the drawing context. /// - Returns: The entire now occupied by the drawn `title` string and its margins in `printingArea` coordinates. func draw(image: UIImage?, into printingArea: CGRect) -> CGRect { guard let image = image else { return .zero } var imageBox = printingArea var imageSize = image.size let scaleX = imageBox.width / imageSize.width let scaleY = imageBox.height / imageSize.height let scale = CGFloat.minimum(scaleX, scaleY) imageSize.width *= scale imageSize.height *= scale imageBox = CGRect(x: printingArea.midX - (imageSize.width / 2.0), // Horizontally center in the printing area y: printingArea.midY - (imageSize.height / 2.0), // Vertically center in the printing area width: imageSize.width, height: imageSize.height) image.draw(in: imageBox) return imageBox } // MARK: - Procedural Printing let item = items[pageIndex] let title = item.name let caption = item.caption let image: UIImage? = item.imageName.flatMap { UIImage(named: $0) } guard let context = UIGraphicsGetCurrentContext() else { Swift.debugPrint("No current context for printing") return } context.saveGState() // Title var printRect = addMargins(to: contentRect) let titleRect = draw(title: title, into: printRect) // Caption let titleDownShift = titleRect.height printRect.origin.y += titleDownShift printRect.size.height -= titleDownShift let captionRect = draw(caption: caption, into: printRect) // Image let captionDownShift = captionRect.height printRect.origin.y += captionDownShift printRect.size.height -= captionDownShift _ = draw(image: image, into: printRect) context.restoreGState() } private func addMargins(to contentRect: CGRect) -> CGRect { var printRect = contentRect printRect.origin.x += 36 printRect.origin.y += 36 printRect.size.width -= 72 printRect.size.height -= 72 return printRect } } ``` ## SceneDelegate.swift ```swift /* Abstract: The primary scene delegate. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? #if targetEnvironment(macCatalyst) private var toolbarModel: MainSceneToolbarModel = MainSceneToolbarModel() #endif func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let windowScene = (scene as? UIWindowScene) else { return } #if targetEnvironment(macCatalyst) windowScene.titlebar?.toolbarStyle = .unified // Give the Catalyst version a toolbar that adds the new Big Sur-look to Catalyst Apps let toolbar = NSToolbar(identifier: "main") toolbar.delegate = toolbarModel toolbar.displayMode = .iconOnly windowScene.titlebar!.toolbar = toolbar // Don't allow the scene to become too small windowScene.sizeRestrictions?.minimumSize = CGSize(width: 932, height: 470) #endif if let browserViewController = window?.rootViewController as? BrowserSplitViewController { NotificationCenter .default .addObserver(self, selector: #selector(browserStateChanged(_:)), name: .browserStateDidChange, object: browserViewController) } if let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity { configure(with: userActivity) } } func sceneDidDisconnect(_ scene: UIScene) { NotificationCenter.default.removeObserver(self) } // State restoration static let activityType = "Browse" private var currentUserActivity: NSUserActivity? = nil var browserViewController: BrowserSplitViewController? { window?.rootViewController as? BrowserSplitViewController } func updateUserActivity() { var newUserActivity: NSUserActivity? = nil if let browserViewController = browserViewController { let userActivity = NSUserActivity(activityType: Self.activityType) var userInfo = [String: Any]() let selectedItems = browserViewController.selectedItems let selectedItemIDs = selectedItems.map { $0.itemID as String } userInfo["selectedItems"] = selectedItemIDs if let detailItem = browserViewController.detailItem { userInfo["detailItem"] = detailItem.itemID as String } userActivity.userInfo = userInfo newUserActivity = userActivity } self.currentUserActivity = newUserActivity newUserActivity?.becomeCurrent() } func configure(with userActivity: NSUserActivity) { if let userInfo = userActivity.userInfo { let selectedItemIDs: [String]? = userInfo["selectedItems"] as? [String] let detailItemID: String? = userInfo["detailItem"] as? String if let browserViewController = browserViewController { let model = browserViewController.model let selectedItems = selectedItemIDs != nil ? selectedItemIDs!.compactMap { model.item(withID: $0) } : [] let detailItem = detailItemID != nil ? model.item(withID: detailItemID!) : nil browserViewController.restoreSelections(selectedItems: selectedItems, detailItem: detailItem) } } } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { configure(with: userActivity) } func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { return currentUserActivity } @objc func browserStateChanged(_ note: Notification) { updateUserActivity() } } #if targetEnvironment(macCatalyst) private class MainSceneToolbarModel: NSObject, NSToolbarDelegate { var shareItem: NSSharingServicePickerToolbarItem = { NSSharingServicePickerToolbarItem(itemIdentifier: .init("share")) }() func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [ NSToolbarItem.Identifier.toggleSidebar, NSToolbarItem.Identifier.primarySidebarTrackingSeparatorItemIdentifier, shareItem.itemIdentifier ] } func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [ NSToolbarItem.Identifier.toggleSidebar, NSToolbarItem.Identifier.flexibleSpace, NSToolbarItem.Identifier.primarySidebarTrackingSeparatorItemIdentifier, shareItem.itemIdentifier ] } func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { switch itemIdentifier { case shareItem.itemIdentifier: return shareItem default: return nil } } } #endif ``` ## SidebarViewController.swift ```swift /* Abstract: Displays a heterogeneous collection of model objects in a sidebar by wrapping them in `AnyModelItem` */ import UIKit extension Country { var allModelItems: [AnyModelItem] { [lodgings.map(AnyModelItem.init), restaurants.map(AnyModelItem.init), sights.map(AnyModelItem.init)].flatMap { $0 } } } /// Sidebar sections enum SidebarSection: Int, CaseIterable { case countries case rewardsPrograms // Per-country sections case lodging case restaurants case sights func children(for modelItem: AnyModelItem?) -> [AnyModelItem] { let sample = SampleData.data switch self { case .countries: return sample.countries.reduce(into: []) { result, country in result += country.allModelItems } case .rewardsPrograms: return sample.rewardsPrograms.map { AnyModelItem($0) } case .lodging: guard let country = modelItem?.country else { return [] } return country.lodgings.map { AnyModelItem($0) } case .restaurants: guard let country = modelItem?.country else { return [] } return country.restaurants.map { AnyModelItem($0) } case .sights: guard let country = modelItem?.country else { return [] } return country.sights.map { AnyModelItem($0) } } } } extension SidebarSection { var name: String { switch self { case .countries: return "Countries" case .rewardsPrograms: return "Rewards Programs" case .lodging: return "Lodging" case .restaurants: return "Restaurants" case .sights: return "Sights" } } var imageName: String { switch self { case .countries: return "globe" case .rewardsPrograms: return "giftcard" case .lodging: return "house" case .restaurants: return "person" case .sights: return "eye" } } } /// A collection item identifier struct SidebarItemIdentifier: Hashable { enum Kind { case expandableSection(SidebarSection) case expandableModelSection(AnyModelItem, SidebarSection) case expandableModelItem(AnyModelItem) case leafModelItem(AnyModelItem) var children: [AnyModelItem] { switch self { case .leafModelItem(let modelItem): return [modelItem] case .expandableSection(let section): return section.children(for: nil) case .expandableModelSection(let subsection, let section): return section.children(for: subsection) case .expandableModelItem(let modelItem): let country = modelItem.country! return country.lodgings.map(AnyModelItem.init) + country.restaurants.map(AnyModelItem.init) + country.sights.map(AnyModelItem.init) } } /// Convenience for getting a human-readable name for the parent-most item of a `Kind` fileprivate var name: String { switch self { case .leafModelItem(let leaf): return leaf.name case .expandableSection(let section): return section.name case .expandableModelSection(let betterName, _): return betterName.name case .expandableModelItem(let anotherBetterName): return anotherBetterName.name } } } var name: String { kind.name } let kind: Kind static func == (lhs: SidebarItemIdentifier, rhs: SidebarItemIdentifier) -> Bool { switch lhs.kind { case .expandableSection(let lhsSection): if case let Kind.expandableSection(rhsSection) = rhs.kind { return lhsSection == rhsSection } case .expandableModelSection(let lhsItem, let lhsSection): if case let Kind.expandableModelSection(rhsItem, rhsSection) = rhs.kind { return lhsItem.itemID == rhsItem.itemID && lhsSection == rhsSection } case .expandableModelItem(let lhsItem): if case let Kind.expandableModelItem(rhsItem) = rhs.kind { return lhsItem.itemID == rhsItem.itemID } case .leafModelItem(let lhsItem): if case let Kind.leafModelItem(rhsItem) = rhs.kind { return lhsItem.itemID == rhsItem.itemID } } return false } func hash(into hasher: inout Hasher) { switch kind { case .expandableSection(let section): hasher.combine("expandableSection") hasher.combine(section.rawValue) case .expandableModelSection(let modelItem, let section): hasher.combine("expandableModelSection") modelItem.hash(into: &hasher) hasher.combine(section.rawValue) case .expandableModelItem(let modelItem): hasher.combine("expandableModelItem") modelItem.hash(into: &hasher) case .leafModelItem(let modelItem): hasher.combine("modelItem") modelItem.hash(into: &hasher) } } } /// A collection view-based view controller that displays model items class SidebarViewController: UIViewController { private var browserSplitViewController: BrowserSplitViewController { self.splitViewController as! BrowserSplitViewController } private var selectedItemsCollection: ModelItemsCollection { browserSplitViewController.selectedItemsCollection } private var model: Model { browserSplitViewController.model } private lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.allowsMultipleSelection = true return collectionView }() private let layout: UICollectionViewLayout = { var configuration = UICollectionLayoutListConfiguration(appearance: .sidebar) return UICollectionViewCompositionalLayout.list(using: configuration) }() // MARK: - Cell Registrations // Top-level header item private lazy var topLevelSectionHeadingRegistration = UICollectionView.CellRegistration<DynamicImageCollectionViewCell, SidebarSection> { cell, indexPath, section in cell.update(with: section) cell.disclosureAccessory = .outlineDisclosure(options: .init(style: .header)) } // Intermediate, collapsible header item private lazy var intermediateSectionHeaderRegistration = UICollectionView.CellRegistration<DynamicImageCollectionViewCell, SidebarSection> { cell, indexPath, section in cell.update(with: section) cell.disclosureAccessory = .outlineDisclosure(options: .init(style: .cell)) } // Intermediate, collapsible item private lazy var disclosableSectionHeaderRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, AnyModelItem> { cell, indexPath, modelItem in var content = UIListContentConfiguration.sidebarCell() content.image = modelItem.iconImage content.text = modelItem.name cell.contentConfiguration = content cell.accessories = [.outlineDisclosure(options: .init(style: .cell))] } // Leaf item private lazy var leafItemRegistration = UICollectionView.CellRegistration<DynamicImageCollectionViewCell, AnyModelItem> { cell, indexPath, modelItem in cell.update(with: modelItem) } fileprivate private(set) lazy var dataSource: UICollectionViewDiffableDataSource<SidebarSection, SidebarItemIdentifier> = { // Create registrations upfront, not in the data source callbacks let leafItemRegistration = leafItemRegistration let topLevelSectionHeadingRegistration = topLevelSectionHeadingRegistration let intermediateSectionHeaderRegistration = intermediateSectionHeaderRegistration let disclosableSectionHeaderRegistration = disclosableSectionHeaderRegistration return UICollectionViewDiffableDataSource<SidebarSection, SidebarItemIdentifier>(collectionView: collectionView) { collectionView, indexPath, itemIdentifier -> UICollectionViewCell in guard let section = SidebarSection(rawValue: indexPath.section) else { fatalError("Unknown section: (indexPath.section)") } switch itemIdentifier.kind { case .expandableSection(let section): return collectionView.dequeueConfiguredReusableCell(using: topLevelSectionHeadingRegistration, for: indexPath, item: section) case .expandableModelSection(_, let section): return collectionView.dequeueConfiguredReusableCell(using: intermediateSectionHeaderRegistration, for: indexPath, item: section) case .expandableModelItem(let modelItem): return collectionView.dequeueConfiguredReusableCell(using: disclosableSectionHeaderRegistration, for: indexPath, item: modelItem) case .leafModelItem(let modelItem): return collectionView.dequeueConfiguredReusableCell(using: leafItemRegistration, for: indexPath, item: modelItem) } } }() override func loadView() { view = collectionView } private func addCountriesToSnapshot() { var countriesSectionSnapshot = NSDiffableDataSourceSectionSnapshot<SidebarItemIdentifier>() let countriesSectionHeaderIdentifier = SidebarItemIdentifier(kind: .expandableSection(.countries)) countriesSectionSnapshot.append([countriesSectionHeaderIdentifier]) let countries = model.countries let countryItems = countries.map { SidebarItemIdentifier(kind: .expandableModelItem(AnyModelItem($0))) } countriesSectionSnapshot.append(countryItems, to: countriesSectionHeaderIdentifier) for country in countries { let countryItemIdentifier = SidebarItemIdentifier(kind: .expandableModelItem(AnyModelItem(country))) let lodgingItemIdentifiers = country.lodgings.map { SidebarItemIdentifier(kind: .leafModelItem(AnyModelItem($0))) } if !lodgingItemIdentifiers.isEmpty { let countryLodgingIdentifier = SidebarItemIdentifier(kind: .expandableModelSection(AnyModelItem(country), .lodging)) countriesSectionSnapshot.append([countryLodgingIdentifier], to: countryItemIdentifier) countriesSectionSnapshot.append(lodgingItemIdentifiers, to: countryLodgingIdentifier) } let restaurantItemIdentifiers = country.restaurants.map { SidebarItemIdentifier(kind: .leafModelItem(AnyModelItem($0))) } if !restaurantItemIdentifiers.isEmpty { let countryRestaurantIdentifier = SidebarItemIdentifier(kind: .expandableModelSection(AnyModelItem(country), .restaurants)) countriesSectionSnapshot.append([countryRestaurantIdentifier], to: countryItemIdentifier) countriesSectionSnapshot.append(restaurantItemIdentifiers, to: countryRestaurantIdentifier) } let sightsItemIdentifiers = country.sights.map { SidebarItemIdentifier(kind: .leafModelItem(AnyModelItem($0))) } if !sightsItemIdentifiers.isEmpty { let countrySightsIdentifier = SidebarItemIdentifier(kind: .expandableModelSection(AnyModelItem(country), .sights)) countriesSectionSnapshot.append([countrySightsIdentifier], to: countryItemIdentifier) countriesSectionSnapshot.append(sightsItemIdentifiers, to: countrySightsIdentifier) } } dataSource.apply(countriesSectionSnapshot, to: .countries, animatingDifferences: false) } private func addRewardsToSnapshot() { // Rewards programs var rewardsProgramsSectionSnapshot = NSDiffableDataSourceSectionSnapshot<SidebarItemIdentifier>() let rewardsProgramsHeaderIdentifier = SidebarItemIdentifier(kind: .expandableSection(.rewardsPrograms)) rewardsProgramsSectionSnapshot.append([rewardsProgramsHeaderIdentifier]) let rewardsPrograms = model.rewardsPrograms let rewardsProgramsIdentifiers = rewardsPrograms.map { SidebarItemIdentifier(kind: .leafModelItem(AnyModelItem($0))) } rewardsProgramsSectionSnapshot.append(rewardsProgramsIdentifiers, to: rewardsProgramsHeaderIdentifier) dataSource.apply(rewardsProgramsSectionSnapshot, to: .rewardsPrograms, animatingDifferences: false) } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = dataSource collectionView.delegate = self // Top-level headers var snapshot = NSDiffableDataSourceSnapshot<SidebarSection, SidebarItemIdentifier>() snapshot.appendSections([.countries, .rewardsPrograms]) dataSource.apply(snapshot, animatingDifferences: false, completion: nil) addCountriesToSnapshot() addRewardsToSnapshot() // Pre-select rows that are already selected. This is useful during state restoration. let selectedItems = selectedItemsCollection.modelItems let itemIdentifiers = selectedItems.compactMap { SidebarItemIdentifier(kind: .leafModelItem($0)) } collectionView.expandParentsToShow(leafItemIdentifiers: itemIdentifiers, dataSource: dataSource) for selectedItem in selectedItems { if let index = dataSource.indexPath(for: SidebarItemIdentifier(kind: .leafModelItem(selectedItem))) { collectionView.selectItem(at: index, animated: false, scrollPosition: []) } } // Subscribe our cells to content size category changes so they can redraw their images. NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } @objc func contentSizeCategoryDidChange(_ note: Notification) { collectionView.visibleCells.forEach { cell in cell.setNeedsUpdateConfiguration() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) #if targetEnvironment(macCatalyst) self.navigationController?.isNavigationBarHidden = true #endif } } extension SidebarViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let sidebarItemIdentifier = dataSource.itemIdentifier(for: indexPath) else { return } let selectedModelItems = sidebarItemIdentifier.kind.children selectedItemsCollection.add(modelItems: selectedModelItems) let subtitle = selectedItemsCollection.subtitle(forMostRecentlySelected: sidebarItemIdentifier) // We want slightly different treatment of the title versus the subtitle in Catalyst. On iPadOS, the title will show in the app switcher. On // Catalyst, the subtitle will show beneath the window's title. #if targetEnvironment(macCatalyst) view.window?.windowScene?.subtitle = subtitle #else view.window?.windowScene?.title = subtitle #endif } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { guard let sidebarItemIdentifier = dataSource.itemIdentifier(for: indexPath) else { return } selectedItemsCollection.remove(modelItems: sidebarItemIdentifier.kind.children) let subtitle = selectedItemsCollection.subtitle(forMostRecentlySelected: nil) #if targetEnvironment(macCatalyst) view.window?.windowScene?.subtitle = subtitle #else view.window?.windowScene?.title = subtitle #endif } } private class DynamicImageCollectionViewCell: UICollectionViewListCell { var disclosureAccessory: UICellAccessory? = nil private var modelItem: AnyModelItem? { didSet { setNeedsUpdateConfiguration() } } private var section: SidebarSection? { didSet { setNeedsUpdateConfiguration() } } func update(with modelItem: AnyModelItem) { self.modelItem = modelItem } func update(with section: SidebarSection) { self.section = section } override func updateConfiguration(using state: UICellConfigurationState) { if let modelItem = modelItem { var newConfiguration = UIListContentConfiguration.sidebarCell().updated(for: state) newConfiguration.text = modelItem.name newConfiguration.image = modelItem.iconImage contentConfiguration = newConfiguration } else if let section = section { var newConfiguration = UIListContentConfiguration.sidebarHeader().updated(for: state) newConfiguration.text = section.name newConfiguration.image = section.imageName.image() contentConfiguration = newConfiguration } // Add checkmarks var accessories = [UICellAccessory]() #if !targetEnvironment(macCatalyst) if state.isSelected { accessories = [.checkmark()] } #endif if let disclosureAccessory = disclosureAccessory { accessories.append(disclosureAccessory) } self.accessories = accessories } } ``` ## SupplementaryViewController.swift ```swift /* Abstract: View Controller used as the supplementary column of our app's split view controller-based interface. `SupplementaryViewController` has to do some work to mainain selection states between the `UISplitViewController`'s `.primary` column and any detail view controllers. */ import UIKit private enum Section: Hashable { case main } protocol ImageNaming { /// An image present in the app's asset catalog. var imageName: String { get } } extension NSNotification.Name { static let selectedItemDidChange = NSNotification.Name("selectedItemDidChange") } /// A collection view-based view controller to display selected model items. class SupplementaryViewController: UIViewController, UICollectionViewDragDelegate { private let selectedItemsCollection: ModelItemsCollection private var browserViewController: BrowserSplitViewController? { splitViewController as? BrowserSplitViewController } var selectedItems: [AnyModelItem] { var items: [AnyModelItem] = [] if let selectedIndexPaths = collectionView.indexPathsForSelectedItems { items = selectedIndexPaths.reduce(into: items) { items, indexPath in if let item = dataSource.itemIdentifier(for: indexPath) { items.append(item) } } } return items } private lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) collectionView.allowsSelection = true collectionView.allowsMultipleSelection = true collectionView.delegate = self collectionView.dragInteractionEnabled = UIApplication.shared.supportsMultipleScenes collectionView.dragDelegate = UIApplication.shared.supportsMultipleScenes ? self : nil return collectionView }() private lazy var collectionViewLayout: UICollectionViewLayout = { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.323), heightDimension: .fractionalWidth(0.323)) let item = NSCollectionLayoutItem(layoutSize: itemSize) item.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .fixed(1), top: .fixed(1), trailing: .fixed(1), bottom: .fixed(1)) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(0.333)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) let config = UICollectionViewCompositionalLayoutConfiguration() return UICollectionViewCompositionalLayout(section: section, configuration: config) }() private lazy var itemCellRegistration = UICollectionView.CellRegistration<ImageCollectionViewConfigurationCell, AnyModelItem> { [unowned self] cell, indexPath, modelItem in cell.automaticallyUpdatesBackgroundConfiguration = false #if targetEnvironment(macCatalyst) cell.doubleTapCallback = { // Open a new window with the detail view for the double-clicked item. guard let doubleClickedItemIndexPath = collectionView.indexPath(for: cell) else { return } let options = UIScene.ActivationRequestOptions() options.collectionJoinBehavior = .preferred UIApplication.shared.requestSceneSessionActivation(nil, userActivity: modelItem.userActivity, options: options, errorHandler: nil) } #endif } private lazy var dataSource: UICollectionViewDiffableDataSource<Section, AnyModelItem> = { _ = itemCellRegistration return UICollectionViewDiffableDataSource<Section, AnyModelItem>(collectionView: collectionView) { [unowned self] cell, indexPath, modelItem in let cell = collectionView.dequeueConfiguredReusableCell(using: itemCellRegistration, for: indexPath, item: modelItem) let image = modelItem.image let imageView = UIImageView(image: image) imageView.backgroundColor = .tertiarySystemBackground imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFit imageView.layer.cornerRadius = 3.0 cell.contentView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] imageView.frame = cell.contentView.frame.insetBy(dx: 4, dy: 4) cell.contentView.addSubview(imageView) return cell } }() init(selectedItemsCollection: ModelItemsCollection) { self.selectedItemsCollection = selectedItemsCollection super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { // swiflint:disable:next overridden_super_call view = UIView() // Slightly inset the collection view to make drag-and-drop animations appear nicer with respect to padding around the drag preview. view.backgroundColor = .systemBackground view.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 3, leading: 2, bottom: 0, trailing: 2) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(collectionView) viewRespectsSystemMinimumLayoutMargins = false collectionView.translatesAutoresizingMaskIntoConstraints = false // This leads to nicer drag and drop visuals (the edges of cells near the edge aren't clipped when dragged). collectionView.clipsToBounds = false let margins = view.layoutMarginsGuide NSLayoutConstraint.activate([ collectionView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: margins.trailingAnchor), collectionView.bottomAnchor.constraint(equalTo: margins.bottomAnchor), collectionView.topAnchor.constraint(equalTo: margins.topAnchor) ]) } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = dataSource reloadSnapshot() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(itemCollectionChanged(_:)), name: .modelItemsCollectionDidChange, object: selectedItemsCollection) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } override func selectAll(_ sender: Any?) { for row in 0..<collectionView.numberOfItems(inSection: 0) { collectionView.selectItem(at: IndexPath(row: row, section: 0), animated: false, scrollPosition: .centeredVertically) } } @objc func itemCollectionChanged(_ note: Notification) { reloadSnapshot(animated: true) // If we've cleared all selected items, make sure to clear them on the split view controller. if collectionView.indexPathsForSelectedItems?.isEmpty ?? true { browserViewController?.detailItem = nil } } private func reloadSnapshot(animated: Bool = false) { var snapshot = NSDiffableDataSourceSnapshot<Section, AnyModelItem>() snapshot.appendSections([.main]) // Enhancement: Consider sorting by the item's name, or better yet by parent-item so animations are smoother. snapshot.appendItems(selectedItemsCollection.modelItems) dataSource.apply(snapshot, animatingDifferences: true) if let selectedItem = browserViewController?.detailItem { if let selectedItemIndex = dataSource.indexPath(for: selectedItem) { collectionView.selectItem(at: selectedItemIndex, animated: false, scrollPosition: []) } } else { collectionView.deselectAll() } } // MARK: - UICollectionViewDragDelegate func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let item = dataSource.itemIdentifier(for: indexPath) else { Swift.debugPrint("Missing Item at (indexPath)") return [] } let itemProvider = NSItemProvider() itemProvider.registerObject(item.userActivity, visibility: .all) let dragItem = UIDragItem(itemProvider: itemProvider) return [dragItem] } func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? { let previewParameters = UIDragPreviewParameters() previewParameters.backgroundColor = view.tintColor if let cell = collectionView.cellForItem(at: indexPath) { previewParameters.visiblePath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: 8) } return previewParameters } } // MARK: - UICollectionViewDelegate extension SupplementaryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let modelItem = dataSource.itemIdentifier(for: indexPath) else { return } if browserViewController?.detailItem != modelItem { browserViewController?.detailItem = modelItem } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if browserViewController?.detailItem != nil { browserViewController?.detailItem = nil } } } ``` ## DataModel+Caching.swift ```swift /* Abstract: Extension to ImageProviding to cache the computed downsampled color and image, indexed by itemID. This extension helps to improve peformance. */ import UIKit import Foundation private struct ObjectCache<T: NSObject> { private let cache: NSCache<NSString, T> init(cacheCountLimit: Int = 20) { let cache = NSCache<NSString, T>() cache.countLimit = cacheCountLimit self.cache = cache } func retrieveCachedObject(item: ImageProviding, objectLoader: () -> T?) -> T? { var retval: T? = nil if let itemIdentifierProviding = item as? ItemIdentifierProviding { let itemID = itemIdentifierProviding.itemID as NSString if let cachedObject = cache.object(forKey: itemID) { retval = cachedObject } else { if let object = objectLoader() { cache.setObject(object, forKey: itemID) retval = object } } } else { retval = objectLoader() } return retval } } private let colorCache = ObjectCache<UIColor>() extension ImageProviding { var downsampledColor: UIColor? { return colorCache.retrieveCachedObject(item: self) { image?.downsampledColor } } } ``` ## ModelItem+UIConvenience.swift ```swift /* Abstract: Methods that aren't part of the Model, but are used frequently interfacing with parts of the UI */ import Foundation import UIKit import LinkPresentation // MARK: Images from Image Names - /// Convenience accessors for looking up images extension AnyModelItem { var iconImage: UIImage? { guard let emojiOrName = iconName else { return nil } if emojiOrName.isSingleEmoji { return emojiOrName.image() } else { return UIImage(named: emojiOrName) ?? UIImage(systemName: emojiOrName) } } var image: UIImage? { imageName.flatMap { UIImage(named: $0) ?? UIImage(systemName: $0) } } } extension IconNameProviding { var iconImage: UIImage? { if iconName.isSingleEmoji { return iconName.image() } else { return UIImage(named: iconName) ?? UIImage(systemName: iconName) } } } extension ImageProviding { var image: UIImage? { UIImage(named: imageName) ?? UIImage(systemName: imageName) } } extension UIActivity.ActivityType { static let toggleFavorite = UIActivity.ActivityType("toggleFavorite") } class ToggleFavoriteActivity: UIActivity { let modelItem: AnyModelItem let label: String init(modelItem: AnyModelItem) { self.label = modelItem.isFavorite ? "Remove from favorites" : "Add to favorites" self.modelItem = modelItem super.init() } override var activityTitle: String? { label } override var activityType: UIActivity.ActivityType? { .toggleFavorite } override var activityImage: UIImage? { UIImage(systemName: modelItem.isFavorite ? "star.fill" : "star") } override func canPerform(withActivityItems activityItems: [Any]) -> Bool { return true } override func perform() { modelItem.isFavorite.toggle() } } // MARK: - UIActivityItemsConfigurationReading extension AnyModelItem: UIActivityItemsConfigurationReading { var itemProvidersForActivityItemsConfiguration: [NSItemProvider] { if let image = image { return [NSItemProvider(object: image)] } else { return [NSItemProvider(object: name as NSString)] } } func activityItemsConfigurationMetadata(key: UIActivityItemsConfigurationMetadataKey) -> Any? { if image != nil { switch key { case .title: return name as NSString case .messageBody: if let caption = caption { return caption as NSString } default: break } } return nil } func activityItemsConfigurationMetadataForItem(at: Int, key: UIActivityItemsConfigurationMetadataKey) -> Any? { var retval: LPLinkMetadata? = nil switch key { case UIActivityItemsConfigurationMetadataKey("linkPresentationMetadata"): if let image = image { let lpMetadata = LPLinkMetadata() lpMetadata.iconProvider = NSItemProvider(object: image) lpMetadata.title = name retval = lpMetadata } default: break } return retval } var applicationActivitiesForActivityItemsConfiguration: [UIActivity]? { return [ToggleFavoriteActivity(modelItem: self)] } } ``` ## String+Emoji.swift ```swift /* Abstract: Heuristical methods for rendering emoji as images. Note that this code is not guaranteed to fit all emoji into the drawn image. */ import UIKit extension String { func image(textStyle: UIFont.TextStyle = .body) -> UIImage? { if let image = UIImage(named: self) { return image } if let image = UIImage(systemName: self) { return image } let pointSize = UIFont.preferredFont(forTextStyle: textStyle).pointSize // Hueristic to fit the wider emoji like flags let padding: CGFloat = 0.35 * pointSize let paddedScaledSize = CGSize(width: pointSize + padding, height: pointSize + padding) let render = UIGraphicsImageRenderer(size: paddedScaledSize) return render.image { context in let rect = CGRect(origin: .init(x: 0, y: 0), size: paddedScaledSize) (self as NSString).draw(in: rect, withAttributes: [.font: UIFont.preferredFont(forTextStyle: textStyle)]) } } } extension Character { /// A simple emoji is one scalar and presented to the user as an Emoji var isSimpleEmoji: Bool { guard let firstScalar = unicodeScalars.first else { return false } return firstScalar.properties.isEmoji && firstScalar.value > 0x238C } /// Checks if the scalars will be merged into an emoji var isCombinedIntoEmoji: Bool { unicodeScalars.count > 1 && unicodeScalars.first?.properties.isEmoji ?? false } var isEmoji: Bool { isSimpleEmoji || isCombinedIntoEmoji } } extension String { var isSingleEmoji: Bool { count == 1 && containsEmoji } var containsEmoji: Bool { contains { $0.isEmoji } } } ``` ## UICollectionView+Convenience.swift ```swift /* Abstract: Utility methods for restoring a collection view to a certain selection state ��expanding parents of selected leaf nodes. */ import UIKit extension UICollectionView { func deselectAll() { indexPathsForSelectedItems?.forEach { indexPath in deselectItem(at: indexPath, animated: false) } } /// Expands all parent sections, and select the leaf identifiers func expandParentsToShow<Section: Hashable, Identifier: Hashable>( leafItemIdentifiers: [Identifier], dataSource: UICollectionViewDiffableDataSource<Section, Identifier>) { let topSnapshot = dataSource.snapshot() for itemIdentifier in leafItemIdentifiers { let sectionIdentifiers = topSnapshot.sectionIdentifiers for sectionIdentifier in sectionIdentifiers { var sectionSnapshot = dataSource.snapshot(for: sectionIdentifier) let itemWasExpanded = sectionSnapshot.recursivelyExpandToShow(item: itemIdentifier) dataSource.apply(sectionSnapshot, to: sectionIdentifier) if itemWasExpanded { break } } } } } extension NSDiffableDataSourceSectionSnapshot { mutating func recursivelyExpandToShow(item: ItemIdentifierType) -> Bool { var itemWasFound = false var itemsToExpand = [ItemIdentifierType]() var currentItem = item while contains(item), let parentItem = parent(of: currentItem) { itemWasFound = true itemsToExpand.append(parentItem) currentItem = parentItem } expand(itemsToExpand) return itemWasFound } } ``` ## UIImage+Downsample.swift ```swift /* Abstract: Utility method on UIImage to allow getting the effective arverage average color of an image */ import UIKit extension UIImage { /// A cached CIContext for downsampling because they can be expensive to create static private let ciContext = CIContext(options: [.workingColorSpace: NSNull()]) /// The average color of all of the image's pixels, including alpha. var downsampledColor: UIColor? { guard let inputImage = CIImage(image: self) else { Swift.debugPrint("Failed to initialize CIImage from UIImage") return nil } let inputExtent = CIVector(x: inputImage.extent.origin.x, y: inputImage.extent.origin.y, z: inputImage.extent.size.width, w: inputImage.extent.size.height) guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent]) else { Swift.debugPrint("Failed to create Core Image CIAreaAverage filter") return nil } guard let outputImage = filter.outputImage else { Swift.debugPrint("Failed to process image with filter") return nil } var bitmap = [UInt16](repeating: 0, count: 4) UIImage.ciContext.render(outputImage, toBitmap: &bitmap, rowBytes: 8, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .RGBA16, colorSpace: nil) return UIColor(red: CGFloat(bitmap[0]) / CGFloat(UInt16.max), green: CGFloat(bitmap[1]) / CGFloat(UInt16.max), blue: CGFloat(bitmap[2]) / CGFloat(UInt16.max), alpha: CGFloat(bitmap[3]) / CGFloat(UInt16.max)) } } ``` ## AppDelegate.swift ```swift /* Abstract: The AppDelegate. */ import SwiftUI import Cocoa private var sharedRing = Ring() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow? func applicationDidFinishLaunching(_ aNotification: Notification) { let content = NSHostingController( rootView: ContentView().environmentObject(sharedRing)) let window = NSWindow(contentViewController: content) window.setFrame(NSRect(x: 100, y: 100, width: 400, height: 300), display: true) self.window = window window.makeKeyAndOrderFront(self) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } // Main menu commands. @IBAction func newWedge(sender: NSControl) { withAnimation(.spring()) { // Holding Option adds 50 wedges as a single model update. if NSApp?.currentEvent?.modifierFlags.contains(.option) ?? false { for _ in 0 ..< 50 { sharedRing.addWedge(.random) } } else { sharedRing.addWedge(.random) } } } @IBAction func clearWedges(sender: NSControl) { withAnimation(.easeInOut(duration: 1.0)) { sharedRing.reset() } } } ``` ## ContentView.swift ```swift /* Abstract: The main view of the app. */ import SwiftUI struct ContentView: View { /// The description of the ring of wedges. @EnvironmentObject var ring: Ring var body: some View { // Create the button group. let overlayContent = VStack(alignment: .leading) { Button(action: newWedge) { Text("New Wedge") } Button(action: clear) { Text("Clear") } Spacer() Toggle(isOn: $ring.randomWalk) { Text("Randomize!") } } .padding() // Map over the array of wedge descriptions to produce the // wedge views, overlaying them via a ZStack. let wedges = ZStack { ForEach(ring.wedgeIDs, id: \.self) { wedgeID in WedgeView(wedge: self.ring.wedges[wedgeID]!) // use a custom transition for insertions and deletions. .transition(.scaleAndFade) // remove wedges when they're tapped. .onTapGesture { withAnimation(.spring()) { self.ring.removeWedge(id: wedgeID) } } } // Stop the window shrinking to zero when wedgeIDs.isEmpty. Spacer() } .flipsForRightToLeftLayoutDirection(true) .padding() // Wrap the wedge container in a drawing group so that // everything draws into a single CALayer using Metal. The // CALayer contents are rendered by the app, removing the // rendering work from the shared render server. let drawnWedges = wedges.drawingGroup() // Composite the ring of wedges under the buttons, over a // white-filled background. return drawnWedges .overlay(overlayContent, alignment: .topLeading) } // Button actions. func newWedge() { withAnimation(.spring()) { self.ring.addWedge(.random) } } func clear() { withAnimation(.easeInOut(duration: 1.0)) { self.ring.reset() } } } /// The custom view modifier defining the transition applied to each /// wedge view as it's inserted and removed from the display. struct ScaleAndFade: ViewModifier { /// True when the transition is active. var isEnabled: Bool // Scale and fade the content view while transitioning in and // out of the container. func body(content: Content) -> some View { return content .scaleEffect(isEnabled ? 0.1 : 1) .opacity(isEnabled ? 0 : 1) } } extension AnyTransition { static let scaleAndFade = AnyTransition.modifier( active: ScaleAndFade(isEnabled: true), identity: ScaleAndFade(isEnabled: false)) } ``` ## Model.swift ```swift /* Abstract: The data model. */ import SwiftUI import Combine /// The data model for a single chart ring. class Ring: ObservableObject { /// A single wedge within a chart ring. struct Wedge: Equatable { /// The wedge's width, as an angle in radians. var width: Double /// The wedge's cross-axis depth, in range [0,1]. var depth: Double /// The ring's hue. var hue: Double /// The wedge's start location, as an angle in radians. fileprivate(set) var start = 0.0 /// The wedge's end location, as an angle in radians. fileprivate(set) var end = 0.0 static var random: Wedge { return Wedge( width: .random(in: 0.5 ... 1), depth: .random(in: 0.2 ... 1), hue: .random(in: 0 ... 1)) } } /// The collection of wedges, tracked by their id. var wedges: [Int: Wedge] { get { if _wedgesNeedUpdate { /// Recalculate locations, to pack within circle. let total = wedgeIDs.reduce(0.0) { $0 + _wedges[$1]!.width } let scale = (.pi * 2) / max(.pi * 2, total) var location = 0.0 for id in wedgeIDs { var wedge = _wedges[id]! wedge.start = location * scale location += wedge.width wedge.end = location * scale _wedges[id] = wedge } _wedgesNeedUpdate = false } return _wedges } set { objectWillChange.send() _wedges = newValue _wedgesNeedUpdate = true } } private var _wedges = [Int: Wedge]() private var _wedgesNeedUpdate = false /// The display order of the wedges. @Published private(set) var wedgeIDs = [Int]() { willSet { objectWillChange.send() } } /// When true, periodically updates the data with random changes. @Published var randomWalk = false { didSet { updateTimer() } } /// The next id to allocate. private var nextID = 0 /// Adds a new wedge description to `array`. func addWedge(_ value: Wedge) { let id = nextID nextID += 1 wedges[id] = value wedgeIDs.append(id) } /// Removes the wedge with `id`. func removeWedge(id: Int) { if let indexToRemove = wedgeIDs.firstIndex(where: { $0 == id }) { wedgeIDs.remove(at: indexToRemove) wedges.removeValue(forKey: id) } } /// Clear all data. func reset() { if !wedgeIDs.isEmpty { wedgeIDs = [] wedges = [:] } } /// Randomly changes values of existing wedges. func randomize() { withAnimation(.spring(response: 2, dampingFraction: 0.5)) { wedges = wedges.mapValues { var wedge = $0 wedge.width = .random(in: max(0.2, wedge.width - 0.2) ... min(1, wedge.width + 0.2)) wedge.depth = .random(in: max(0.2, wedge.depth - 0.2) ... min(1, wedge.depth + 0.2)) return wedge } } } private var timer: Timer? /// Ensures the random-walk timer has the correct state. func updateTimer() { if randomWalk, timer == nil { randomize() timer = Timer.scheduledTimer( withTimeInterval: 1, repeats: true ) { [weak self] _ in self?.randomize() } } else if !randomWalk, let timer = self.timer { timer.invalidate() self.timer = nil } } } /// Extend the wedge description to conform to the Animatable type to /// simplify creation of custom shapes using the wedge. extension Ring.Wedge: Animatable { // Use a composition of pairs to merge the interpolated values into // a single type. AnimatablePair acts as a single interpolatable // values, given two interpolatable input types. // We'll interpolate the derived start/end angles, and the depth // and color values. The width parameter is not used for rendering, // and so doesn't need to be interpolated. typealias AnimatableData = AnimatablePair< AnimatablePair<Double, Double>, AnimatablePair<Double, Double>> var animatableData: AnimatableData { get { .init(.init(start, end), .init(depth, hue)) } set { start = newValue.first.first end = newValue.first.second depth = newValue.second.first hue = newValue.second.second } } } ``` ## WedgeView.swift ```swift /* Abstract: The Wedge view. */ import SwiftUI /// A view drawing a single color-filled ring wedge. struct WedgeView: View { var wedge: Ring.Wedge var body: some View { // Fill the wedge shape with its chosen gradient. WedgeShape(wedge).fill(wedge.foregroundGradient) } } struct WedgeShape: Shape { var wedge: Ring.Wedge init(_ wedge: Ring.Wedge) { self.wedge = wedge } func path(in rect: CGRect) -> Path { let points = WedgeGeometry(wedge, in: rect) var path = Path() path.addArc(center: points.center, radius: points.innerRadius, startAngle: .radians(wedge.start), endAngle: .radians(wedge.end), clockwise: false) path.addLine(to: points[.bottomTrailing]) path.addArc(center: points.center, radius: points.outerRadius, startAngle: .radians(wedge.end), endAngle: .radians(wedge.start), clockwise: true) path.closeSubpath() return path } var animatableData: Ring.Wedge.AnimatableData { get { wedge.animatableData } set { wedge.animatableData = newValue } } } /// Helper type for creating view-space points within a wedge. private struct WedgeGeometry { var wedge: Ring.Wedge var center: CGPoint var innerRadius: CGFloat var outerRadius: CGFloat init(_ wedge: Ring.Wedge, in rect: CGRect) { self.wedge = wedge center = CGPoint(x: rect.midX, y: rect.midY) let radius = min(rect.width, rect.height) * 0.5 innerRadius = radius / 4 outerRadius = innerRadius + (radius - innerRadius) * CGFloat(wedge.depth) } /// Returns the view location of the point in the wedge at unit- /// space location `unitPoint`, where the X axis of `p` moves around the /// wedge arc and the Y axis moves out from the inner to outer /// radius. subscript(unitPoint: UnitPoint) -> CGPoint { let radius = lerp(innerRadius, outerRadius, by: unitPoint.y) let angle = lerp(wedge.start, wedge.end, by: Double(unitPoint.x)) return CGPoint(x: center.x + CGFloat(cos(angle)) * radius, y: center.y + CGFloat(sin(angle)) * radius) } } /// Colors derived from the wedge hue for drawing. extension Ring.Wedge { var startColor: Color { return Color(hue: hue, saturation: 0.4, brightness: 0.8) } var endColor: Color { return Color(hue: hue, saturation: 0.7, brightness: 0.9) } var backgroundColor: Color { Color(hue: hue, saturation: 0.5, brightness: 0.8, opacity: 0.1) } var foregroundGradient: AngularGradient { AngularGradient( gradient: Gradient(colors: [startColor, endColor]), center: .center, startAngle: .radians(start), endAngle: .radians(end) ) } } /// Linearly interpolate from `from` to `to` by the fraction `amount`. private func lerp<T: BinaryFloatingPoint>(_ fromValue: T, _ toValue: T, by amount: T) -> T { return fromValue + (toValue - fromValue) * amount } ``` ## AppDelegate.swift ```swift /* Abstract: The application delegate. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } } ``` ## DestinationPost.swift ```swift /* Abstract: The post object. */ import UIKit struct Section: Identifiable { enum Identifier: String, CaseIterable { case featured = "Featured" case all = "All" } var id: Identifier var posts: [DestinationPost.ID] } struct Asset: Identifiable { static let noAsset: Asset = Asset(id: "none", isPlaceholder: false, image: UIImage(systemName: "airplane.circle.fill")!) var id: String var isPlaceholder: Bool var image: UIImage func withImage(_ image: UIImage) -> Asset { var this = self this.image = image return this } } struct DestinationPost: Identifiable { var id: String var region: String var subregion: String? var numberOfLikes: Int var assetID: Asset.ID init(id: String, region: String, subregion: String? = nil, numberOfLikes: Int, assetID: Asset.ID) { self.id = id self.region = region self.subregion = subregion self.numberOfLikes = numberOfLikes self.assetID = assetID } } ``` ## PostGridViewController.swift ```swift /* Abstract: The grid view controller. */ import UIKit import Combine class PostGridViewController: UIViewController { var dataSource: UICollectionViewDiffableDataSource<Section.ID, DestinationPost.ID>! = nil var collectionView: UICollectionView! = nil var sectionsStore: AnyModelStore<Section> var postsStore: AnyModelStore<DestinationPost> var assetsStore: AssetStore fileprivate var prefetchingIndexPathOperations = [IndexPath: AnyCancellable]() fileprivate let sectionHeaderElementKind = "SectionHeader" init(sectionsStore: AnyModelStore<Section>, postsStore: AnyModelStore<DestinationPost>, assetsStore: AssetStore) { self.sectionsStore = sectionsStore self.postsStore = postsStore self.assetsStore = assetsStore super.init(nibName: nil, bundle: .main) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Destinations" configureHierarchy() configureDataSource() setInitialData() } } extension PostGridViewController { private func configureHierarchy() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.backgroundColor = .systemBackground collectionView.prefetchDataSource = self view.addSubview(collectionView) } private func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration<DestinationPostCell, DestinationPost.ID> { [weak self] cell, indexPath, postID in guard let self = self else { return } let post = self.postsStore.fetchByID(postID) let asset = self.assetsStore.fetchByID(post.assetID) // Retrieve the token that's tracking this asset from either the prefetching operations dictionary // or just use a token that's already set on the cell, which is the case when a cell is being reconfigured. var assetToken = self.prefetchingIndexPathOperations.removeValue(forKey: indexPath) ?? cell.assetToken // If the asset is a placeholder and there is no token, ask the asset store to load it, reconfiguring // the cell in its completion handler. if asset.isPlaceholder && assetToken == nil { assetToken = self.assetsStore.loadAssetByID(post.assetID) { [weak self] in self?.setPostNeedsUpdate(postID) } } cell.assetToken = assetToken cell.configureFor(post, using: asset) } dataSource = UICollectionViewDiffableDataSource<Section.ID, DestinationPost.ID>(collectionView: collectionView) { (collectionView, indexPath, identifier) in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier) } let headerRegistration = createSectionHeaderRegistration() dataSource.supplementaryViewProvider = { collectionView, elementKind, indexPath in return collectionView.dequeueConfiguredReusableSupplementary(using: headerRegistration, for: indexPath) } } private func setPostNeedsUpdate(_ id: DestinationPost.ID) { var snapshot = self.dataSource.snapshot() snapshot.reconfigureItems([id]) self.dataSource.apply(snapshot, animatingDifferences: true) } private func setInitialData() { // Initial data var snapshot = NSDiffableDataSourceSnapshot<Section.ID, DestinationPost.ID>() snapshot.appendSections(Section.ID.allCases) for sectionType in Section.ID.allCases { let items = self.sectionsStore.fetchByID(sectionType).posts snapshot.appendItems(items, toSection: sectionType) } dataSource.apply(snapshot, animatingDifferences: false) } } extension PostGridViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { for indexPath in indexPaths { // Don't start a new prefetching operation if one is in process. guard prefetchingIndexPathOperations[indexPath] != nil else { continue } guard let destinationID = self.dataSource.itemIdentifier(for: indexPath) else { continue } let destination = self.postsStore.fetchByID(destinationID) prefetchingIndexPathOperations[indexPath] = assetsStore.loadAssetByID(destination.assetID) { [weak self] in // After the asset load completes, trigger a reconfigure for the item so the cell can be updated if // it is visible. self?.setPostNeedsUpdate(destinationID) } } } func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) { for indexPath in indexPaths { prefetchingIndexPathOperations.removeValue(forKey: indexPath)?.cancel() } } } extension PostGridViewController { private func createSectionHeaderRegistration() -> UICollectionView.SupplementaryRegistration<UICollectionViewListCell> { return UICollectionView.SupplementaryRegistration<UICollectionViewListCell>( elementKind: sectionHeaderElementKind ) { [weak self] supplementaryView, elementKind, indexPath in guard let self = self else { return } let sectionID = self.dataSource.snapshot().sectionIdentifiers[indexPath.section] supplementaryView.configurationUpdateHandler = { supplementaryView, state in guard let supplementaryCell = supplementaryView as? UICollectionViewListCell else { return } var contentConfiguration = UIListContentConfiguration.plainHeader().updated(for: state) contentConfiguration.textProperties.font = Appearance.sectionHeaderFont contentConfiguration.textProperties.color = UIColor.label contentConfiguration.text = sectionID.rawValue supplementaryCell.contentConfiguration = contentConfiguration supplementaryCell.backgroundConfiguration = .clear() } } } /// - Tag: Grid private func createLayout() -> UICollectionViewLayout { let sectionProvider = { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(350)) let item = NSCollectionLayoutItem(layoutSize: itemSize) // If there's space, adapt and go 2-up + peeking 3rd item. let columnCount = layoutEnvironment.container.effectiveContentSize.width > 500 ? 3 : 1 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(350)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: columnCount) group.interItemSpacing = .fixed(20) let section = NSCollectionLayoutSection(group: group) let sectionID = self.dataSource.snapshot().sectionIdentifiers[sectionIndex] section.interGroupSpacing = 20 if sectionID == .featured { section.decorationItems = [ .background(elementKind: "SectionBackground") ] let titleSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(Appearance.sectionHeaderFont.lineHeight)) let titleSupplementary = NSCollectionLayoutBoundarySupplementaryItem( layoutSize: titleSize, elementKind: self.sectionHeaderElementKind, alignment: .top) section.boundarySupplementaryItems = [titleSupplementary] section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 20, bottom: 20, trailing: 20) } else { section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 20, trailing: 20) } return section } let config = UICollectionViewCompositionalLayoutConfiguration() config.interSectionSpacing = 20 let layout = UICollectionViewCompositionalLayout( sectionProvider: sectionProvider, configuration: config) layout.register(SectionBackgroundDecorationView.self, forDecorationViewOfKind: "SectionBackground") return layout } } ``` ## SceneDelegate.swift ```swift /* Abstract: The scene delegate. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = PostGridViewController(sectionsStore: SampleData.sectionsStore, postsStore: SampleData.postsStore, assetsStore: SampleData.assetsStore) self.window = window window.makeKeyAndVisible() } } } ``` ## AssetStore.swift ```swift /* Abstract: The asset store. */ import Foundation import UIKit import Combine import UniformTypeIdentifiers extension Publisher where Failure == Never { // Like `replaceNil` but allows for passing a fallback publisher. func flatMapIfNil<DS: Publisher>(_ downstream: @escaping () -> DS) -> Publishers.FlatMap<AnyPublisher<DS.Output, DS.Failure>, Publishers.SetFailureType<Self, DS.Failure>> where DS.Output? == Output { return self.flatMap { opt in if let wrapped = opt { return Just(wrapped).setFailureType(to: DS.Failure.self).eraseToAnyPublisher() } else { return downstream().eraseToAnyPublisher() } } } } extension Publisher { /// Calls a function and returns the same output as upstream. func withOutput(execute: @escaping (Output) -> Void) -> Publishers.Map<Self, Output> { self.map { output in execute(output) return output } } } class AssetStore: ModelStore { static let placeholderFallbackImage = UIImage(systemName: "airplane.circle.fill")! private let lock = UnfairLock() private let preparedImages = MemoryLimitedCache() private let localAssets: FileBasedCache public let placeholderStore: FileBasedCache private let placeholderQueue = DispatchQueue(label: "com.apple.DestinationUnlocked.placeholderGenerationQueue", qos: .utility, attributes: [], autoreleaseFrequency: .workItem, target: nil) init(fileManager: FileManager = .default) { let cachesDirectory = try! fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("asset-images", isDirectory: true) let placeholdersDirectory = cachesDirectory.appendingPathComponent("placeholders", isDirectory: true) self.localAssets = FileBasedCache(directory: cachesDirectory, fileManager: fileManager) try! localAssets.createDirectoryIfNeeded() self.placeholderStore = PlaceholderStore(directory: placeholdersDirectory, imageFormat: UTType.jpeg, fileManager: fileManager) try! placeholderStore.createDirectoryIfNeeded() } func fetchByID(_ id: Asset.ID) -> Asset { if let image = preparedImages.fetchByID(id) { return image } return placeholderStore.fetchByID(id) ?? Asset(id: id, isPlaceholder: true, image: Self.placeholderFallbackImage) } func loadAssetByID(_ id: Asset.ID, completionHandler: (() -> Void)? = nil) -> AnyCancellable { if let assertion = preparedImages.takeAssertionForID(id) { completionHandler?() return assertion } var prepareImagesCancellation: AnyCancellable? = nil let downloadCancellation = prepareAssetIfNeeded(id: id) .sink { _ in // Take an assertion on the prepared image so that the cell // can easily access the image when it's reconfigured. prepareImagesCancellation = self.preparedImages.takeAssertionForID(id) completionHandler?() } return AnyCancellable { downloadCancellation.cancel() prepareImagesCancellation?.cancel() } } enum AssetError: Swift.Error { case preparingImageFailed } // Cache the current requests to ensure only one image is processing for // each asset at a time. private var requestsCache: [Asset.ID: Publishers.Share<AnyPublisher<Asset, Never>>] = [:] func prepareAssetIfNeeded(id: Asset.ID) -> Publishers.Share<AnyPublisher<Asset, Never>> { // Check the current requests for a match. if let request = requestsCache[id] { return request } // Start a new preparation if there is not a cached one. let publisher = self.prepareAsset(id: id) .subscribe(on: Self.networkingQueue) .receive(on: DispatchQueue.main) .handleEvents(receiveCompletion: { [weak self] _ in // When the operation is complete, remove the current request. self?.requestsCache.removeValue(forKey: id) }) .assertNoFailure("Downloading Asset (id: (id)") .receive(on: DispatchQueue.main) .eraseToAnyPublisher() .share() requestsCache[id] = publisher return publisher } func prepareAsset(id: Asset.ID) -> AnyPublisher<Asset, Error> { // First check the local cache for the image. return Just(self.localAssets.fetchByID(id)) // If there is no local asset, then download it from the server. .flatMapIfNil { self.makeDownloadRequest(id: id) } .tryMap { (asset: Asset) -> Asset in // Begin preparing the image on this queue (see `subscribe(on: DispatchQueue)`) guard let preparedImage = asset.image.preparingForDisplay() else { throw AssetError.preparingImageFailed } return asset.withImage(preparedImage) } // Cache the prepared image. .withOutput(execute: self.preparedImages.add(asset:)) .eraseToAnyPublisher() } private func makeDownloadRequest(id: Asset.ID) -> AnyPublisher<Asset, Error> { let url = self.localAssets.url(forID: id) return Self.makeAssetDownload(for: id, to: url) .tryMap { () -> Asset in // After download completes, ensure the local cache has // the asset. guard let asset = self.localAssets.fetchByID(id) else { throw CocoaError(.fileNoSuchFile) } self.placeholderQueue.async { // Start generating a placeholder image to use in the future. self.placeholderStore.addByMovingFromURL(url, forAsset: id) } return asset }.eraseToAnyPublisher() } // MARK: Sample Code Specific // Make a queue for fake network download to use. static let networkingQueue = DispatchQueue(label: "com.example.API.networking-queue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem, target: nil) // Start "downloading" the image. // For the sample code, pull the image from the main Bundle. // Replace this with an actual download from a server. For an example, see the `DownloadTaskPublisher` included with // this code. static func makeAssetDownload(for assetID: Asset.ID, to destinationURL: URL) -> AnyPublisher<Void, Error> { Just(assetID) .delay(for: .seconds(.random(in: 1..<6)), scheduler: self.networkingQueue) .share() .tryMap { assetID in guard let url = Bundle.main.url(forResource: assetID, withExtension: "jpg") else { throw CocoaError(.fileNoSuchFile) } try? FileManager.default.copyItem(at: url, to: destinationURL) } .eraseToAnyPublisher() } } ``` ## ModelStore.swift ```swift /* Abstract: The model store. */ import Foundation protocol ModelStore { associatedtype Model: Identifiable func fetchByID(_ id: Model.ID) -> Model } class AnyModelStore<Model: Identifiable>: ModelStore { private var models = [Model.ID: Model]() init(_ models: [Model]) { self.models = models.groupingByUniqueID() } func fetchByID(_ id: Model.ID) -> Model { return self.models[id]! } } extension Sequence where Element: Identifiable { func groupingByID() -> [Element.ID: [Element]] { return Dictionary(grouping: self, by: { $0.id }) } func groupingByUniqueID() -> [Element.ID: Element] { return Dictionary(uniqueKeysWithValues: self.map { ($0.id, $0) }) } } ``` ## SampleData.swift ```swift /* Abstract: The sample data. */ import Foundation struct SampleData { static let sectionsStore = AnyModelStore([ Section(id: .featured, posts: ["a", "b"]), Section(id: .all, posts: ["c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]) ]) static let postsStore = AnyModelStore([ DestinationPost(id: "a", region: "Peru", subregion: "Cusco", numberOfLikes: 31, assetID: "cusco"), DestinationPost(id: "b", region: "Caribbean", subregion: "Saint Lucia", numberOfLikes: 25, assetID: "st-lucia"), DestinationPost(id: "c", region: "Japan", subregion: "Tokyo", numberOfLikes: 16, assetID: "tokyo"), DestinationPost(id: "d", region: "Iceland", subregion: "Reykjav�k", numberOfLikes: 9, assetID: "iceland"), DestinationPost(id: "e", region: "France", subregion: "Paris", numberOfLikes: 14, assetID: "paris"), DestinationPost(id: "f", region: "Italy", subregion: "Capri", numberOfLikes: 11, assetID: "italy"), DestinationPost(id: "g", region: "Viet Nam", subregion: "Cat Ba", numberOfLikes: 17, assetID: "vietnam"), DestinationPost(id: "h", region: "New Zealand", subregion: nil, numberOfLikes: 5, assetID: "new-zealand"), DestinationPost(id: "i", region: "Indonesia", subregion: "Bali", numberOfLikes: 10, assetID: "bali"), DestinationPost(id: "j", region: "Ireland", subregion: "Cork", numberOfLikes: 21, assetID: "cork"), DestinationPost(id: "k", region: "Chile", subregion: "Patagonia", numberOfLikes: 9, assetID: "patagonia"), DestinationPost(id: "l", region: "Cambodia", subregion: nil, numberOfLikes: 14, assetID: "cambodia") ]) static let assetsStore = AssetStore() } ``` ## Appearance.swift ```swift /* Abstract: Defines some appearance constants. */ import Foundation import UIKit struct Appearance { static let sectionHeaderFont: UIFont = { let boldFontDescriptor = UIFontDescriptor .preferredFontDescriptor(withTextStyle: .largeTitle) .withSymbolicTraits(.traitBold)! return UIFont(descriptor: boldFontDescriptor, size: 0) }() static let postImageHeightRatio = 0.8 static let titleFont: UIFont = { let descriptor = UIFontDescriptor .preferredFontDescriptor(withTextStyle: .title1) .withSymbolicTraits(.traitBold)! return UIFont(descriptor: descriptor, size: 0) }() static let subtitleFont: UIFont = { let descriptor = UIFontDescriptor .preferredFontDescriptor(withTextStyle: .title2) .withSymbolicTraits(.traitBold)! return UIFont(descriptor: descriptor, size: 0) }() static let likeCountFont: UIFont = { let descriptor = UIFontDescriptor .preferredFontDescriptor(withTextStyle: .subheadline) .withDesign(.monospaced)! return UIFont(descriptor: descriptor, size: 0) }() } ``` ## FileBasedCache.swift ```swift /* Abstract: A cache that saves things in local files. */ import Foundation import UIKit import os import UniformTypeIdentifiers extension Logger { static let disabled = Logger(.disabled) static let `default` = Logger(.default) } class FileBasedCache: Cache { var fileManager: FileManager let imageFormat: UTType let directory: URL var logger: Logger var signposter: OSSignposter var isPlaceholderStore: Bool = false init(directory: URL, imageFormat: UTType = .jpeg, logger: Logger = .default, fileManager: FileManager = .default) { self.directory = directory self.logger = logger self.signposter = OSSignposter(logger: logger) self.imageFormat = imageFormat self.fileManager = fileManager } func createDirectoryIfNeeded() throws { try fileManager.createDirectory(at: self.directory, withIntermediateDirectories: true, attributes: nil) } func fetchByID(_ id: Asset.ID) -> Asset? { guard let image = UIImage(contentsOfFile: url(forID: id).path) else { return nil } return Asset(id: id, isPlaceholder: isPlaceholderStore, image: image) } func addByMovingFromURL(_ url: URL, forAsset id: Asset.ID) { precondition(isMatchingImageType(url), "Asset at (url) does not conform to (imageFormat)") try? fileManager.moveItem(at: url, to: self.url(forID: id)) } func clear() throws { try fileManager.removeItem(at: self.directory) try createDirectoryIfNeeded() } func isMatchingImageType(_ url: URL) -> Bool { return UTType( filenameExtension: url.pathExtension, conformingTo: imageFormat ) != nil } func url(forID id: Asset.ID) -> URL { return directory.appendingPathComponent(id).appendingPathExtension(for: imageFormat) } } ``` ## MemoryLimitedCache.swift ```swift /* Abstract: An in-memory cache. */ import UIKit import Combine import UniformTypeIdentifiers import os protocol Cache { associatedtype Model: Identifiable func fetchByID(_ id: Model.ID) -> Model? } extension Measurement where UnitType: Dimension { static var zero: Self { return .init(value: 0.0, unit: UnitType.baseUnit()) } } // Cache that tries to stay under a fixed memory limit. class MemoryLimitedCache: Cache { let memoryLimit: Measurement<UnitInformationStorage> private(set) var currentMemoryUsage = Measurement<UnitInformationStorage>.zero private let accessLock = UnfairLock() private var assets: [Asset.ID: Asset] = [:] // GuardedBy(accessLock) private var protectedAssetIDs: [Asset.ID: Int] = [:] // GuardedBy(accessLock) private var cancellation = [AnyCancellable]() private let logger: Logger private let signposter: OSSignposter // The default memory limit is 320 MB, which is very large. This is because there are // incredibly large assets for demonstration purposes. Rely on the Image resizing APIs // to scale images to the size needed and to save memory. init(limit: Measurement<UnitInformationStorage> = .init(value: 320, unit: .megabytes), logger: Logger = .default, signposter: OSSignposter? = nil) { self.memoryLimit = limit self.logger = logger self.signposter = signposter ?? OSSignposter(logger: logger) // Purge everything when app is under memory pressure. NotificationCenter.default .publisher(for: UIApplication.didReceiveMemoryWarningNotification) .sink { [weak self] _ in self?.purge() } .store(in: &cancellation) } func fetchByID(_ id: Asset.ID) -> Asset? { return accessLock.withLock { self.assets[id] } } // Asset with `id` will have its retention priority increased by 1 until `.cancel` is called. // - Returns: Cancellable which will decrease the priority by 1. func takeAssertionForID(_ id: Asset.ID) -> AnyCancellable? { let lock = self.accessLock.acquire() defer { lock.cancel() } guard self.assets[id] != nil else { return nil } let signpostID = signposter.makeSignpostID() let interval = signposter.beginInterval("Assertion", id: signpostID, "id=(id, attributes: "name=id")") protectedAssetIDs[id, default: 0] += 1 return AnyCancellable { [weak self] in guard let self = self else { return } self.accessLock.withLock { guard var retainCount = self.protectedAssetIDs[id] else { return } retainCount -= 1 // Passing nil to remove the id from `protectedAssetID`. self.protectedAssetIDs[id] = retainCount > 0 ? retainCount : nil } self.signposter.endInterval("Assertion", interval) } } func add(asset: Asset) { guard !asset.isPlaceholder else { logger.notice("Placeholder ((asset.id)) was sent to MemoryLimitedCache - Rejecting.") return } let estimatedMemory = self.estimatedMemory(of: asset) signposter.emitEvent("AddAsset", "assetID=(asset.id) memoryUsage=(estimatedMemory)") accessLock.withLock { // Remove the current asset if it exists. if let currentAsset = assets.removeValue(forKey: asset.id) { currentMemoryUsage = currentMemoryUsage - self.estimatedMemory(of: currentAsset) } if (currentMemoryUsage + estimatedMemory) >= memoryLimit { self._locked_purge(atLeast: estimatedMemory) } assets[asset.id] = asset currentMemoryUsage = currentMemoryUsage + estimatedMemory } } func purge(atLeast amount: Measurement<UnitInformationStorage>? = nil) { accessLock.withLock { _locked_purge(atLeast: amount) } } /// Estimates the cost of an image as `Width*Height*Channels`. /// - note: Image memory cost can vary depending on the image and only *preparedImages* are safe /// to estimate this way. func estimatedMemory(of asset: Asset) -> Measurement<UnitInformationStorage> { let image = asset.image return Measurement(value: Double(image.size.width * image.size.height * 3), unit: UnitInformationStorage.bytes) } private func _locked_purge(atLeast amount: Measurement<UnitInformationStorage>?) { let interval = signposter.beginInterval("Purge", "amount=(amount?.formatted() ?? "<all>", attributes: "name=amount")") defer { signposter.endInterval("Purge", interval, "newCount=(self.assets.count)") } guard var amountToGo = amount, amountToGo < currentMemoryUsage else { assets.removeAll() logger.log("Removed all. Saving (self.currentMemoryUsage)") currentMemoryUsage = .zero return } // Delete non-protected IDs first and then go through the others. let weightedKeys = self.assets.keys.map { ($0, self.protectedAssetIDs[$0, default: 0]) }.sorted(by: { $0.1 < $1.1 }).map { $0.0 } for id in weightedKeys { guard amountToGo > .zero else { break } let asset = self.assets.removeValue(forKey: id)! let estimatedMemory = self.estimatedMemory(of: asset) logger.trace("Removed (id) saving (estimatedMemory)") amountToGo = amountToGo - estimatedMemory currentMemoryUsage = currentMemoryUsage - estimatedMemory } } } ``` ## PlaceholderStore.swift ```swift /* Abstract: A store that generates placeholder images of larger assets. */ import Foundation import UniformTypeIdentifiers import CoreGraphics import os import ImageIO class PlaceholderStore: FileBasedCache { override init(directory: URL, imageFormat: UTType = .jpeg, logger: Logger = .default, fileManager: FileManager = .default) { super.init(directory: directory, imageFormat: imageFormat, logger: logger, fileManager: fileManager) self.isPlaceholderStore = true } override func addByMovingFromURL(_ url: URL, forAsset id: Asset.ID) { self.downsample(from: url, to: self.url(forID: id)) } func downsample(from sourceURL: URL, to destinationURL: URL) { signposter.withIntervalSignpost("PlaceholderDownsample", id: signposter.makeSignpostID()) { let readOptions: [CFString: Any] = [ // Save the new image and don't retain any extra memory. kCGImageSourceShouldCache: false ] guard let source = CGImageSourceCreateWithURL(sourceURL as CFURL, readOptions as CFDictionary) else { self.logger.error("Could not make image source from (sourceURL, privacy: .public)") return } let imageSize = sizeFromSource(source) let writeOptions = [ // When the image data is read, only read the data that is needed. kCGImageSourceSubsampleFactor: subsampleFactor(maxPixelSize: 100, imageSize: imageSize), // When data is written, ensure the longest dimension is 100px. kCGImageDestinationImageMaxPixelSize: 100, // Compress the image as much as possible. kCGImageDestinationLossyCompressionQuality: 0.0 // Merge the readOptions since `CGImageDestinationAddImageFromSource` is used // which both reads (makes a CGImage) and writes (saves to CGDestination). ].merging(readOptions, uniquingKeysWith: { aSide, bSide in aSide }) guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, imageFormat.identifier as CFString, 1, writeOptions as CFDictionary) else { self.logger.error("Could not make image destination for (destinationURL, privacy: .public)") return } CGImageDestinationAddImageFromSource(destination, source, 0, writeOptions as CFDictionary) CGImageDestinationFinalize(destination) } } func subsampleFactor(maxPixelSize: Int, imageSize: CGSize) -> Int { let largerDimensionMultiple = max(imageSize.width, imageSize.height) / CGFloat(maxPixelSize) let subsampleFactor = floor(log2(largerDimensionMultiple)) return Int(subsampleFactor.rounded(.towardZero)) } func sizeFromSource(_ source: CGImageSource) -> CGSize { let options: [CFString: Any] = [ // Get the image's size without reading it into memory. kCGImageSourceShouldCache: false ] let properties = CGImageSourceCopyPropertiesAtIndex( source, 0, options as NSDictionary ) as? [String: CFNumber] let width = properties?[kCGImagePropertyPixelWidth as String] ?? 1 as CFNumber let height = properties?[kCGImagePropertyPixelHeight as String] ?? 1 as CFNumber return CGSize(width: Int(truncating: width), height: Int(truncating: height)) } } ``` ## URLSession+DownloadTaskPublisher.swift ```swift /* Abstract: A URL session data task publisher. */ import Foundation import Combine extension URLSession { public func downloadTaskPublisher(for request: URLRequest) -> DownloadTaskPublisher { return DownloadTaskPublisher(request: request, session: self) } public func downloadTaskPublisher(for url: URL) -> DownloadTaskPublisher { self.downloadTaskPublisher(for: URLRequest(url: url)) } } public struct DownloadTaskPublisher: Publisher { public typealias Output = (url: URL, response: URLResponse) public typealias Failure = URLError public let request: URLRequest public let session: URLSession public init(request: URLRequest, session: URLSession) { self.request = request self.session = session } public func receive<S>(subscriber: S) where S: Subscriber, DownloadTaskPublisher.Failure == S.Failure, DownloadTaskPublisher.Output == S.Input { let subscription = DownloadTaskSubscription(parent: self, downstream: subscriber) subscriber.receive(subscription: subscription) } private typealias Parent = DownloadTaskPublisher private final class DownloadTaskSubscription<Downstream: Subscriber>: Subscription where Downstream.Input == Parent.Output, Downstream.Failure == Parent.Failure { private let lock: UnfairLock private var parent: Parent? private var downstream: Downstream? private var demand: Subscribers.Demand private var task: URLSessionDownloadTask! init(parent: Parent, downstream: Downstream) { self.lock = UnfairLock() self.parent = parent self.downstream = downstream self.demand = .max(0) self.task = parent.session.downloadTask(with: parent.request, completionHandler: handleResponse(url:response:error:)) } func request(_ demandingSubscribers: Subscribers.Demand) { precondition(demandingSubscribers > 0, "Invalid request of zero demand") let lockAssertion = lock.acquire() guard parent != nil else { // The lock has already been canceled so bail. lockAssertion.cancel() return } self.demand += demandingSubscribers guard let task = self.task else { lockAssertion.cancel() return } lockAssertion.cancel() task.resume() } private func handleResponse(url: URL?, response: URLResponse?, error: Error?) { let lockAssertion = lock.acquire() guard demand > 0, parent != nil, let downstreamResponse = downstream else { lockAssertion.cancel() return } parent = nil downstream = nil // Clear demand since this is a single shot shape. demand = .max(0) task = nil lockAssertion.cancel() if let url = url, let response = response, error == nil { _ = downstreamResponse.receive((url, response)) downstreamResponse.receive(completion: .finished) } else { let urlError = error as? URLError ?? URLError(.unknown) downstreamResponse.receive(completion: .failure(urlError)) } } func cancel() { let lockAssertion = lock.acquire() guard parent != nil else { lockAssertion.cancel() return } parent = nil downstream = nil demand = .max(0) let task = self.task self.task = nil lockAssertion.cancel() task?.cancel() } } } ``` ## UnfairLock.swift ```swift /* Abstract: A custom unfair lock implementation. */ import Foundation import UIKit import Combine final class UnfairLock { @usableFromInline let lock: UnsafeMutablePointer<os_unfair_lock> public init() { lock = .allocate(capacity: 1) lock.initialize(to: os_unfair_lock()) } deinit { lock.deallocate() } @inlinable @inline(__always) func withLock<Result>(body: () throws -> Result) rethrows -> Result { os_unfair_lock_lock(lock) defer { os_unfair_lock_unlock(lock) } return try body() } @inlinable @inline(__always) func withLock(body: () -> Void) { os_unfair_lock_lock(lock) defer { os_unfair_lock_unlock(lock) } body() } // Assert that the current thread owns the lock. @inlinable @inline(__always) public func assertOwner() { os_unfair_lock_assert_owner(lock) } // Assert that the current thread does not own the lock. @inlinable @inline(__always) public func assertNotOwner() { os_unfair_lock_assert_not_owner(lock) } private final class LockAssertion: Cancellable { private var _owner: UnfairLock init(owner: UnfairLock) { _owner = owner os_unfair_lock_lock(owner.lock) } __consuming func cancel() { os_unfair_lock_unlock(_owner.lock) } } func acquire() -> Cancellable { return LockAssertion(owner: self) } } ``` ## DestinationPostCell.swift ```swift /* Abstract: The cell that displays destinations. */ import UIKit import Combine extension CACornerMask { static func alongEdge(_ edge: CGRectEdge) -> CACornerMask { switch edge { case .maxXEdge: return [.layerMaxXMinYCorner, .layerMaxXMaxYCorner] case .maxYEdge: return [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] case .minXEdge: return [.layerMinXMinYCorner, .layerMinXMaxYCorner] case .minYEdge: return [.layerMinXMinYCorner, .layerMaxXMinYCorner] } } } class DestinationPostCell: UICollectionViewCell { // Set on each cell to track asset use. The cell will call cancel on the token when // preparing for reuse or when it deinitializes. public var assetToken: Cancellable? private let imageView = UIImageView() private let propertiesView = DestinationPostPropertiesView() private var validLayoutBounds: CGRect? = nil private var validSizeThatFits: CGSize? = nil override init(frame: CGRect) { super.init(frame: frame) imageView.contentMode = .scaleAspectFill imageView.backgroundColor = .secondarySystemBackground // Clips to Bounds because images draw outside their bounds // when a corner radius is set. imageView.clipsToBounds = true contentView.addSubview(imageView) contentView.addSubview(propertiesView) contentView.layer.cornerCurve = .continuous contentView.layer.cornerRadius = 12.0 self.pushCornerPropertiesToChildren() layer.shadowOpacity = 0.2 layer.shadowRadius = 6.0 } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { assetToken?.cancel() assetToken = nil } public func configureFor(_ post: DestinationPost, using asset: Asset) { imageView.image = asset.image propertiesView.post = post } override func prepareForReuse() { super.prepareForReuse() assetToken?.cancel() assetToken = nil } override func layoutSubviews() { super.layoutSubviews() let (imageFrame, propertiesFrame) = bounds.divided(atDistance: imageHeight(at: bounds.size), from: .minYEdge) imageView.frame = imageFrame propertiesView.frame = propertiesFrame // Setting a shadow path avoids costly offscreen passes. layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath previousBounds = self.bounds.size } // Override `sizeThatFits` so it can ask the `propertiesView`. override func sizeThatFits(_ size: CGSize) -> CGSize { var height = self.imageHeight(at: size) height += propertiesView.sizeThatFits(size).height return CGSize(width: size.width, height: height) } // A cache value to ensure it doesn't relay out. private var previousBounds: CGSize = .zero override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { // If it's already rendered at the proposed size it can just return. if previousBounds == layoutAttributes.size && !propertiesView.needsRelayout { return layoutAttributes } else { // This will call `sizeThatFits`. return super.preferredLayoutAttributesFitting(layoutAttributes) } } // Applying the corner radius to the children means not having to set `clipsToBounds` which // saves from having extra offscreen passes. private func pushCornerPropertiesToChildren() { imageView.layer.maskedCorners = contentView.layer.maskedCorners.intersection(.alongEdge(.minYEdge)) propertiesView.layer.maskedCorners = contentView.layer.maskedCorners.intersection(.alongEdge(.maxYEdge)) imageView.layer.cornerRadius = contentView.layer.cornerRadius propertiesView.layer.cornerRadius = contentView.layer.cornerRadius imageView.layer.cornerCurve = contentView.layer.cornerCurve propertiesView.layer.cornerCurve = contentView.layer.cornerCurve } private func imageHeight(at size: CGSize) -> CGFloat { return ceil(size.width * Appearance.postImageHeightRatio) } } ``` ## DestinationPostPropertiesView.swift ```swift /* Abstract: The destination post properties view. */ import UIKit class DestinationPostPropertiesView: UIView { private let titleLabel = UILabel() private let subtitleLabel = UILabel() private let likeCountLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .secondarySystemBackground titleLabel.font = Appearance.titleFont titleLabel.textColor = UIColor.label titleLabel.adjustsFontForContentSizeCategory = true subtitleLabel.font = Appearance.subtitleFont subtitleLabel.textColor = UIColor.secondaryLabel subtitleLabel.adjustsFontForContentSizeCategory = true likeCountLabel.font = Appearance.likeCountFont likeCountLabel.textColor = .secondaryLabel likeCountLabel.adjustsFontForContentSizeCategory = true addSubview(titleLabel) addSubview(subtitleLabel) addSubview(likeCountLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var needsRelayout: Bool = true var post: DestinationPost? { didSet { let header = self.headerValues(for: post) if header != self.headerValues(for: oldValue) { titleLabel.text = header.title subtitleLabel.text = header.subtitle // Only invalidate our current size // when the post changes. needsRelayout = true } let numberOfLikes = post?.numberOfLikes ?? 0 likeCountLabel.text = "(numberOfLikes) likes" } } private var previousBounds: CGSize = .zero override func layoutSubviews() { super.layoutSubviews() needsRelayout = false var layoutBounds = bounds.inset(by: layoutMargins) // Fills the remaining height with the `sizeThatFits` // the `view` func layout(view: UIView) { let fittingSize = CGSize(width: layoutBounds.width, height: UILabel.noIntrinsicMetric) let size = view.sizeThatFits(fittingSize) (view.frame, layoutBounds) = layoutBounds.divided(atDistance: size.height, from: .minYEdge) } layout(view: titleLabel) if subtitleLabel.text != nil { layout(view: subtitleLabel) } if likeCountLabel.text != nil { layout(view: likeCountLabel) } } override func sizeThatFits(_ size: CGSize) -> CGSize { let layoutMargin = self.layoutMargins let fittingSize = CGSize(width: size.width - layoutMargins.left - layoutMargins.right, height: UILabel.noIntrinsicMetric) var height = layoutMargin.top + layoutMargin.bottom height += titleLabel.sizeThatFits(fittingSize).height if subtitleLabel.text != nil { height += subtitleLabel.sizeThatFits(fittingSize).height } if likeCountLabel.text != nil { height += likeCountLabel.sizeThatFits(fittingSize).height } return CGSize(width: size.width, height: height) } private func headerValues(for post: DestinationPost?) -> (title: String?, subtitle: String?) { guard let post = post else { return (nil, nil) } if let subregion = post.subregion { return (subregion, post.region) } else { return (post.region, nil) } } } ``` ## SectionBackgroundView.swift ```swift /* Abstract: The section background view. */ import UIKit class SectionBackgroundDecorationView: UICollectionReusableView { private var gradientLayer = CAGradientLayer() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("not implemented") } } extension SectionBackgroundDecorationView { func configure() { gradientLayer.colors = [UIColor.systemBackground.withAlphaComponent(0).cgColor, UIColor.systemPink.withAlphaComponent(0.5).cgColor] layer.addSublayer(gradientLayer) gradientLayer.frame = layer.bounds } override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = layer.bounds } } ``` ## UITests.swift ```swift /* Abstract: UI performance tests. */ import XCTest class UITests: XCTestCase { override func setUpWithError() throws { // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() measure(metrics: [XCTOSSignpostMetric.scrollingAndDecelerationMetric]) { app.collectionViews.firstMatch.swipeUp(velocity: .fast) } } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } } ``` ## CustomLayoutSampleApp.swift ```swift /* Abstract: The app definition. */ import SwiftUI /// The entry point for the app that contains the app's single scene. /// /// The app creates an instance of ``Model`` using the /// [`StateObject`](https://developer.apple.com/documentation/swiftui/StateObject) /// property wrapper, and initializes it with ``Model/startData``. The app then /// shares the model with the entire view hierarchy using the /// [`environmentObject(_:)`](https://developer.apple.com/documentation/swiftui/view/environmentObject(_:)) /// view modifier. @main struct CustomLayoutSampleApp: App { // Initialize a data model with zero votes for everyone. @StateObject private var model: Model = Model.startData var body: some Scene { WindowGroup { ContentView() .environmentObject(model) } } } ``` ## MyEqualWidthHStack.swift ```swift /* Abstract: A custom horizontal stack that offers all its subviews the width of its largest subview. */ import SwiftUI /// A custom horizontal stack that offers all its subviews the width of its /// widest subview. /// /// This custom layout arranges views horizontally, giving each the width needed /// by the widest subview. /// /// ![Three rectangles arranged in a horizontal line. Each rectangle contains /// one smaller rectangle. The smaller rectangles have varying widths. Dashed /// lines above each of the container rectangles show that the larger rectangles /// all have the same width as each other.](voting-buttons) /// /// The custom stack implements the protocol's two required methods. First, /// ``sizeThatFits(proposal:subviews:cache:)`` reports the container's size, /// given a set of subviews. /// /// ```swift /// let maxSize = maxSize(subviews: subviews) /// let spacing = spacing(subviews: subviews) /// let totalSpacing = spacing.reduce(0) { $0 + $1 } /// /// return CGSize( /// width: maxSize.width * CGFloat(subviews.count) + totalSpacing, /// height: maxSize.height) /// ``` /// /// This method combines the largest size in each dimension with the horizontal /// spacing between subviews to find the container's total size. Then, /// ``placeSubviews(in:proposal:subviews:cache:)`` tells each of the subviews /// where to appear within the layout's bounds. /// /// ```swift /// let maxSize = maxSize(subviews: subviews) /// let spacing = spacing(subviews: subviews) /// /// let placementProposal = ProposedViewSize(width: maxSize.width, height: maxSize.height) /// var nextX = bounds.minX + maxSize.width / 2 /// /// for index in subviews.indices { /// subviews[index].place( /// at: CGPoint(x: nextX, y: bounds.midY), /// anchor: .center, /// proposal: placementProposal) /// nextX += maxSize.width + spacing[index] /// } /// ``` /// /// The method creates a single size proposal for the subviews, and then uses /// that, along with a point that changes for each subview, to arrange the /// subviews in a horizontal line with default spacing. struct MyEqualWidthHStack: Layout { /// Returns a size that the layout container needs to arrange its subviews /// horizontally. /// - Tag: sizeThatFitsHorizontal func sizeThatFits( proposal: ProposedViewSize, subviews: Subviews, cache: inout Void ) -> CGSize { guard !subviews.isEmpty else { return .zero } let maxSize = maxSize(subviews: subviews) let spacing = spacing(subviews: subviews) let totalSpacing = spacing.reduce(0) { $0 + $1 } return CGSize( width: maxSize.width * CGFloat(subviews.count) + totalSpacing, height: maxSize.height) } /// Places the subviews in a horizontal stack. /// - Tag: placeSubviewsHorizontal func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void ) { guard !subviews.isEmpty else { return } let maxSize = maxSize(subviews: subviews) let spacing = spacing(subviews: subviews) let placementProposal = ProposedViewSize(width: maxSize.width, height: maxSize.height) var nextX = bounds.minX + maxSize.width / 2 for index in subviews.indices { subviews[index].place( at: CGPoint(x: nextX, y: bounds.midY), anchor: .center, proposal: placementProposal) nextX += maxSize.width + spacing[index] } } /// Finds the largest ideal size of the subviews. private func maxSize(subviews: Subviews) -> CGSize { let subviewSizes = subviews.map { $0.sizeThatFits(.unspecified) } let maxSize: CGSize = subviewSizes.reduce(.zero) { currentMax, subviewSize in CGSize( width: max(currentMax.width, subviewSize.width), height: max(currentMax.height, subviewSize.height)) } return maxSize } /// Gets an array of preferred spacing sizes between subviews in the /// horizontal dimension. private func spacing(subviews: Subviews) -> [CGFloat] { subviews.indices.map { index in guard index < subviews.count - 1 else { return 0 } return subviews[index].spacing.distance( to: subviews[index + 1].spacing, along: .horizontal) } } } ``` ## MyEqualWidthVStack.swift ```swift /* Abstract: A custom vertical stack that offers all its subviews the width of its largest subview. */ import SwiftUI /// A custom vertical stack that offers all its subviews the width of its /// widest subview. /// /// This custom layout behaves almost identically to the ``MyEqualWidthHStack``, /// except that it arranges equal-width subviews in a vertical stack, rather /// than a horizontal one. It also implements a cache. /// /// ### Adding a cache /// /// The methods of the /// [`Layout`](https://developer.apple.com/documentation/swiftui/layout) /// protocol take a bidirectional `cache` /// parameter. The cache provides access to optional storage that's shared among /// all the methods of a particular layout instance. To demonstrate the use of a /// cache, this layout creates storage to share size and spacing calculations /// between its ``sizeThatFits(proposal:subviews:cache:)`` and /// ``placeSubviews(in:proposal:subviews:cache:)`` implementations. /// /// First, the layout defines a ``CacheData`` type for the storage: /// /// ```swift /// struct CacheData { /// let maxSize: CGSize /// let spacing: [CGFloat] /// let totalSpacing: CGFloat /// } /// ``` /// /// It then implements the protocol's optional ``makeCache(subviews:)`` /// method to do the calculations for a set of subviews, returning a value of /// the type defined above. /// /// ```swift /// func makeCache(subviews: Subviews) -> CacheData { /// let maxSize = maxSize(subviews: subviews) /// let spacing = spacing(subviews: subviews) /// let totalSpacing = spacing.reduce(0) { $0 + $1 } /// /// return CacheData( /// maxSize: maxSize, /// spacing: spacing, /// totalSpacing: totalSpacing) /// } /// ``` /// /// If the subviews change, SwiftUI calls the layout's /// ``updateCache(_:subviews:)`` method. The default implementation of that /// method calls ``makeCache(subviews:)`` again, which recalculates the data. /// Then the ``sizeThatFits(proposal:subviews:cache:)`` and /// ``placeSubviews(in:proposal:subviews:cache:)`` methods make /// use of their `cache` parameter to retrieve the data. For example, /// ``placeSubviews(in:proposal:subviews:cache:)`` reads the size and the /// spacing array from the cache. /// /// ```swift /// let maxSize = cache.maxSize /// let spacing = cache.spacing /// ``` /// /// Contrast this with ``MyEqualWidthHStack``, which doesn't use a /// cache, and instead calculates the size and spacing information every time /// it needs that information. /// /// > Note: Most simple layouts, including this one, don't /// gain much efficiency from using a cache. You can profile your app /// with Instruments to find out whether a particular layout type actually /// benefits from a cache. struct MyEqualWidthVStack: Layout { /// Returns a size that the layout container needs to arrange its subviews /// vertically with equal widths. func sizeThatFits( proposal: ProposedViewSize, subviews: Subviews, cache: inout CacheData ) -> CGSize { guard !subviews.isEmpty else { return .zero } // Load size and spacing information from the cache. let maxSize = cache.maxSize let totalSpacing = cache.totalSpacing return CGSize( width: maxSize.width, height: maxSize.height * CGFloat(subviews.count) + totalSpacing) } /// Places the subviews in a vertical stack. /// - Tag: placeSubviewsVertical func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout CacheData ) { guard !subviews.isEmpty else { return } // Load size and spacing information from the cache. let maxSize = cache.maxSize let spacing = cache.spacing let placementProposal = ProposedViewSize(width: maxSize.width, height: bounds.height) var nextY = bounds.minY + maxSize.height / 2 for index in subviews.indices { subviews[index].place( at: CGPoint(x: bounds.midX, y: nextY), anchor: .center, proposal: placementProposal) nextY += maxSize.height + spacing[index] } } /// A type that stores cached data. /// - Tag: CacheData struct CacheData { let maxSize: CGSize let spacing: [CGFloat] let totalSpacing: CGFloat } /// Creates a cache for a given set of subviews. /// /// When the subviews change, SwiftUI calls the ``updateCache(_:subviews:)`` /// method. The ``MyEqualWidthVStack`` layout relies on the default /// implementation of that method, which just calls this method again /// to recreate the cache. /// - Tag: makeCache func makeCache(subviews: Subviews) -> CacheData { let maxSize = maxSize(subviews: subviews) let spacing = spacing(subviews: subviews) let totalSpacing = spacing.reduce(0) { $0 + $1 } return CacheData( maxSize: maxSize, spacing: spacing, totalSpacing: totalSpacing) } /// Finds the largest ideal size of the subviews. private func maxSize(subviews: Subviews) -> CGSize { let subviewSizes = subviews.map { $0.sizeThatFits(.unspecified) } let maxSize: CGSize = subviewSizes.reduce(.zero) { currentMax, subviewSize in CGSize( width: max(currentMax.width, subviewSize.width), height: max(currentMax.height, subviewSize.height)) } return maxSize } /// Gets an array of preferred spacing sizes between subviews in the /// vertical dimension. private func spacing(subviews: Subviews) -> [CGFloat] { subviews.indices.map { index in guard index < subviews.count - 1 else { return 0 } return subviews[index].spacing.distance( to: subviews[index + 1].spacing, along: .vertical) } } } ``` ## MyRadialLayout.swift ```swift /* Abstract: A custom layout that arranges its views in a circle. */ import SwiftUI /// A custom layout that arranges its views in a circle. /// /// This container works as a general radial layout for any number of views. /// If you provide exactly three views in the layout's view builder and give /// the views rank values using the `Rank` view layout key, the layout rotates /// the view positions so that the views appear in rank order from top to /// bottom. /// /// ![Three filled circles placed at equal distances along the outline of a /// larger, empty circle. The outline of the larger circle uses a dashed /// line.](avatars) /// /// Like other custom layouts, this layout implements the two required methods. /// For ``sizeThatFits(proposal:subviews:cache:)``, the layout fills the /// available space by returning whatever size its container proposes. /// The layout uses the proposal's /// [`replacingUnspecifiedDimensions(by:)`](https://developer.apple.com/documentation/swiftui/proposedviewsize/replacingunspecifieddimensions(by:)) /// method to convert the proposal into a concrete size: /// /// ```swift /// proposal.replacingUnspecifiedDimensions() /// ``` /// /// Then, in the ``placeSubviews(in:proposal:subviews:cache:)`` method, the /// layout rotates a vector, translates the vector to the middle of the /// placement region, and uses that as the anchor for the subview: /// /// ```swift /// for (index, subview) in subviews.enumerated() { /// // Find a vector with an appropriate size and rotation. /// var point = CGPoint(x: 0, y: -radius) /// .applying(CGAffineTransform( /// rotationAngle: angle * Double(index) + offset)) /// /// // Shift the vector to the middle of the region. /// point.x += bounds.midX /// point.y += bounds.midY /// /// // Place the subview. /// subview.place(at: point, anchor: .center, proposal: .unspecified) /// } /// ``` /// /// The offset that the layout applies to the rotation accounts for the current /// rankings, placing higher-ranked pets closer to the top of the interface. The /// app stores ranks on the subviews using the /// [`LayoutValueKey`](https://developer.apple.com/documentation/swiftui/layoutvaluekey) /// protocol, and then reads the values to calculate the offset before placing /// views. struct MyRadialLayout: Layout { /// Returns a size that the layout container needs to arrange its subviews /// in a circle. /// /// This implementation uses whatever space the container view proposes. /// If the container asks for this layout's ideal size, it offers the /// the [`unspecified`](https://developer.apple.com/documentation/swiftui/proposedviewsize/unspecified) /// proposal, which contains `nil` in each dimension. /// To convert that to a concrete size, this method uses the proposal's /// [`replacingUnspecifiedDimensions(by:)`](https://developer.apple.com/documentation/swiftui/proposedviewsize/replacingunspecifieddimensions(by:)) /// method. /// - Tag: sizeThatFitsRadial func sizeThatFits( proposal: ProposedViewSize, subviews: Subviews, cache: inout Void ) -> CGSize { // Take whatever space is offered. proposal.replacingUnspecifiedDimensions() } /// Places the stack's subviews in a circle. /// - Tag: placeSubviewsRadial func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void ) { // Place the views within the bounds. let radius = min(bounds.size.width, bounds.size.height) / 3.0 // The angle between views depends on the number of views. let angle = Angle.degrees(360.0 / Double(subviews.count)).radians // Read the ranks from each view, and find the appropriate offset. // This only has an effect for the specific case of three views with // nonuniform rank values. Otherwise, the offset is zero, and it has // no effect on the placement. let ranks = subviews.map { subview in subview[Rank.self] } let offset = getOffset(ranks) for (index, subview) in subviews.enumerated() { // Find a vector with an appropriate size and rotation. var point = CGPoint(x: 0, y: -radius) .applying(CGAffineTransform( rotationAngle: angle * Double(index) + offset)) // Shift the vector to the middle of the region. point.x += bounds.midX point.y += bounds.midY // Place the subview. subview.place(at: point, anchor: .center, proposal: .unspecified) } } } extension MyRadialLayout { /// Finds the angular offset that arranges the views in rank order. /// /// This method produces an offset that tells a radial layout how much /// to rotate all of its subviews so that they display in order, from /// top to bottom, according to their ranks. The method only has meaning /// for exactly three laid-out views, initially positioned with the first /// view at the top, the second at the lower right, and the third in the /// lower left of the radial layout. /// /// - Parameter ranks: The rank values for the three subviews. Provide /// exactly three ranks. /// /// - Returns: An angle in radians. The method returns zero if you provide /// anything other than three ranks, or if the ranks are all equal, /// representing a three-way tie. private func getOffset(_ ranks: [Int]) -> Double { guard ranks.count == 3, !ranks.allSatisfy({ $0 == ranks.first }) else { return 0.0 } // Get the offset as a fraction of a third of a circle. // Put the leader at the top of the circle, and then adjust by // a residual amount depending on what the other two are doing. var fraction: Double if ranks[0] == 1 { fraction = residual(rank1: ranks[1], rank2: ranks[2]) } else if ranks[1] == 1 { fraction = -1 + residual(rank1: ranks[2], rank2: ranks[0]) } else { fraction = 1 + residual(rank1: ranks[0], rank2: ranks[1]) } // Convert the fraction to an angle in radians. return fraction * 2.0 * Double.pi / 3.0 } /// Gets the residual fraction based on what the other two ranks are doing. private func residual(rank1: Int, rank2: Int) -> Double { if rank1 == 1 { return -0.5 } else if rank2 == 1 { return 0.5 } else if rank1 < rank2 { return -0.25 } else if rank1 > rank2 { return 0.25 } else { return 0 } } } /// A key that the layout uses to read the rank for a subview. private struct Rank: LayoutValueKey { static let defaultValue: Int = 1 } extension View { /// Sets the rank layout value on a view. func rank(_ value: Int) -> some View { layoutValue(key: Rank.self, value: value) } } ``` ## Model.swift ```swift /* Abstract: A model that holds the pet data. */ import SwiftUI /// Storage for pet data. /// /// This model keeps a collection of ``Pet`` instances in the ``pets`` array. /// Each element tracks the vote count for a particular pet type. You can /// get summary information about the collection, like the total /// votes in the ``totalVotes`` property, and the rank of a specified pet /// using the ``rank(_:)`` method. /// /// To extend this app, you might share this model data in iCloud among a /// group of your app's users. class Model: ObservableObject { /// The pets that people can vote for. /// /// The model supports any number of pets, but parts of the app's user /// interface, especially the ``Profile`` view, work only for exactly three /// pets. @Published var pets: [Pet] /// Creates a new model object with the given set of pets. init(pets: [Pet]) { self.pets = pets } /// The sum of all votes across all pets. var totalVotes: Int { pets.reduce(0) { $0 + $1.votes } } /// A Boolean value that indicates whether all the pets have the same /// number of votes. var isAllWayTie: Bool { pets.allSatisfy { $0.votes == pets.first?.votes } } /// Calculates the rank of the specified pet. /// /// Because this method calculates the rank as the number of pets that have /// more votes than the specified pet, pets with the same number of votes /// have the same rank, resulting in a tie. func rank(_ pet: Pet) -> Int { pets.reduce(1) { $0 + (($1.votes > pet.votes) ? 1 : 0) } } } extension Model { /// A model instance to use for running the app, starting with zero votes /// for each contender. static var startData: Model = Model(pets: [ Pet(type: "Cat", color: .orange), Pet(type: "Goldfish", color: .yellow), Pet(type: "Dog", color: .brown) ]) /// A model instance to use for previews. /// /// This preview data assigns each pet the number of votes that matches its /// index to ensure that the preview looks the same all the time. /// If you prefer random data, use something like the following instead: /// /// ```swift /// model.pets[index].votes = Int.random(in: 0...100) /// ``` static var previewData: Model { let model = startData for index in model.pets.indices { model.pets[index].votes = index } return model } } ``` ## Pet.swift ```swift /* Abstract: A representation of a single pet. */ import SwiftUI /// A type of pet that people can vote for. struct Pet: Identifiable, Equatable { /// The name of the pet's type, like cat or dog. let type: String /// A color to use for the pet's avatar. let color: Color /// The total votes that the pet has received. var votes: Int = 0 /// An identifier that's unique for each pet. /// /// This structure uses the pet's type as the identifier. This assumes /// that no two pet's have the same type string. var id: String { type } } ``` ## Avatar.swift ```swift /* Abstract: A visual representation of the specified pet. */ import SwiftUI /// A visual representation of the specified pet. /// /// This view shows a colorful circle that contains the first letter of the /// pet's type. If you prefer an image for the avatar, you can add images for /// each pet type to the asset catalog using the pet's type name as the name /// of the image. Then replace the /// [`Circle`](https://developer.apple.com/documentation/swiftui/circle) /// and its modifiers in the code below with an /// [`Image`](https://developer.apple.com/documentation/swiftui/image) /// view like this: /// /// ```swift /// Image(pet.type) /// .resizable() /// .aspectRatio(contentMode: .fill) /// .clipShape(Circle()) /// .shadow(radius: 7) /// .frame(width: 100, height: 100) /// ``` struct Avatar: View { /// The pet to visualize. var pet: Pet var body: some View { Circle() .frame(width: 80, height: 80) .foregroundColor(pet.color) .shadow(radius: 3) .overlay { Text(pet.type.prefix(1).capitalized) // Use the first letter. .font(.system(size: 64)) } } } /// A SwiftUI preview provider for the avatar view. struct Avatar_Previews: PreviewProvider { static var previews: some View { HStack(spacing: 20) { ForEach(Model.previewData.pets) { pet in Avatar(pet: pet) } } } } ``` ## ButtonStack.swift ```swift /* Abstract: A view that shows buttons that people tap to vote for their favorite pet. */ import SwiftUI /// A view that shows buttons that people tap to vote for their favorite pet, /// arranged in a way that best fits available space. /// /// The size of the voting buttons that this view displays depends on the width /// of the text they contain. For people that speak another language or that /// use a larger text size, the horizontal arrangement provided by the default /// ``MyEqualWidthHStack`` layout might not fit in the display. So this view uses /// [`ViewThatFits`](https://developer.apple.com/documentation/swiftui/viewthatfits) /// to let SwiftUI choose between that and an alternative vertical arrangement /// provided by the ``MyEqualWidthVStack`` layout: /// /// ```swift /// ViewThatFits { // Choose the first view that fits. /// MyEqualWidthHStack { // Arrange horizontally if it fits... /// Buttons() /// } /// MyEqualWidthVStack { // ...or vertically, otherwise. /// Buttons() /// } /// } /// ``` /// /// - Tag: ButtonStack struct ButtonStack: View { var body: some View { ViewThatFits { // Choose the first view that fits. MyEqualWidthHStack { // Arrange horizontally if it fits... Buttons() } MyEqualWidthVStack { // ...or vertically, otherwise. Buttons() } } } } /// A set of buttons that enable voting for the different pets. /// /// This is just a list of buttons, and depends on its container view to do /// the layout. private struct Buttons: View { @EnvironmentObject private var model: Model var body: some View { ForEach($model.pets) { $pet in Button { pet.votes += 1 } label: { Text(pet.type) .frame(maxWidth: .infinity) // Expand to fill the offered space. } .buttonStyle(.bordered) } } } /// A SwiftUI preview provider for the voting buttons. struct ButtonStack_Previews: PreviewProvider { static var previews: some View { ButtonStack() .environmentObject(Model.previewData) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view for the app. */ import SwiftUI /// The root view of the app's one window group scene. struct ContentView: View { var body: some View { VStack { Spacer() Profile() Spacer() Leaderboard() Spacer() ButtonStack() .padding(.bottom) } } } /// A SwiftUI preview provider for the app's main content view. struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(Model.previewData) } } ``` ## Leaderboard.swift ```swift /* Abstract: A view that shows a grid of information about the contenders. */ import SwiftUI /// A view that shows a grid of information about the contenders. /// /// This view demonstrates how to use a /// [`Grid`](https://developer.apple.com/documentation/swiftui/grid) by /// drawing a leaderboard that shows vote counts and percentages. /// /// ![A grid with three rows and three columns. The first column and last column /// each contain rectangles in every cell. The middle column contains progress /// indicators with different amounts of progress.](leaderboard) /// /// The grid contains a /// [`GridRow`](https://developer.apple.com/documentation/swiftui/gridrow) inside a /// [`ForEach`](https://developer.apple.com/documentation/swiftui/foreach), /// where each view in the row creates a column cell. So the first view appears /// in the first column, the second in the second column, and so on. Because the /// [`Divider`](https://developer.apple.com/documentation/swiftui/divider) /// appears outside of a grid row instance, it creates a /// row that spans the width of the grid. /// /// ```swift /// Grid(alignment: .leading) { /// ForEach(model.pets) { pet in /// GridRow { /// Text(pet.type) /// ProgressView( /// value: Double(pet.votes), /// total: Double(max(1, model.totalVotes))) // Avoid dividing by zero. /// Text("(pet.votes)") /// .gridColumnAlignment(.trailing) /// } /// /// Divider() /// } /// } /// ``` /// /// The leaderboard initializes the grid with leading-edge alignment, which /// applies to every cell in the grid. Meanwhile, the /// [`gridColumnAlignment(_:)`](https://developer.apple.com/documentation/swiftui/view/gridcolumnalignment(_:)) /// view modifier that appears on the vote count cell overrides the alignment /// of cells in that column to use trailing-edge alignment. /// /// - Tag: Leaderboard struct Leaderboard: View { @EnvironmentObject private var model: Model var body: some View { Grid(alignment: .leading) { ForEach(model.pets) { pet in GridRow { Text(pet.type) ProgressView( value: Double(pet.votes), total: Double(max(1, model.totalVotes))) // Avoid dividing by zero. Text("(pet.votes)") .gridColumnAlignment(.trailing) } Divider() } } .padding() } } /// A SwiftUI preview provider for the leaderboard view. struct Leaderboard_Previews: PreviewProvider { static var previews: some View { Leaderboard() .environmentObject(Model.previewData) } } ``` ## Podium.swift ```swift /* Abstract: A background that shows bands for first, second, and third place. */ import SwiftUI /// A background that shows bands for first, second, and third place. /// /// The ``Profile`` view uses this view as a base, and places the pet avatars on /// top of it, arranged in a way that shows each pet's relative rank. struct Podium: View { var body: some View { VStack(spacing: 2) { ForEach(1..<4) { band($0) } } .aspectRatio(1.5, contentMode: .fit) } /// Draws one band with rank-specific characteristics. private func band(_ rank: Int) -> some View { Color.primary.opacity(0.1 * Double(rank)) .overlay(alignment: .leading) { rankText(rank) } .overlay(alignment: .trailing) { rankText(rank) } } /// Draws one rank text indicator. private func rankText(_ rank: Int) -> some View { Text("(rank)") .font(.system(size: 64)) .opacity(0.1) } } /// A SwiftUI preview provider for the podium's background view. struct Podium_Previews: PreviewProvider { static var previews: some View { Podium() } } ``` ## Profile.swift ```swift /* Abstract: A view that shows how contenders rank relative to one another. */ import SwiftUI /// A view that shows how contenders rank relative to one another. /// /// This view makes use of the custom radial layout ``MyRadialLayout`` to show /// pet avatars in a circle, arranged according to their ranks. The radial /// layout can calculate an offset that creates an appropriate arrangement for /// all but one set of rankings: there's no way to show a three-way tie with the /// avatars in a circle. To resolve this, the view detects this condition and /// and uses it to put the avatars in a line instead using the /// [`HStackLayout`](https://developer.apple.com/documentation/swiftui/hstacklayout) /// type, which is a version of the built-in /// [`HStack`](https://developer.apple.com/documentation/swiftui/hstack) /// that conforms to the /// [`Layout`](https://developer.apple.com/documentation/swiftui/layout) /// protocol. To transition between the layout types, the app uses the /// [`AnyLayout`](https://developer.apple.com/documentation/swiftui/anylayout) /// type. /// /// ```swift /// let layout = model.isAllWayTie ? AnyLayout(HStackLayout()) : AnyLayout(MyRadialLayout()) /// /// Podium() /// .overlay(alignment: .top) { /// layout { /// ForEach(model.pets) { pet in /// Avatar(pet: pet) /// .rank(model.rank(pet)) /// } /// } /// .animation(.default, value: model.pets) /// } /// ``` /// /// Because the structural identity of the views remains the same throughout, the /// [`animation(_:value:)`](https://developer.apple.com/documentation/swiftui/view/animation(_:value:)) /// view modifier creates animated transitions between layout types. The /// modifier also animates radial layout changes that result from changes in /// the rankings because the calculated offsets depend on the same pet data. /// /// > Important: This view assumes that the model contains exactly three pets. /// Any other number results in undefined behavior. /// /// - Tag: Profile struct Profile: View { @EnvironmentObject private var model: Model var body: some View { // Use a horizontal layout for a tie; use a radial layout, otherwise. let layout = model.isAllWayTie ? AnyLayout(HStackLayout()) : AnyLayout(MyRadialLayout()) Podium() .overlay(alignment: .top) { layout { ForEach(model.pets) { pet in Avatar(pet: pet) .rank(model.rank(pet)) } } .animation(.default, value: model.pets) } } } /// A SwiftUI preview provider for the view that shows the ranked, pet avatars. struct Profile_Previews: PreviewProvider { static var previews: some View { Profile() .environmentObject(Model.previewData) } } ``` ## Asset.swift ```swift /* Abstract: The data model for an asset. */ import SwiftUI enum Asset: String, CaseIterable, Identifiable { case beach case botanist case camping case coffeeberry case creek case discovery case hillside case lab case lake case landing case ocean case park case poppy case samples case yucca var id: Self { self } var title: String { rawValue.capitalized } var landscapeImage: Image { Image(rawValue + "_landscape") } var portraitImage: Image { Image(rawValue + "_portrait") } var keywords: [String] { switch self { case .beach: ["nature", "photography", "sea", "ocean", "beach", "sunset", "sea", "waves", "boats", "sky"] case .camping: ["nature", "photography", "forest", "insects", "dark", "camping", "plants"] case .creek: ["creek", "nature", "photography", "plants", "petal", "flower"] case .hillside: ["hillside", "cliffs", "sea", "ocean", "waves", "surf", "rocks", "nature", "photography", "grass", "plants"] case .ocean: ["sea", "ocean", "nature", "photography", "waves", "island", "sky"] case .park: ["nature", "photography", "park", "cactus", "plants", "sky"] case .lake: ["nature", "photography", "water", "turtles", "animals", "reeds"] case .coffeeberry: ["animated", "animation", "plants", "coffeeberry"] case .yucca: ["animated", "animation", "plants", "yucca"] case .poppy: ["animated", "animation", "plants", "poppy"] case .samples: ["animated", "animation", "plants", "samples"] case .discovery: ["botanist", "discovery", "science", "animated", "animation", "character", "cave", "mushrooms", "fungus", "fungi", "plants"] case .lab: ["botanist", "science", "lab", "laboratory", "animated", "animation", "character", "window", "plants"] case .botanist: ["botanist", "science", "animated", "animation", "character", "rocks", "grass", "plants"] case .landing: ["botanist", "science", "animated", "animation", "character", "space", "planet"] } } static var lookupTable: [String: [Asset]] { var result: [String: [Asset]] = [:] for asset in allCases { for keyword in asset.keywords { result[keyword, default: []].append(asset) } } return result } } ``` ## CodeSampleArtwork.swift ```swift /* Abstract: The data model for generating sample code artwork. */ import SwiftUI let colors: [Color] = [ .red, .orange, .yellow, .green, .teal, .mint, .cyan, .blue, .indigo, .purple, .pink, .brown, .gray ] extension CGSize { static var moviePosterSize: Self { .init(width: 250, height: 375) } static var albumArtSize: Self { .init(width: 308, height: 308) } static var appIconSize: Self { .init(width: 400, height: 240) } static var topShelfSize: Self { .init(width: 360, height: 60) } } struct CodeSampleArtwork: View { var size: CGSize var color: Color init(size: CGSize = .init(width: 400, height: 240)) { self.size = size self.color = colors.randomElement()! } var body: some View { ZStack(alignment: .center) { Rectangle() .fill(color.gradient) .saturation(0.8) .aspectRatio(size.width / size.height, contentMode: .fill) Text("{ }") .font(.system(size: 160, design: .rounded)) .minimumScaleFactor(0.2) .foregroundColor(.white) .offset(y: -10) } } } #Preview("AppIcon") { CodeSampleArtwork() } #Preview("MoviePoster") { CodeSampleArtwork(size: .init(width: 250, height: 375)) } #Preview("AlbumCover") { CodeSampleArtwork(size: .init(width: 308, height: 308)) } ``` ## ButtonsView.swift ```swift /* Abstract: A view that shows button style options. */ import SwiftUI /// The `ButtonsView` provides a showcase of the various button styles available /// in tvOS. /// /// Of these, only the `.card` style is unique to Apple�TV. You can /// adjust each style using the `.buttonBorderShape()` modifier, though it /// affects the various styles differently. /// /// Try adding an accent color to the app's asset catalog and see how each /// button style uses it. struct ButtonsView: View { var body: some View { ScrollView(.vertical) { // Bordered buttons, the default platter-backed button style. HStack { Button("Bordered") {} Button("Bordered") {} .buttonBorderShape(.capsule) Button {} label: { Image(systemName: "movieclapper") } .buttonBorderShape(.circle) } Divider() // The default bordered button style, but this time with an // applied `.tint()`. This provides exactly the same behavior as // iOS. HStack { Button("Bordered (tint)") {} Button("Bordered (tint)") {} .buttonBorderShape(.capsule) Button {} label: { Image(systemName: "movieclapper") } .buttonBorderShape(.circle) } .tint(.blue) Divider() // The `.borderedProminent` style behaves exactly like `.bordered` // unless you add a tint. The system uses the tint color for // the button's unfocused platter for a more prominent appearance. // This provides the same appearance here as in iOS. HStack { Button("Prominent") {} Button("Prominent") {} .buttonBorderShape(.capsule) Button {} label: { Image(systemName: "movieclapper") } .buttonBorderShape(.circle) } .tint(.blue) .buttonStyle(.borderedProminent) Divider() /// The `.plain` button style behaves like a bordered button that /// has no platter until it receives focus. It appears to be just a /// text view until focus moves to it, at which point it lifts and /// gains a white platter. You can use this for a truncated /// description, where you click it to see a complete description /// in a full-screen overlay. HStack { Button("Plain") {} Button {} label: { Label("Labeled", systemImage: "movieclapper") } Button {} label: { Image(systemName: "movieclapper") } .buttonBorderShape(.circle) } .buttonStyle(.plain) Divider() // Borderless buttons locate the first `Image` instance within their // labels and apply the `.highlight` hover effect to that image. // They also apply a rounded-rectangle clipping shape to the image. // // The `.highlight` hover effect lifts its content when it has // focus, scaling it up and providing a drop shadow. It also places // a specular highlight on its content, and tilts as if on a motion // gimbal as you drag your finger across the touch surface of the // Siri Remote. HStack { Button {} label: { Image("discovery_portrait") .resizable() .frame(width: 250, height: 375) Text("Borderless Portrait") } Button {} label: { Image("discovery_landscape") .resizable() .frame(width: 400, height: 240) Text("Borderless Landscape") } // If your button doesn't contain an `Image` instance, or if it // contains more than one and you want the highlight effect to // apply to something other than the first instance, you can tag // any view manually with `.hoverEffect(.highlight)` to make it // the focus of the button's hover effect. Button {} label: { CodeSampleArtwork(size: .appIconSize) .frame(width: 400, height: 240) .hoverEffect(.highlight) Text("Custom Icon View") } // Applying a button border shape on a borderless button changes // the clipping shape to use for the highlighted image. The most // common occurrence of this is in the cast/crew lockups at the // bottom of a movie page on the Apple�TV app, where the app // clips the image to a circle. Button {} label: { Image(systemName: "person.circle") .font(.title) .background(Color.blue.grayscale(0.7)) // Places the effect on the image *and* its background. .hoverEffect(.highlight) Text("Shaped") } .buttonBorderShape(.circle) } .buttonStyle(.borderless) Divider() // The `.card` modifier provides a rounded rectangle clip shape by // default, and draws a platter behind its content with no applied // padding. This means that a `.card` button containing an image // is just that image with the corresponding clip shape and focus // behavior. // // When the button has focus, the content and platter grow, and the // platter becomes a little lighter and more opaque, though not as // much as the `.bordered` button style. The style provides a motion // effect that derives from the Siri Remote's touch surface, which // adjusts the button's offset on the x and y axes without any 3D // tilt effects. VStack { HStack { // Because the style doesn't apply padding by default (as it // does with bordered buttons), a plain label in a card // button has a platter that fits tightly around the label. Button {} label: { Label("A Card Button", systemImage: "button.horizontal") } // A card button containing an image doesn't have a visible // platter because the image covers it unless you mask it or // clip it independently of the button. Button {} label: { Image("discovery_landscape") .resizable() .frame(width: 400, height: 240) .overlay(alignment: .bottom) { Text("Image Card") } } // Placing text below the image reveals the platter. Button {} label: { VStack { Image("discovery_landscape") .resizable() .frame(width: 400, height: 240) Text("Vertical Card") } } } HStack { // Applying some padding to the button's label creates an // effect more like the Apple�TV app's search results, with // the content inset within the platter. Button {} label: { VStack { Image("discovery_landscape") .resizable() .frame(width: 400, height: 240) .clipShape(RoundedRectangle(cornerRadius: 12)) Text("Inset Card") } .padding(20) } // Setting the button border shape clips the entire card button, // including the platter and content. Button {} label: { VStack { Image("discovery_landscape") .resizable() .frame(width: 400, height: 240) .clipShape(RoundedRectangle(cornerRadius: 12)) Text("Circle Card") } .padding(20) } .buttonBorderShape(.circle) } } .buttonStyle(.card) Divider() // The card button style can be a good starting point for building // your own content lockups. The style simply displays its content // with a clip shape and background, and nothing else. This makes // it work particularly well when pairing it with a custom label // style, such as the `CardOverlayLabelStyle`. HStack { // A simple implementation with a single textual title. Button {} label: { Label { Text("Title at the bottom") .font(.caption.bold()) .foregroundStyle(.secondary) } icon: { Image("discovery_landscape") .resizable() .aspectRatio(400 / 240, contentMode: .fit) } } .frame(maxWidth: 400) // An example with a more complex label that places titles at // the top and bottom of the resulting lockup. Button {} label: { Label { VStack(alignment: .leading, spacing: 4) { Text("Title at the top") .font(.body.bold()) Text("Some subtitle text as well") .font(.caption) Spacer() Text("Additional info at the bottom") .font(.caption2) .foregroundStyle(.secondary) } } icon: { Image("discovery_landscape") .resizable() .aspectRatio(400 / 240, contentMode: .fit) } } .frame(maxWidth: 400) } .buttonStyle(.card) .labelStyle(CardOverlayLabelStyle()) } } } /// Implements a custom card lockup label style. /// /// This style takes the label's icon and uses it as a backdrop for its title. /// It overlays a subtle gradient on the icon to darken it toward the bottom, /// along with a 2 pt stroke, which it effectively transforms into a 1 pt /// inner-stroke when combining it with the card button's matching button border /// shape's clipping region. /// /// The style then places the label's title on top of the icon, with a little /// padding. The surrounding `ZStack` uses `.bottomLeading` alignment, so the /// title aligns toward the lower corner by default. struct CardOverlayLabelStyle: LabelStyle { func makeBody(configuration: Configuration) -> some View { ZStack(alignment: .bottomLeading) { configuration.icon .overlay { LinearGradient( stops: [ .init(color: .black.opacity(0.6), location: 0.1), .init(color: .black.opacity(0.2), location: 0.25), .init(color: .black.opacity(0), location: 0.4) ], startPoint: .bottom, endPoint: .top ) } .overlay { RoundedRectangle(cornerRadius: 12) .stroke(lineWidth: 2) .foregroundStyle(.quaternary) } configuration.title .padding(6) } } } #Preview { ButtonsView() } ``` ## CardContentView.swift ```swift /* Abstract: A view that shows content in a card. */ import SwiftUI struct CardContentView: View { var asset: Asset var body: some View { HStack(alignment: .top, spacing: 10) { asset.landscapeImage .resizable() .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 12)) VStack(alignment: .leading) { Text(asset.title) .font(.body) Text("Subtitle text goes here, limited to two lines") .font(.caption2) .foregroundStyle(.secondary) .lineLimit(2) Spacer(minLength: 0) HStack(spacing: 4) { ForEach(1..<4) { _ in Image(systemName: "ellipsis.rectangle.fill") } } .foregroundStyle(.secondary) } } } } #Preview { CardContentView(asset: .botanist) } ``` ## CardShelf.swift ```swift /* Abstract: A view that shows a shelf of cards. */ import SwiftUI struct CardShelf: View { var body: some View { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ForEach(Asset.allCases) { asset in Button {} label: { CardContentView(asset: asset) .padding([.leading, .top, .bottom], 12) .padding(.trailing, 20) .frame(maxWidth: .infinity) } .containerRelativeFrame(.horizontal, count: 3, spacing: 40) } } } .scrollClipDisabled() .buttonStyle(.card) } } #Preview { CardShelf() } ``` ## ContentView.swift ```swift /* Abstract: The main content view for the app. */ import SwiftUI struct ContentView: View { var body: some View { TabView { // The main content app landing page. Tab("Stack", systemImage: "line.3.horizontal") { StackView() } // A gallery of the different button styles available in tvOS. Tab("Buttons", systemImage: "button.horizontal") { ButtonsView() } // An example of a full-screen product description. Tab("Description", systemImage: "text.quote") { DescriptionView() } // A searchable content grid. Tab("Search", systemImage: "magnifyingglass") { SearchView() } } } } #Preview { ContentView() } ``` ## DescriptionView.swift ```swift /* Abstract: A view that shows an example of a content product page with an expandable text description. */ import SwiftUI let loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. In hac habitasse platea dictumst vestibulum rhoncus est pellentesque elit. Id cursus metus aliquam eleifend. Sem et tortor consequat id porta nibh venenatis cras sed. Volutpat commodo sed egestas egestas fringilla phasellus faucibus scelerisque eleifend. Tincidunt eget nullam non nisi est sit amet facilisis magna. Etiam sit amet nisl purus in mollis nunc sed id. Proin nibh nisl condimentum id venenatis. Etiam erat velit scelerisque in. Ultricies leo integer malesuada nunc vel risus. Sed lectus vestibulum mattis ullamcorper velit sed. Turpis tincidunt id aliquet risus feugiat in. Volutpat diam ut venenatis tellus. Tortor consequat id porta nibh venenatis cras sed felis. Vulputate eu scelerisque felis imperdiet proin. Viverra tellus in hac habitasse platea dictumst vestibulum rhoncus est. Pharetra et ultrices neque ornare aenean. Curabitur vitae nunc sed velit dignissim sodales ut." /// The `DescriptionView` provides an example of how to build a product page /// similar to those you see on the Apple�TV app. /// /// It provides a background image with a custom material gradient overlay that /// adds a blur behind the title and interactive content. It also places a /// title at the top of the view, and labels and controls at the bottom. struct DescriptionView: View { @State var showDescription = false var body: some View { VStack(alignment: .leading) { Text("Title") .font(.largeTitle) .bold() Spacer() VStack(spacing: 12) { Text("Signup information") .font(.caption.bold()) .foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .leading) HStack(alignment: .top, spacing: 30) { // The three buttons each need to be the same width. To // achieve this, their labels use // `.frame(maxWidth: .infinity)`. It's important to place // this modifier on the label rather than on the button // because the button is simply the label with some padding // and a background. This means that the button's platter // doesn't extend beyond its label farther than its static // padding amount, so the view stretches the label in the // required axis. The default alignment of a max-width // frame is `.center`, so the text remains centered inside // the button. VStack(spacing: 12) { Button {} label: { Text("Sign Up") .font(.body.bold()) .frame(maxWidth: .infinity) } Button {} label: { Text("Buy or Rent") .font(.body.bold()) .frame(maxWidth: .infinity) } Button {} label: { Label("Add to Up Next", systemImage: "plus") .font(.body.bold()) .frame(maxWidth: .infinity) } } // The view presents the description using the `.plain` // button style, which renders only its label until it // receives focus. The `.lineLimit` modifier truncates the // content, and when someone presses the button, a // `.fullScreenCover` presents the entire description. Button { showDescription = true } label: { Text(loremIpsum) .font(.callout) .lineLimit(5) } .buttonStyle(.plain) .frame(width: 1000) // If you want to have flowing text with different // attributes on different words, you can use either an // `AttributedString` or, for simplicity, add some `Text` // views together. VStack(spacing: 0) { Text("Starring") .foregroundStyle(.secondary) + Text(" Stars, Costars, and Extras") Text("Director") .foregroundStyle(.secondary) + Text(" Someone Great") } } } .padding(.top) } .background { Asset.beach.landscapeImage .aspectRatio(contentMode: .fill) .overlay { // Provide a material gradient by filling an area with // the chosen material and then applying a mask to that // area. Adjust opacity of the material to reveal the // image while providing a blurred backing to any overlaid // text. Rectangle() .fill(.ultraThinMaterial) .mask { LinearGradient( stops: [ .init(color: .white, location: 0.2), .init(color: .white.opacity(0.7), location: 0.4), .init(color: .white.opacity(0), location: 0.56), .init(color: .white.opacity(0), location: 0.7), .init(color: .white.opacity(0.25), location: 0.8) ], startPoint: .bottom, endPoint: .top ) } } .ignoresSafeArea() } .fullScreenCover(isPresented: $showDescription) { VStack(alignment: .center) { Text(loremIpsum) .frame(maxWidth: 600) } } } } #Preview { DescriptionView() } ``` ## HeroBackgroundView.swift ```swift /* Abstract: A view that shows the background for a hero view. */ import SwiftUI struct HeroBackgroundView: View { var body: some View { VStack(alignment: .leading) { Text("tvOS with SwiftUI") .font(.largeTitle).bold() HStack { Button("Button 1") {} Button("Button 2") {} Spacer() } Spacer() } .background { Image("beach_landscape") .resizable() .mask { LinearGradient( stops: [ .init(color: .black, location: 0.0), .init(color: .black, location: 0.25), .init(color: .black.opacity(0), location: 0.7) ], startPoint: .top, endPoint: .bottom ) } .ignoresSafeArea() } } } #Preview { HeroBackgroundView() } ``` ## HeroHeaderView.swift ```swift /* Abstract: A view that shows the header for a hero view. */ import SwiftUI struct HeroHeaderView: View { var belowFold: Bool var body: some View { Image("beach_landscape") .resizable() .aspectRatio(contentMode: .fill) .overlay { // The view builds the material gradient by filling an area with // a material, and then masking that area using a linear // gradient. Rectangle() .fill(.regularMaterial) .mask { maskView } } .ignoresSafeArea() } var maskView: some View { // The gradient makes direct use of the `belowFold` property to // determine the opacity of its stops. This way, when `belowFold` // changes, the gradient can animate the change to its opacity smoothly. // If you swap out the gradient with an opaque color, SwiftUI builds a // cross-fade between the solid color and the gradient, resulting in a // strange fade-out-and-back-in appearance. LinearGradient( stops: [ .init(color: .black, location: 0.25), .init(color: .black.opacity(belowFold ? 1 : 0.3), location: 0.375), .init(color: .black.opacity(belowFold ? 1 : 0), location: 0.5) ], startPoint: .bottom, endPoint: .top ) } } #Preview { HeroHeaderView(belowFold: false) } #Preview { HeroHeaderView(belowFold: true) } ``` ## MovieShelf.swift ```swift /* Abstract: A view that shows a shelf of movies. */ import SwiftUI struct MovieShelf: View { var body: some View { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ForEach(Asset.allCases) { asset in Button {} label: { asset.portraitImage .resizable() .aspectRatio(250 / 375, contentMode: .fit) .containerRelativeFrame(.horizontal, count: 6, spacing: 40) Text(asset.title) } } } } .scrollClipDisabled() .buttonStyle(.borderless) } } #Preview { MovieShelf() } ``` ## SearchView.swift ```swift /* Abstract: A view that shows a search interface. */ import SwiftUI let columns: [GridItem] = Array(repeating: .init(.flexible(), spacing: 40), count: 4) /// The `SearchView` shows an example of a simple search function. struct SearchView: View { /// When someone enters text into the search field, the system stores it /// here. @State var searchTerm: String = "" /// The view organizes a set of assets into a `Dictionary` to provide a /// lookup table that maps keywords to assets. var assets: [String: [Asset]] = Asset.lookupTable /// The assets to use in the `ForEach` come from here. /// /// If `searchTerm` is empty, this property flattens the lookup table into /// an array of assets and removes any duplicates. /// /// If there's a search term, the property performs the same operation, but /// first it filters out any items with keys that don't match the search /// term. var matchingAssets: [Asset] { if searchTerm.isEmpty { assets.values .flatMap { $0 } .reduce(into: []) { if !$0.contains($1) { $0.append($1) } } } else { assets .filter { $0.key.contains(searchTerm) } .flatMap { $0.value } .reduce(into: []) { if !$0.contains($1) { $0.append($1) } } } } /// For a stable list in the display, this takes any assets matching the /// current search term and sorts them by title. var sortedMatchingAssets: [Asset] { matchingAssets .sorted(using: SortDescriptor(\.title, comparator: .lexical)) } /// This determines suggested search terms by examining all the keys /// (keywords) in the lookup table and filtering for matches against the /// current search term. var suggestedSearchTerms: [String] { guard !searchTerm.isEmpty else { return [] } return assets.keys.filter { $0.contains(searchTerm) } } var body: some View { ScrollView(.vertical) { LazyVGrid(columns: columns, spacing: 40) { ForEach(sortedMatchingAssets) { asset in Button {} label: { asset.landscapeImage .resizable() .aspectRatio(16 / 9, contentMode: .fit) Text(asset.title) } } } .buttonStyle(.borderless) } .scrollClipDisabled() .searchable(text: $searchTerm) .searchSuggestions { ForEach(suggestedSearchTerms, id: \.self) { suggestion in Text(suggestion) } } } } #Preview { SearchView() } ``` ## SectionsView.swift ```swift /* Abstract: A view that shows multiple sections. */ import SwiftUI struct SectionsView: View { var body: some View { VStack(alignment: .leading) { Section("My Movies") { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ShelfContent() } } } Divider() Section { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ShelfContent() } } } header: { Label("My Movies", systemImage: "movieclapper.fill") } Divider() Section { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ShelfContent() } } } header: { Label("My Movies", systemImage: "movieclapper.fill") } footer: { Text("Some extra information") .font(.caption) } } .scrollClipDisabled() } } struct ShelfContent: View { var body: some View { ForEach(0..<10) { _ in Button {} label: { CodeSampleArtwork(size: .init(width: 300, height: 160)) .hoverEffect(.highlight) Text(titles.randomElement()!) } .containerRelativeFrame(.horizontal, count: 5, spacing: 40) } .buttonStyle(.borderless) } } #Preview { SectionsView() } ``` ## SidebarContentView.swift ```swift /* Abstract: The main content view for the app, with a sidebar and extra items. */ import SwiftUI enum Tabs: String, Hashable, CaseIterable, Identifiable { case stack case sections case description case buttons case background case carousel case search var id: Self { self } } enum MyMoviesTab: Equatable, Hashable, Identifiable { case upNext case movieStore case tvStore case search case browse case library(MyLibraryTab?) var description: String { switch self { case .upNext: "Up Next" case .movieStore: "Movie Store" case .tvStore: "TV Store" case .search: "Search" case .browse: "Browse" case .library(let child): "Library | (child?.rawValue ?? "")" } } var icon: String { switch self { case .upNext: return "movieclapper" case .movieStore: return "bag" case .tvStore: return "tv" case .search: return "magnifyingglass" case .browse: return "rectangle.stack" case .library(let child): return child?.icon ?? "x.circle" } } var color: Color { switch self { case .upNext: return .red case .movieStore: return .orange case .tvStore: return .yellow case .search: return .green case .browse: return .pink case .library: return .blue } } func detail() -> some View { Label(description, systemImage: icon) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(color.opacity(0.4)) } var id: String { description } } enum MyLibraryTab: String, Equatable, Hashable, CaseIterable, Identifiable { case all = "All" case wantToWatch = "Want to Watch" case movies = "Movies" case tvShows = "TV Shows" case samples = "My Samples" var icon: String { switch self { case .all: "rectangle.stack" case .wantToWatch: "arrow.forward.circle" case .movies: "movieclapper" case .tvShows: "tv" case .samples: "popcorn" } } var color: Color { switch self { case .all: return .red case .wantToWatch: return .orange case .movies: return .green case .tvShows: return .blue case .samples: return .pink } } func detail() -> some View { Label("Library | (rawValue)", systemImage: icon) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(color.opacity(0.4)) } var id: String { rawValue } var applyModifiers: Bool { self == .movies } var isPrincipalTab: Bool { self == .all } } struct SidebarContentView: View { @State var selection: MyMoviesTab = .upNext var body: some View { TabView(selection: $selection) { Tab("Search", systemImage: "magnifyingglass", value: .search) { SearchView() } Tab("Up Next", systemImage: "movieclapper", value: .upNext) { StackView() } Tab("Movie Store", systemImage: "bag", value: .movieStore) { MyMoviesTab.movieStore.detail() } Tab("TV Store", systemImage: "tv", value: .tvStore) { MyMoviesTab.tvStore.detail() } Tab("Browse", systemImage: "rectangle.stack", value: .browse) { MyMoviesTab.browse.detail() } TabSection("Library") { ForEach(MyLibraryTab.allCases) { libraryTab in Tab(libraryTab.rawValue, systemImage: libraryTab.icon, value: MyMoviesTab.library(libraryTab) ) { libraryTab.detail() } } } } .tabViewStyle(.sidebarAdaptable) } } #Preview { SidebarContentView() } ``` ## StackView.swift ```swift /* Abstract: A view that shows content shelves in a vertical stack below a header view. */ import SwiftUI /// The `StackView` implements an example landing page for a content catalog /// app. /// /// It defines several shelves with a showcase or hero header area above them. /// The view defines its header area using a `.containerRelativeFrame`, taking /// up 80% of its own container's vertical space, and defines a /// `.focusSection()` so that its full width can act as a target for focus /// movement, which it then diverts to its content. Otherwise, moving focus up /// from the right side of the shelves below might fail, or might jump all the /// way to the tab bar. /// /// This view also defines an above/below fold appearance in concert with its /// background view. When above the fold, its background renders a material /// gradient toward the bottom of the screen. When focus moves downward enough /// to roll the header area offscreen, the view snaps down to the first row of /// shelves and the background material grows to cover the entire image, /// softening the background without entirely abandoning the header's /// coloration. struct StackView: View { @State private var belowFold = false private var showcaseHeight: CGFloat = 800 var body: some View { NavigationStack { ScrollView(.vertical) { VStack(alignment: .leading, spacing: 26) { // The header/showcase view. VStack(alignment: .leading) { Text("tvOS with SwiftUI") .font(.largeTitle).bold() Spacer() HStack { Button("Show") {} NavigationLink("More Info�") { Text("Hello") } } .padding(.bottom, 80) } // Stretch the trailing edge to the width of the screen. .frame(maxWidth: .infinity, alignment: .leading) // Then place a focus target over that entire area. .focusSection() // Use 80% of the container's vertical space. .containerRelativeFrame(.vertical, alignment: .topLeading) { length, _ in length * 0.8 } .onScrollVisibilityChange { visible in // When the header scrolls more than 50% offscreen, // toggle to the below-the-fold state. withAnimation { belowFold = !visible } } Section("Movie Shelf") { MovieShelf() } Section("TV and Music Shelf") { TVMusicShelf() } Section("Content Cards") { CardShelf() } } // Use this vertical stack's content views to determine scroll // targeting. .scrollTargetLayout() } .background(alignment: .top) { // Draw the background, which changes when the view moves below // the fold. HeroHeaderView(belowFold: belowFold) } .scrollTargetBehavior( // This is a custom scroll target behavior that uses the // expected height of the showcase view. FoldSnappingScrollTargetBehavior( aboveFold: !belowFold, showcaseHeight: showcaseHeight)) // Disable scroll clipping so the scroll view doesn't clip the // raised focus effects. .scrollClipDisabled() .frame(maxHeight: .infinity, alignment: .top) } } } /// Implements an above- or below-the-fold snapping behavior. /// /// This behavior uses the expected height of the header to determine the /// snapping behavior, depending on whether the view is currently above the fold /// (showing the header) or below (showing only the shelves). When a scroll /// event moves the scroll view's content bounds beyond a certain threshold, it /// changes the target of the scroll so that it either snaps to the top of the /// scroll view, or snaps to a point below the header. struct FoldSnappingScrollTargetBehavior: ScrollTargetBehavior { var aboveFold: Bool var showcaseHeight: CGFloat /// This takes a `ScrollTarget` that contains the proposed end point of /// the current scroll event. In tvOS, this is the target of a scroll /// that the focus engine triggers when attempting to bring a newly focused /// item into view. func updateTarget(_ target: inout ScrollTarget, context: TargetContext) { // If the current scroll offset is near the top of the view and the // target is not lower than 30% of the header's height, all is good. // This allows a little flexibility when moving toward any buttons that // might be part of the header view. if aboveFold && target.rect.minY < showcaseHeight * 0.3 { // The target isn't moving enough to pass the snap point. return } // If the header isn't visible and the target isn't high enough to // reveal any of the header, the scroll can land anywhere the system // determines within this area. if !aboveFold && target.rect.minY > showcaseHeight { // The target isn't far enough up to reveal the showcase. return } // The view needs to snap upward to reveal the header only if the // target is more than 30% of the way up from the bottom edge of the // showcase. let showcaseRevealThreshold = showcaseHeight * 0.7 // If the target of the scroll is anywhere between the header's bottom // edge and that threshold, the view needs to snap to hide the header. let snapToHideRange = showcaseRevealThreshold...showcaseHeight if aboveFold || snapToHideRange.contains(target.rect.origin.y) { // The view is either above the fold and scrolling more than 30% of // the way down, or it's below the fold and isn't moving up far // enough to reveal the showcase. // This case likely triggers every time you move focus among the // items on the top content shelf, as the focus system brings them a // little farther onto the screen. It's very likely that this code // is setting the target origin to it's current position here, // effectively denying any scrolling at all. target.rect.origin.y = showcaseHeight } else { // The view is below the fold and it's moving up beyond the bottom // 30% of the header view. Snap to the view's origin to reveal the // entire header. target.rect.origin.y = 0 } } } #Preview { StackView() } ``` ## TVCatalogApp.swift ```swift /* Abstract: The entry point for the app. */ import SwiftUI @main struct TVCatalogApp: App { var body: some Scene { WindowGroup { // You have a choice here: // - `ContentView` uses classic `TabView` navigation. // - `SidebarContentView` uses the new sidebar, with extra filler // items. ContentView() // SidebarContentView() } } } ``` ## TVMusicShelf.swift ```swift /* Abstract: A view that shows a shelf of items that represent album covers. */ import SwiftUI let titles: [String] = [ "Mercury", "Venus", "Terra", "Mars", "Jupiter", "Saturn", "Neptune", "Uranus", "Pluto", "Charon", "Io", "Iapetus", "Triton", "Europa", "Ganymede", "Phobos", "Deimos", "Ceres" ] struct TVMusicShelf: View { var body: some View { ScrollView(.horizontal) { LazyHStack(spacing: 40) { ForEach(0..<20) { _ in Button {} label: { CodeSampleArtwork(size: .albumArtSize) .hoverEffect(.highlight) Text(titles.randomElement()!) .visibleWhenFocused() } .containerRelativeFrame(.horizontal, count: 5, spacing: 40) } } } .scrollClipDisabled() .buttonStyle(.borderless) } } #Preview { TVMusicShelf() } ``` ## VisibleWhenFocusedModifier.swift ```swift /* Abstract: A view modifier to affect the opacity of a view when it's in focus. */ import SwiftUI struct VisibleWhenFocusedModifier: ViewModifier { @Environment(\.isFocused) var isFocused func body(content: Content) -> some View { content.opacity(isFocused ? 1 : 0) } } extension View { func visibleWhenFocused() -> some View { modifier(VisibleWhenFocusedModifier()) } } ``` ## CreateVisualEffectsDemoApp.swift ```swift /* Abstract: The main entry point into the app. */ import SwiftUI @main struct CreateVisualEffectsDemoApp: App { var body: some Scene { WindowGroup { Text("You'll find the examples in the Xcode project's previews.") .foregroundStyle(.secondary) .multilineTextAlignment(.center) } } } ``` ## CustomTransition.swift ```swift /* Abstract: Examples for using custom transitions and composing built-in transition modifiers. */ import SwiftUI #Preview("Custom Transition") { @Previewable @State var isVisible: Bool = true VStack { GroupBox { Toggle("Visible", isOn: $isVisible.animation()) } Spacer() if isVisible { Avatar() .transition(Twirl()) } Spacer() } .padding() } #Preview("Composing existing transitions") { @Previewable @State var isVisible: Bool = true VStack { GroupBox { Toggle("Visible", isOn: $isVisible.animation()) } Spacer() if isVisible { Avatar() .transition(.scale.combined(with: .opacity)) } Spacer() } .padding() } struct Twirl: Transition { func body(content: Content, phase: TransitionPhase) -> some View { content .scaleEffect(phase.isIdentity ? 1 : 0.5) .opacity(phase.isIdentity ? 1 : 0) .blur(radius: phase.isIdentity ? 0 : 10) .rotationEffect( .degrees( phase == .willAppear ? 360 : phase == .didDisappear ? -360 : .zero ) ) .brightness(phase == .willAppear ? 1 : 0) } } struct Avatar: View { var body: some View { Circle() .fill(.blue) .overlay { Image(systemName: "person.fill") .resizable() .scaledToFit() .scaleEffect(0.5) .foregroundStyle(.white) } .frame(width: 80, height: 80) .compositingGroup() } } ``` ## MeshGradient.swift ```swift /* Abstract: A simple mesh gradient. */ import SwiftUI #Preview { MeshGradient( width: 3, height: 3, points: [ [0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [0.0, 0.5], [0.8, 0.2], [1.0, 0.5], [0.0, 1.0], [0.5, 1.0], [1.0, 1.0] ], colors: [ .black, .black, .black, .blue, .blue, .blue, .green, .green, .green ]) .edgesIgnoringSafeArea(.all) } ``` ## Ripple.swift ```swift /* Abstract: Examples for using and configuring the ripple shader as a layer effect. */ import SwiftUI #Preview("Ripple") { @Previewable @State var counter: Int = 0 @Previewable @State var origin: CGPoint = .zero VStack { Spacer() Image("palm_tree") .resizable() .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 24)) .onPressingChanged { point in if let point { origin = point counter += 1 } } .modifier(RippleEffect(at: origin, trigger: counter)) Spacer() } .padding() } #Preview("Ripple Editor") { @Previewable @State var origin: CGPoint = .zero @Previewable @State var time: TimeInterval = 0.3 @Previewable @State var amplitude: TimeInterval = 12 @Previewable @State var frequency: TimeInterval = 15 @Previewable @State var decay: TimeInterval = 8 VStack { GroupBox { Grid { GridRow { VStack(spacing: 4) { Text("Time") Slider(value: $time, in: 0 ... 2) } VStack(spacing: 4) { Text("Amplitude") Slider(value: $amplitude, in: 0 ... 100) } } GridRow { VStack(spacing: 4) { Text("Frequency") Slider(value: $frequency, in: 0 ... 30) } VStack(spacing: 4) { Text("Decay") Slider(value: $decay, in: 0 ... 20) } } } .font(.subheadline) } Spacer() Image("palm_tree") .resizable() .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 24)) .modifier(RippleModifier(origin: origin, elapsedTime: time, duration: 2, amplitude: amplitude, frequency: frequency, decay: decay)) .onTapGesture { origin = $0 } Spacer() } .padding(.horizontal) } struct PushEffect<T: Equatable>: ViewModifier { var trigger: T func body(content: Content) -> some View { content.keyframeAnimator( initialValue: 1.0, trigger: trigger ) { view, value in view.visualEffect { view, _ in view.scaleEffect(value) } } keyframes: { _ in SpringKeyframe(0.95, duration: 0.2, spring: .snappy) SpringKeyframe(1.0, duration: 0.2, spring: .bouncy) } } } /// A modifer that performs a ripple effect to its content whenever its /// trigger value changes. struct RippleEffect<T: Equatable>: ViewModifier { var origin: CGPoint var trigger: T init(at origin: CGPoint, trigger: T) { self.origin = origin self.trigger = trigger } func body(content: Content) -> some View { let origin = origin let duration = duration content.keyframeAnimator( initialValue: 0, trigger: trigger ) { view, elapsedTime in view.modifier(RippleModifier( origin: origin, elapsedTime: elapsedTime, duration: duration )) } keyframes: { _ in MoveKeyframe(0) LinearKeyframe(duration, duration: duration) } } var duration: TimeInterval { 3 } } /// A modifier that applies a ripple effect to its content. struct RippleModifier: ViewModifier { var origin: CGPoint var elapsedTime: TimeInterval var duration: TimeInterval var amplitude: Double = 12 var frequency: Double = 15 var decay: Double = 8 var speed: Double = 1200 func body(content: Content) -> some View { let shader = ShaderLibrary.Ripple( .float2(origin), .float(elapsedTime), // Parameters .float(amplitude), .float(frequency), .float(decay), .float(speed) ) let maxSampleOffset = maxSampleOffset let elapsedTime = elapsedTime let duration = duration content.visualEffect { view, _ in view.layerEffect( shader, maxSampleOffset: maxSampleOffset, isEnabled: 0 < elapsedTime && elapsedTime < duration ) } } var maxSampleOffset: CGSize { CGSize(width: amplitude, height: amplitude) } } extension View { func onPressingChanged(_ action: @escaping (CGPoint?) -> Void) -> some View { modifier(SpatialPressingGestureModifier(action: action)) } } struct SpatialPressingGestureModifier: ViewModifier { var onPressingChanged: (CGPoint?) -> Void @State var currentLocation: CGPoint? init(action: @escaping (CGPoint?) -> Void) { self.onPressingChanged = action } func body(content: Content) -> some View { let gesture = SpatialPressingGesture(location: $currentLocation) content .gesture(gesture) .onChange(of: currentLocation, initial: false) { _, location in onPressingChanged(location) } } } struct SpatialPressingGesture: UIGestureRecognizerRepresentable { final class Coordinator: NSObject, UIGestureRecognizerDelegate { @objc func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer ) -> Bool { true } } @Binding var location: CGPoint? func makeCoordinator(converter: CoordinateSpaceConverter) -> Coordinator { Coordinator() } func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer { let recognizer = UILongPressGestureRecognizer() recognizer.minimumPressDuration = 0 recognizer.delegate = context.coordinator return recognizer } func handleUIGestureRecognizerAction( _ recognizer: UIGestureRecognizerType, context: Context) { switch recognizer.state { case .began: location = context.converter.localLocation case .ended, .cancelled, .failed: location = nil default: break } } } ``` ## ScrollTransitions.swift ```swift /* Abstract: Examples for using scroll transitions for a view. */ import SwiftUI #Preview("Paging + Parallax") { let photos = [ Photo("Lily Pads"), Photo("Fish"), Photo("Succulent") ] ScrollView(.horizontal) { LazyHStack(spacing: 16) { ForEach(photos) { photo in VStack { ZStack { ItemPhoto(photo) .scrollTransition(axis: .horizontal) { content, phase in content .offset(x: phase.isIdentity ? 0 : phase.value * -200) } } .containerRelativeFrame(.horizontal) .clipShape(RoundedRectangle(cornerRadius: 36)) ItemLabel(photo) .scrollTransition(axis: .horizontal) { content, phase in content .opacity(phase.isIdentity ? 1 : 0) .offset(x: phase.value * 100) } } } } } .contentMargins(32) .scrollTargetBehavior(.paging) } #Preview("Paging + Rotation") { let photos = [ Photo("Lily Pads"), Photo("Fish"), Photo("Succulent") ] ScrollView(.horizontal) { LazyHStack(spacing: 12) { ForEach(photos) { photo in ItemPhoto(photo) .containerRelativeFrame(.horizontal) .clipShape(RoundedRectangle(cornerRadius: 36)) .scrollTransition(axis: .horizontal) { content, phase in content .rotationEffect(.degrees(phase.value * 1.5)) } } } } .contentMargins(24) .scrollTargetBehavior(.paging) } #Preview("Paging") { let photos = [ Photo("Lily Pads"), Photo("Fish"), Photo("Succulent") ] ScrollView(.horizontal) { LazyHStack(spacing: 12) { ForEach(photos) { photo in ItemPhoto(photo) .containerRelativeFrame(.horizontal) .clipShape(RoundedRectangle(cornerRadius: 36)) } } } .contentMargins(24) .scrollTargetBehavior(.paging) } struct Photo: Identifiable { var title: String var id: Int = .random(in: 0 ... 100) init(_ title: String) { self.title = title } } struct ItemPhoto: View { var photo: Photo init(_ photo: Photo) { self.photo = photo } var body: some View { Image(photo.title) .resizable() .scaledToFill() .frame(height: 500) } } struct ItemLabel: View { var photo: Photo init(_ photo: Photo) { self.photo = photo } var body: some View { Text(photo.title) .font(.title) } } ``` ## Stripes.swift ```swift /* Abstract: An example of using the `Stripes` shader as a `ShapeStyle`. */ import SwiftUI #Preview("Stripes") { VStack { let fill = ShaderLibrary.Stripes( .float(12), .colorArray([ .red, .orange, .yellow, .green, .blue, .indigo ]) ) Circle().fill(fill) } .padding() } ``` ## TextTransition.swift ```swift /* Abstract: A custom transition that puts a custom effect on each text run that `EmphasisAttribute` annotates. */ import SwiftUI #Preview("Text Transition") { @Previewable @State var isVisible: Bool = true VStack { GroupBox { Toggle("Visible", isOn: $isVisible.animation()) } Spacer() if isVisible { let visualEffects = Text("Visual Effects") .customAttribute(EmphasisAttribute()) .foregroundStyle(.pink) .bold() Text("Build (visualEffects) with SwiftUI ??") .font(.system(.title, design: .rounded, weight: .semibold)) .frame(width: 250) .transition(TextTransition()) } Spacer() } .multilineTextAlignment(.center) .padding() } #Preview("Text Transition Editor") { @Previewable @State var time: TimeInterval = 0.3 VStack { GroupBox { HStack { Text("Progress") Slider(value: $time, in: 0 ... 0.8) } } Spacer() let visualEffects = Text("Visual Effects") .customAttribute(EmphasisAttribute()) .foregroundStyle(.pink) .bold() Text("Build (visualEffects) with SwiftUI ??") .font(.system(.title, design: .rounded, weight: .semibold)) .frame(width: 250) .textRenderer(AppearanceEffectRenderer(elapsedTime: time, totalDuration: 0.8)) Spacer() } .multilineTextAlignment(.center) .padding() } struct EmphasisAttribute: TextAttribute {} /// A text renderer that animates its content. struct AppearanceEffectRenderer: TextRenderer, Animatable { /// The amount of time that passes from the start of the animation. /// Animatable. var elapsedTime: TimeInterval /// The amount of time the app spends animating an individual element. var elementDuration: TimeInterval /// The amount of time the entire animation takes. var totalDuration: TimeInterval var spring: Spring { .snappy(duration: elementDuration - 0.05, extraBounce: 0.4) } var animatableData: Double { get { elapsedTime } set { elapsedTime = newValue } } init(elapsedTime: TimeInterval, elementDuration: Double = 0.4, totalDuration: TimeInterval) { self.elapsedTime = min(elapsedTime, totalDuration) self.elementDuration = min(elementDuration, totalDuration) self.totalDuration = totalDuration } func draw(layout: Text.Layout, in context: inout GraphicsContext) { for run in layout.flattenedRuns { if run[EmphasisAttribute.self] != nil { let delay = elementDelay(count: run.count) for (index, slice) in run.enumerated() { // The time that the current element starts animating, // relative to the start of the animation. let timeOffset = TimeInterval(index) * delay // The amount of time that passes for the current element. let elementTime = max(0, min(elapsedTime - timeOffset, elementDuration)) // Make a copy of the context so that individual slices // don't affect each other. var copy = context draw(slice, at: elementTime, in: &copy) } } else { // Make a copy of the context so that individual slices // don't affect each other. var copy = context // Runs that don't have a tag of `EmphasisAttribute` quickly // fade in. copy.opacity = UnitCurve.easeIn.value(at: elapsedTime / 0.2) copy.draw(run) } } } func draw(_ slice: Text.Layout.RunSlice, at time: TimeInterval, in context: inout GraphicsContext) { // Calculate a progress value in unit space for blur and // opacity, which derive from `UnitCurve`. let progress = time / elementDuration let opacity = UnitCurve.easeIn.value(at: 1.4 * progress) let blurRadius = slice.typographicBounds.rect.height / 16 * UnitCurve.easeIn.value(at: 1 - progress) // The y-translation derives from a spring, which requires a // time in seconds. let translationY = spring.value( fromValue: -slice.typographicBounds.descent, toValue: 0, initialVelocity: 0, time: time) context.translateBy(x: 0, y: translationY) context.addFilter(.blur(radius: blurRadius)) context.opacity = opacity context.draw(slice, options: .disablesSubpixelQuantization) } /// Calculates how much time passes between the start of two consecutive /// element animations. /// /// For example, if there's a total duration of 1 s and an element /// duration of 0.5 s, the delay for two elements is 0.5 s. /// The first element starts at 0 s, and the second element starts at 0.5 s /// and finishes at 1 s. /// /// However, to animate three elements in the same duration, /// the delay is 0.25 s, with the elements starting at 0.0 s, 0.25 s, /// and 0.5 s, respectively. func elementDelay(count: Int) -> TimeInterval { let count = TimeInterval(count) let remainingTime = totalDuration - count * elementDuration return max(remainingTime / (count + 1), (totalDuration - elementDuration) / count) } } extension Text.Layout { /// A helper function for easier access to all runs in a layout. var flattenedRuns: some RandomAccessCollection<Text.Layout.Run> { self.flatMap { line in line } } /// A helper function for easier access to all run slices in a layout. var flattenedRunSlices: some RandomAccessCollection<Text.Layout.RunSlice> { flattenedRuns.flatMap(\.self) } } struct TextTransition: Transition { static var properties: TransitionProperties { TransitionProperties(hasMotion: true) } func body(content: Content, phase: TransitionPhase) -> some View { let duration = 0.9 let elapsedTime = phase.isIdentity ? duration : 0 let renderer = AppearanceEffectRenderer( elapsedTime: elapsedTime, totalDuration: duration ) content.transaction { transaction in // Force the animation of `elapsedTime` to pace linearly and // drive per-glyph springs based on its value. if !transaction.disablesAnimations { transaction.animation = .linear(duration: duration) } } body: { view in view.textRenderer(renderer) } } } ``` ## VisualEffects.swift ```swift /* Abstract: Examples for applying visual effects to a view based on its position inside a `ScrollView`. */ import SwiftUI #Preview("Position-based Hue & Scale") { ScrollView(.vertical) { VStack { ForEach(0 ..< 20) { _ in RoundedRectangle(cornerRadius: 24) .fill(.purple) .frame(height: 100) .visualEffect { content, proxy in let frame = proxy.frame(in: .scrollView(axis: .vertical)) let parentBounds = proxy .bounds(of: .scrollView(axis: .vertical)) ?? .infinite // The distance this view extends past the bottom edge // of the scroll view. let distance = min(0, frame.minY) return content .hueRotation(.degrees(frame.origin.y / 10)) .scaleEffect(1 + distance / 700) .offset(y: -distance / 1.25) .brightness(-distance / 400) .blur(radius: -distance / 50) } } } .padding() } } #Preview("Position-based Hue") { ScrollView(.vertical) { VStack { ForEach(0 ..< 20) { _ in RoundedRectangle(cornerRadius: 24) .fill(.purple) .frame(height: 100) .visualEffect { content, proxy in content .hueRotation(.degrees(proxy.frame(in: .global).origin.y / 10)) } } } .padding() } } ``` ## AppDelegate.swift ```swift /* Abstract: The app delegate. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } } ``` ## PresentationHelper.swift ```swift /* Abstract: A helper class for injecting presentation settings. */ import UIKit extension UISheetPresentationController.Detent.Identifier { static let small = UISheetPresentationController.Detent.Identifier("small") } class PresentationHelper { static let sharedInstance = PresentationHelper() var largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier = .medium var prefersScrollingExpandsWhenScrolledToEdge: Bool = false var prefersEdgeAttachedInCompactHeight: Bool = true var widthFollowsPreferredContentSizeWhenEdgeAttached: Bool = true } ``` ## SceneDelegate.swift ```swift /* Abstract: The scene delegate. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? } ``` ## SettingsViewController.swift ```swift /* Abstract: The view controller that displays options for presenting sheets. */ import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var largestUndimmedDetentIdentifierControl: UISegmentedControl! @IBOutlet weak var prefersScrollingExpandsWhenScrolledToEdgeSwitch: UISwitch! @IBOutlet weak var prefersEdgeAttachedInCompactHeightSwitch: UISwitch! @IBOutlet weak var widthFollowsPreferredContentSizeWhenEdgeAttachedSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() let selectedSegmentIndex: Int switch PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier { case .small: selectedSegmentIndex = 0 case .medium: selectedSegmentIndex = 1 default: selectedSegmentIndex = 2 } largestUndimmedDetentIdentifierControl.selectedSegmentIndex = selectedSegmentIndex prefersScrollingExpandsWhenScrolledToEdgeSwitch.isOn = PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge prefersEdgeAttachedInCompactHeightSwitch.isOn = PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight widthFollowsPreferredContentSizeWhenEdgeAttachedSwitch.isOn = PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached } @IBAction func largestUndimmedDetentChanged(_ sender: UISegmentedControl) { let largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier switch sender.selectedSegmentIndex { case 0: largestUndimmedDetentIdentifier = .small case 1: largestUndimmedDetentIdentifier = .medium default: largestUndimmedDetentIdentifier = .large } PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier = largestUndimmedDetentIdentifier updateSheet() } @IBAction func prefersScrollingExpandsWhenScrolledToEdgeSwitchChanged(_ sender: UISwitch) { PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge = sender.isOn updateSheet() } @IBAction func prefersEdgeAttachedInCompactHeightSwitchChanged(_ sender: UISwitch) { PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight = sender.isOn updateSheet() } @IBAction func widthFollowsPreferredContentSizeWhenEdgeAttachedChanged(_ sender: UISwitch) { PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached = sender.isOn updateSheet() } func updateSheet() { guard let sheet = popoverPresentationController?.adaptiveSheetPresentationController else { return } sheet.largestUndimmedDetentIdentifier = PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier sheet.prefersScrollingExpandsWhenScrolledToEdge = PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge sheet.prefersEdgeAttachedInCompactHeight = PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached } } ``` ## ViewController.swift ```swift /* Abstract: The view controller that displays the postcards. */ import UIKit class ViewController: UIViewController, UIFontPickerViewControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextViewDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var textView: UITextView! var imageViewAspectRatioConstraint: NSLayoutConstraint? // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() imageView.layer.cornerRadius = 8.0 imageView.layer.cornerCurve = .continuous } // MARK: SettingsViewController @IBAction func showSettings(_ sender: UIBarButtonItem) { guard presentedViewController == nil else { dismiss(animated: true, completion: { self.showSettings(sender) }) return } if let settingsViewController = self.storyboard?.instantiateViewController(withIdentifier: "settings") as? SettingsViewController { settingsViewController.modalPresentationStyle = .popover if let popover = settingsViewController.popoverPresentationController { popover.barButtonItem = sender let sheet = popover.adaptiveSheetPresentationController sheet.detents = [ .custom(identifier: .small) { context in 0.3 * context.maximumDetentValue }, .medium(), .large() ] sheet.prefersGrabberVisible = true // This only applies to the Settings View Controller. // Custom Detents are unavailable on Remote View Controllers. sheet.largestUndimmedDetentIdentifier = PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier sheet.prefersScrollingExpandsWhenScrolledToEdge = PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge sheet.prefersEdgeAttachedInCompactHeight = PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached } textView.resignFirstResponder() present(settingsViewController, animated: true, completion: nil) } } // MARK: UIImagePickerViewController @IBAction func showImagePicker(_ sender: UIBarButtonItem) { guard presentedViewController == nil else { dismiss(animated: true, completion: { self.showImagePicker(sender) }) return } let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.modalPresentationStyle = .popover if let popover = imagePicker.popoverPresentationController { popover.barButtonItem = sender let sheet = popover.adaptiveSheetPresentationController sheet.detents = [.medium(), .large()] sheet.largestUndimmedDetentIdentifier = .medium sheet.prefersScrollingExpandsWhenScrolledToEdge = PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge sheet.prefersEdgeAttachedInCompactHeight = PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached } textView.resignFirstResponder() present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let image = info[.originalImage] as? UIImage { imageView.image = image if let constraint = imageViewAspectRatioConstraint { NSLayoutConstraint.deactivate([constraint]) } let newConstraint = imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: image.size.width / image.size.height) NSLayoutConstraint.activate([newConstraint]) imageViewAspectRatioConstraint = newConstraint view.layoutIfNeeded() } if let sheet = picker.popoverPresentationController?.adaptiveSheetPresentationController { sheet.animateChanges { sheet.selectedDetentIdentifier = .medium } } } // MARK: UIFontPickerViewController @IBAction func showFontPicker(_ sender: UIBarButtonItem) { guard presentedViewController == nil else { dismiss(animated: true, completion: { self.showFontPicker(sender) }) return } let fontPicker = UIFontPickerViewController() fontPicker.delegate = self fontPicker.modalPresentationStyle = .popover if let popover = fontPicker.popoverPresentationController { popover.barButtonItem = sender let sheet = popover.adaptiveSheetPresentationController sheet.detents = [.medium(), .large()] sheet.largestUndimmedDetentIdentifier = .medium sheet.prefersScrollingExpandsWhenScrolledToEdge = PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge sheet.prefersEdgeAttachedInCompactHeight = PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached } textView.resignFirstResponder() present(fontPicker, animated: true, completion: nil) let inputView = UIInputView(frame: .zero, inputViewStyle: .default) inputView.isUserInteractionEnabled = false inputView.allowsSelfSizing = true textView.inputView = inputView textView.reloadInputViews() } func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) { if let descriptor = viewController.selectedFontDescriptor { let font = UIFont(descriptor: descriptor, size: 56.0) let selectedRange = textView.selectedRange if textView.isFirstResponder { let attributedText = NSMutableAttributedString(attributedString: textView.attributedText) attributedText.addAttribute(.font, value: font, range: selectedRange) textView.attributedText = attributedText textView.selectedRange = selectedRange } else { textView.font = font } view.layoutIfNeeded() } if let sheet = viewController.popoverPresentationController?.adaptiveSheetPresentationController { sheet.animateChanges { sheet.selectedDetentIdentifier = .medium } } } func fontPickerViewControllerDidCancel(_ viewController: UIFontPickerViewController) { dismiss(animated: true) } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag, completion: completion) // Reset the inputView each time when dismissing a view controller. self.textView.inputView = nil self.textView.reloadInputViews() } // MARK: UITextView func textViewDidBeginEditing(_ textView: UITextView) { if presentedViewController != nil { dismiss(animated: true) } } } ``` ## ContentView.swift ```swift /* Abstract: The app's top level view. */ import SwiftUI /// A view that presents the app's user interface. struct ContentView: View { @Environment(PlayerModel.self) private var player #if os(visionOS) @Environment(ImmersiveEnvironment.self) private var immersiveEnvironment #endif var body: some View { #if os(visionOS) Group { switch player.presentation { case .fullWindow: PlayerView() .immersiveEnvironmentPicker { ImmersiveEnvironmentPickerView() } .onAppear { player.play() } default: // Shows the app's content library by default. DestinationTabs() } } .immersionManager() #else DestinationTabs() .presentVideoPlayer() #endif } } #Preview(traits: .previewData) { ContentView() } ``` ## DestinationTabs.swift ```swift /* Abstract: The top level tab navigation for the app. */ import SwiftUI import SwiftData /// The top level tab navigation for the app. struct DestinationTabs: View { /// Keep track of tab view customizations in app storage. #if !os(macOS) && !os(tvOS) @AppStorage("sidebarCustomizations") var tabViewCustomization: TabViewCustomization #endif @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Query(filter: #Predicate<Video> { $0.isFeatured }, sort: \.id) private var videos: [Video] @Namespace private var namespace @State private var selectedTab: Tabs = .watchNow var body: some View { TabView(selection: $selectedTab) { Tab(Tabs.watchNow.name, systemImage: Tabs.watchNow.symbol, value: .watchNow) { WatchNowView() } .customizationID(Tabs.watchNow.customizationID) // Disable customization behavior on the watchNow tab to ensure that the tab remains visible. #if !os(macOS) && !os(tvOS) .customizationBehavior(.disabled, for: .sidebar, .tabBar) #endif Tab(Tabs.library.name, systemImage: Tabs.library.symbol, value: .library) { LibraryView() } .customizationID(Tabs.library.customizationID) // Disable customization behavior on the library tab to ensure that the tab remains visible. #if !os(macOS) && !os(tvOS) .customizationBehavior(.disabled, for: .sidebar, .tabBar) #endif Tab(Tabs.new.name, systemImage: Tabs.new.symbol, value: .new) { Text("This view is intentionally blank") } .customizationID(Tabs.new.customizationID) Tab(Tabs.favorites.name, systemImage: Tabs.favorites.symbol, value: .favorites) { Text("This view is intentionally blank") } .customizationID(Tabs.favorites.customizationID) Tab(value: .search, role: .search) { Text("This view is intentionally blank") } .customizationID(Tabs.search.customizationID) #if !os(macOS) && !os(tvOS) .customizationBehavior(.disabled, for: .sidebar, .tabBar) #endif #if !os(visionOS) TabSection { ForEach(Category.collectionsList) { category in Tab(category.name, systemImage: category.icon, value: Tabs.collections(category)) { CategoryView( category: category, namespace: namespace ) } .customizationID(category.customizationID) } } header: { Label("Collections", systemImage: "folder") } .customizationID(Tabs.collections(.forest).name) #if !os(macOS) && !os(tvOS) // Prevent the tab from appearing in the tab bar by default. .defaultVisibility(.hidden, for: .tabBar) .hidden(horizontalSizeClass == .compact) #endif TabSection { ForEach(Category.animationsList) { category in Tab(category.name, systemImage: category.icon, value: Tabs.animations(category)) { CategoryView( category: category, namespace: namespace ) } .customizationID(category.customizationID) } } header: { Label("Animations", systemImage: "folder") } .customizationID(Tabs.animations(.amazing).name) #if !os(macOS) && !os(tvOS) // Prevent tab from appearing in the tab bar by default. .defaultVisibility(.hidden, for: .tabBar) .hidden(horizontalSizeClass == .compact) #endif #endif } .tabViewStyle(.sidebarAdaptable) #if !os(macOS) && !os(tvOS) .tabViewCustomization($tabViewCustomization) #endif } } #Preview(traits: .previewData) { DestinationTabs() } ``` ## DestinationVideo.swift ```swift /* Abstract: The main app structure. */ import SwiftUI import SwiftData import os /// The main app structure. @main struct DestinationVideo: App { /// An object that manages the model storage configuration. private let modelContainer: ModelContainer /// An object that controls the video playback behavior. @State private var player: PlayerModel #if os(visionOS) /// An object that stores the app's level of immersion. @State private var immersiveEnvironment = ImmersiveEnvironment() /// The content brightness to apply to the immersive space. @State private var contentBrightness: ImmersiveContentBrightness = .automatic /// The effect modifies the passthrough in immersive space. @State private var surroundingsEffect: SurroundingsEffect? = nil #endif var body: some Scene { // The app's primary content window. WindowGroup { ContentView() .environment(player) .modelContainer(modelContainer) #if os(visionOS) .environment(immersiveEnvironment) #endif #if os(macOS) .toolbar(removing: .title) .toolbarBackgroundVisibility(.hidden, for: .windowToolbar) #endif // Set minimum window size #if os(macOS) || os(visionOS) .frame(minWidth: Constants.contentWindowWidth, maxWidth: .infinity, minHeight: Constants.contentWindowHeight, maxHeight: .infinity) #endif // Use a dark color scheme on supported platforms. #if os(iOS) || os(macOS) .preferredColorScheme(.dark) #endif } #if !os(tvOS) .windowResizability(.contentSize) #endif // The video player window #if os(macOS) PlayerWindow(player: player) #endif #if os(visionOS) // Defines an immersive space to present a destination in which to watch the video. ImmersiveSpace(id: ImmersiveEnvironmentView.id) { ImmersiveEnvironmentView() .environment(immersiveEnvironment) .onAppear { contentBrightness = immersiveEnvironment.contentBrightness surroundingsEffect = immersiveEnvironment.surroundingsEffect } .onDisappear { contentBrightness = .automatic surroundingsEffect = nil } // Apply a custom tint color for the video passthrough of a person's hands and surroundings. .preferredSurroundingsEffect(surroundingsEffect) } // Set the content brightness for the immersive space. .immersiveContentBrightness(contentBrightness) // Set the immersion style to progressive, so the user can use the Digital Crown to dial in their experience. .immersionStyle(selection: .constant(.progressive), in: .progressive) #endif } /// Load video metadata and initialize the model container and video player model. init() { do { let modelContainer = try ModelContainer(for: Video.self, Person.self, Genre.self, UpNextItem.self) try Importer.importVideoMetadata(into: modelContainer.mainContext) self._player = State(initialValue: PlayerModel(modelContainer: modelContainer)) self.modelContainer = modelContainer } catch { fatalError(error.localizedDescription) } } } /// A global log of events for the app. let logger = Logger() ``` ## AVExtensions.swift ```swift /* Abstract: A structure that represents the result of an audio session interruption, such as a phone call. */ import AVFoundation #if !os(macOS) // A type that unpacks the relevant values from an `AVAudioSession` interruption event. struct InterruptionResult { let type: AVAudioSession.InterruptionType let options: AVAudioSession.InterruptionOptions init?(_ notification: Notification) { // Determine the interruption type and options. guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSession.InterruptionType, let options = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? AVAudioSession.InterruptionOptions else { return nil } self.type = type self.options = options } } #endif ``` ## DestinationVideoExtensions.swift ```swift /* Abstract: Helper methods that simplify the ideal video player placement calculation. */ import Foundation #if os(macOS) extension PlayerWindow { /// Calculates the aspect ratio of the specified size. func aspectRatio(of size: CGSize) -> CGFloat { size.width / size.height } /// Calculates the center point of a size so the player appears in the center of the specified rectangle. func deltas( of size: CGSize, _ otherSize: CGSize ) -> (width: CGFloat, height: CGFloat) { (size.width / otherSize.width, size.height / otherSize.height) } /// Calculates the center point of a size so the player appears in the center of the specified rectangle. func position( of size: CGSize, centeredIn bounds: CGRect ) -> CGPoint { let midWidth = size.width / 2 let midHeight = size.height / 2 return .init(x: bounds.midX - midWidth, y: bounds.midY - midHeight) } /// Calculates the largest size a window can be in the current display, while maintaining the window's aspect ratio. func calculateZoomedSize( of currentSize: CGSize, inBounds bounds: CGRect, withAspectRatio aspectRatio: CGFloat, andDeltas deltas: (width: CGFloat, height: CGFloat) ) -> CGSize { if (aspectRatio > 1 && currentSize.height * deltas.width <= bounds.height) || (aspectRatio < 1 && currentSize.width * deltas.height <= bounds.width) { return .init( width: bounds.width, height: currentSize.height * deltas.width ) } else { return .init( width: currentSize.width * deltas.height, height: bounds.height ) } } } #endif ``` ## MultiplatformExtensions.swift ```swift /* Abstract: Helper extensions that simplify multiplatform development. */ import Foundation #if os(macOS) import AppKit public typealias PlatformImage = NSImage extension NSImage { var cgImage: CGImage? { var rect = CGRect(origin: .zero, size: size) return cgImage(forProposedRect: &rect, context: nil, hints: nil) } } #else import UIKit public typealias PlatformImage = UIImage #endif extension PlatformImage { var imageData: Data? { #if os(macOS) tiffRepresentation #else pngData() #endif } } ``` ## Category.swift ```swift /* Abstract: Descriptions of the video collections that the app presents. */ import SwiftUI /// Descriptions of the video collections that the app presents. enum Category: Int, Equatable, Hashable, Identifiable, CaseIterable { case cinematic = 1000 case forest = 1001 case sea = 1002 case animals = 1003 case amazing = 1004 case extraordinary = 1005 var id: Int { rawValue } var name: String { switch self { case .cinematic: String(localized: "Cinematic Shots", comment: "Collection name") case .forest: String(localized: "Forest Life", comment: "Collection name") case .sea: String(localized: "By the Sea", comment: "Collection name") case .animals: String(localized: "Cute Animals", comment: "Collection name") case .amazing: String(localized: "Amazing Animation", comment: "Collection name") case .extraordinary: String(localized: "Extraordinary", comment: "Collection name") } } var description: String { switch self { case .cinematic: String(localized: """ Celebrate the art of cinematography with beautifully-captured videos and animation. The perfect collection for any cinema lover. """, comment: "The description of a collection of videos.") case .forest: String(localized: """ Take a break from the busyness of city life and immerse yourself in nature with a curated collection of videos. \ Focus your attention on the forests of California and learn about the variety of cool plants. """, comment: "The description of a collection of videos.") case .sea: String(localized: """ You can almost feel the calming sea breeze and the refreshing ocean mist as you take in the wonder of the vast Pacific Ocean. \ The perfect collection of videos for those that feel the call of the ocean. """, comment: "The description of a collection of videos.") case .animals: String(localized: """ Take a closer look at some of nature�s cutest animals. Feathered and shelled friends star in this adorable collection of animal videos. \ From little birds soaring through the sky to turtles in a lake fighting for the sunniest spot. """, comment: "The description of a collection of videos.") case .amazing: String(localized: """ Whether you�re a fan of 2D or 3D animation, this collection includes the best of both. Step into the world of a robot botanist with \ this new series of animated films. """, comment: "The description of a collection of videos.") case .extraordinary: String(localized: """ Step on to another planet as you follow the robot botanist on its mission to explore the universe and discover new and \ exciting plant life. Come see what exciting adventures lay in store. """, comment: "The description of a collection of videos.") } } var tab: Tabs { switch self { case .cinematic, .forest, .sea, .animals: .collections(self) case .amazing, .extraordinary: .animations(self) } } var icon: String { switch self { default: "list.and.film" } } var image: String { switch self { case .cinematic: "cinematic_poster" case .forest: "forest_poster" case .sea: "sea_poster" case .animals: "animals_poster" case .amazing: "amazing_poster" case .extraordinary: "extraordinary_poster" } } var customizationID: String { return "com.example.apple-samplecode.DestinationVideo." + self.name } static var collectionsList: [Category] { [.cinematic, .forest, .sea, .animals] } static var animationsList: [Category] { [.amazing, .extraordinary] } static func findCategory(from id: Int) -> Category? { Category.allCases.first { $0.id == id } } } ``` ## Constants.swift ```swift /* Abstract: Constant values that the app defines. */ import SwiftUI /// Constant values that the app defines. struct Constants { static var cardSpacing: Double { #if os(tvOS) 50 #else 20 #endif } static var cardPadding: Double { #if os(tvOS) 30 #else 20 #endif } static var heroTextMargin: Double { #if os(visionOS) 500 #elseif os(tvOS) 800 #else 500 #endif } static var heroViewHeight: Double { #if os(visionOS) 550 #else 900 #endif } static var extendSafeAreaTV: Double { #if os(tvOS) 160 #else 0 #endif } static var heroSafeAreaHeight: Double { #if os(macOS) 40 #elseif os(tvOS) 120 #elseif os(visionOS) 0 #else 100 #endif } static var detailSafeAreaHeight: Double { #if os(macOS) 40 #elseif os(visionOS) 100 #else 90 #endif } static var detailPadding: Double { #if os(tvOS) 30 #else 50 #endif } static let compactDetailSafeAreaHeight: Double = 100 static let compactSafeAreaHeight: Double = 65 static let gradientSize: Double = 650 static let compactGradientSize: Double = 400 static let cornerRadius: Double = 10.0 static var outerPadding: Double { #if os(visionOS) 50 #elseif os(tvOS) 0 #else 20 #endif } static var videoCardWidth: Double { #if os(tvOS) 550 #elseif os(macOS) 250 #else 300 #endif } static let compactVideoCardWidth: Double = 200 static var upNextVideoCardWidth: Double { #if os(tvOS) 400 #else 200 #endif } static var categoryTopPadding: Double { #if os(macOS) 5 #else 0 #endif } static var stackImageWidth: Double { #if os(tvOS) 400 #elseif os(macOS) 180 #else 250 #endif } static let stackImageCompactWidth: Double = 150 static let verticalTextSpacing: Double = 15 static let detailCompactPadding: Double = 20 static let detailTrailingPadding: Double = 100 static let genreSpacing: Double = 8 static let genreVerticalPadding: Double = 3 static let genreHorizontalPadding: Double = 8 static let trailerHeight: Double = 450 static let playerWindowHeight: Double = 512 static let playerWindowWidth: Double = 960 static let contentWindowHeight: Double = 600 static let contentWindowWidth: Double = 960 static var watchNowSpacing: Double { #if os(macOS) 5 #else 0 #endif } static var listTitleVerticalPadding: Double { #if os(iOS) || os(visionOS) 5 #else 0 #endif } static var controllerPreferredHeight: Double { #if os(tvOS) 250 #else 150 #endif } static let libraryColumnCountCompact: Int = 2 static var libraryColumnCount: Int { #if os(iOS) 3 #else 4 #endif } } ``` ## Genre.swift ```swift /* Abstract: A model class that defines the properties of a genre. */ import Foundation import SwiftData /// A model class that defines the properties of a genre. @Model final class Genre: Identifiable { @Relationship var videos: [Video] var id: Int var name: String init( id: Int, name: String, videos: [Video] = [] ) { self.videos = videos self.id = id self.name = name } } extension Genre { var localizedName: String { String(localized: LocalizedStringResource(stringLiteral: self.name)) } } extension SampleData { @MainActor static let genres = [ Genre(id: 0, name: "Drama"), Genre(id: 1, name: "Romance"), Genre(id: 2, name: "Comedy"), Genre(id: 3, name: "Action"), Genre(id: 4, name: "Adventure"), Genre(id: 5, name: "Documentary"), Genre(id: 6, name: "Mystery"), Genre(id: 7, name: "Animation"), Genre(id: 8, name: "Sci-Fi") ] } ``` ## Importer.swift ```swift /* Abstract: Loads and parses the video metadata into the app. */ import Foundation import SwiftData import OSLog /// A video metadata loader. struct Importer { /// A metadata import status logger. static let logger = Logger(subsystem: "com.example.DestinationVideo", category: "Import") /// Loads the video metadata for the app. /// - Parameter context: The model context that this function writes the metadata to. /// - Parameter isPreview: A Boolean value that indicates whether to import the data for previews. @MainActor static func importVideoMetadata( into context: ModelContext, isPreview: Bool = false ) throws { logger.info("In Importer.importVideoMetadata") // If the app isn't loading preview data, checks if import needs to run. if !isPreview { // If the app already imported the data, then it doesn't import it again. guard hasImported == false else { return } } let videos = SampleData.videos let people = SampleData.people let genres = SampleData.genres let mappings = SampleData.relationships // Uses the relationship mapping for each video to complete the metadata for that video instance. mappings.forEach { map in if let video = videos.first(where: { $0.id == map.videoID }) { video.actors = people.filter { map.actorIDs.contains($0.id) } video.directors = people.filter { map.directorIDs.contains($0.id) } video.writers = people.filter { map.writerIDs.contains($0.id) } video.genres = genres.filter { map.genreIDs.contains($0.id) } // Registers the completed video metadata into the model context. context.insert(video) } } // Saves the data from the model context to persistent storage. try context.save() // Indicates that the video metadata has been imported in the user defaults database. UserDefaults.standard.set(true, forKey: "hasImported") } /// A Boolean value that indicates whether data has already been imported. static var hasImported: Bool { UserDefaults.standard.bool(forKey: "hasImported") } } ``` ## Person.swift ```swift /* Abstract: A model class that defines the properties of a person. */ import Foundation import SwiftData /// A model class that defines the properties of a person. @Model final class Person { @Relationship var appearsIn: [Video] @Relationship var wrote: [Video] @Relationship var directed: [Video] var id: Int var initial: String var surname: String init( id: Int, initial: String, surname: String, appearsIn: [Video] = [], wrote: [Video] = [], directed: [Video] = [] ) { self.appearsIn = appearsIn self.wrote = wrote self.directed = directed self.id = id self.initial = initial self.surname = surname } } extension Person { var displayName: String { PersonNameComponents(givenName: initial, familyName: surname).formatted() } } extension SampleData { @MainActor static let people = [ Person(id: 0, initial: "A", surname: "Cloud"), Person(id: 1, initial: "A", surname: "Leaf"), Person(id: 2, initial: "A", surname: "Tent"), Person(id: 3, initial: "B", surname: "Misty"), Person(id: 4, initial: "B", surname: "Skies"), Person(id: 5, initial: "D", surname: "Lily"), Person(id: 6, initial: "E", surname: "Reed"), Person(id: 7, initial: "F", surname: "Log"), Person(id: 8, initial: "G", surname: "Grass"), Person(id: 9, initial: "G", surname: "Run"), Person(id: 10, initial: "G", surname: "Seaglass"), Person(id: 11, initial: "J", surname: "Sun"), Person(id: 12, initial: "K", surname: "Dark"), Person(id: 13, initial: "K", surname: "Green"), Person(id: 14, initial: "L", surname: "Misty"), Person(id: 15, initial: "L", surname: "Shore"), Person(id: 16, initial: "L", surname: "Windy"), Person(id: 17, initial: "M", surname: "Seagull"), Person(id: 18, initial: "M", surname: "Turtle"), Person(id: 19, initial: "N", surname: "Hide"), Person(id: 20, initial: "N", surname: "Sand"), Person(id: 21, initial: "A", surname: "Cloud"), Person(id: 22, initial: "O", surname: "Scary"), Person(id: 23, initial: "P", surname: "Sky"), Person(id: 24, initial: "R", surname: "Hill"), Person(id: 25, initial: "R", surname: "Rock"), Person(id: 26, initial: "S", surname: "Dandy"), Person(id: 27, initial: "S", surname: "Sticks"), Person(id: 28, initial: "T", surname: "Daisy"), Person(id: 29, initial: "U", surname: "Brush"), Person(id: 30, initial: "U", surname: "Dare"), Person(id: 31, initial: "V", surname: "Sunny"), Person(id: 32, initial: "V", surname: "Water"), Person(id: 33, initial: "Z", surname: "Splash") ] } ``` ## PreviewData.swift ```swift /* Abstract: A modifier that creates the a model container for the preview data. */ import Foundation import SwiftData import SwiftUI /// A modifier that creates the a model container for the preview data. struct PreviewData: PreviewModifier { static func makeSharedContext() throws -> ModelContainer { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer( for: Video.self, Genre.self, Person.self, UpNextItem.self, configurations: config ) try Importer.importVideoMetadata(into: container.mainContext, isPreview: true) return container } func body(content: Content, context: ModelContainer) -> some View { content.modelContainer(context) .environment(PlayerModel(modelContainer: context)) #if os(visionOS) .environment(ImmersiveEnvironment()) #endif #if os(iOS) || os(macOS) .preferredColorScheme(.dark) #endif } } extension PreviewTrait where T == Preview.ViewTraits { @MainActor static var previewData: Self = .modifier(PreviewData()) } ``` ## RelationshipMapping.swift ```swift /* Abstract: The relationship between video, actor, writer, director, and genre. */ import Foundation /// The relationship between video, actor, writer, director ,and genre. struct RelationshipMapping: Decodable { let videoID: Int let actorIDs: [Int] let writerIDs: [Int] let directorIDs: [Int] let genreIDs: [Int] } extension SampleData { @MainActor static let relationships = [ RelationshipMapping( videoID: 0, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [7, 8] ), RelationshipMapping( videoID: 1, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [7, 4] ), RelationshipMapping( videoID: 2, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [7, 8] ), RelationshipMapping( videoID: 3, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [7, 8] ), RelationshipMapping( videoID: 4, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [7, 6] ), RelationshipMapping( videoID: 5, actorIDs: [20, 23, 11, 16], writerIDs: [25, 10], directorIDs: [17], genreIDs: [2, 7] ), RelationshipMapping( videoID: 6, actorIDs: [20, 23, 11, 16], writerIDs: [25, 10], directorIDs: [17], genreIDs: [0, 1] ), RelationshipMapping( videoID: 7, actorIDs: [18, 13], writerIDs: [33], directorIDs: [5], genreIDs: [2, 3] ), RelationshipMapping( videoID: 8, actorIDs: [27, 7, 2], writerIDs: [28], directorIDs: [21], genreIDs: [3, 4] ), RelationshipMapping( videoID: 9, actorIDs: [3, 24], writerIDs: [8, 0], directorIDs: [26, 31], genreIDs: [5] ), RelationshipMapping( videoID: 10, actorIDs: [22, 30], writerIDs: [9], directorIDs: [19, 12], genreIDs: [6] ), RelationshipMapping( videoID: 11, actorIDs: [14, 24], writerIDs: [0], directorIDs: [29], genreIDs: [1, 0] ), RelationshipMapping( videoID: 12, actorIDs: [1, 6], writerIDs: [32, 15], directorIDs: [4], genreIDs: [2, 3] ) ] } ``` ## SampleData.swift ```swift /* Abstract: The app's sample data. */ import Foundation /// The app's sample data. struct SampleData { } extension SampleData { @MainActor static let videos = [ Video( id: 0, name: "A BOT-anist Adventure", synopsis: """ An awe-inspiring tale of a beloved robot, on a quest to save extraordinary vegetation from extinction. \ Uncover the mysterious plant life inhabiting an alien planet, \ and cheer on the robot botanist as it sets out to discover and save new and exciting plants. """, categoryIDs: [ 1000, 1004, 1005 ], url: URL(string: "file://BOT-anist_video.mov")!, imageName: "BOT-anist", yearOfRelease: 2024, duration: 66, contentRating: "NR", isHero: true ), Video( id: 1, name: "Landing", synopsis: """ After a long journey through the stars, the robot botanist and its trusty spaceship finally arrive at Wolf 1069 B, \ ready to explore the mysteries that lie on the planet�s surface. \ New plants to catalog, new animals to discover, and cool rocks to unearth. Follow along as the botanist�s mission begins! """, categoryIDs: [ 1004, 1005 ], url: URL(string: "file://BOT-anist_video.mov")!, imageName: "landing", yearOfRelease: 2024, duration: 66, contentRating: "NR", isFeatured: true ), Video( id: 2, name: "Seed Sampling", synopsis: """ On a planet covered in lush jungles and thriving vegetation there�s bound to be some unique plants out there, \ and the robot botanist is on a mission to find and catalog them all. But as the botanist explores this new planet, \ it comes to discover more than just new plants. """, categoryIDs: [ 1001, 1004, 1005 ], url: URL(string: "file://BOT-anist_video.mov")!, imageName: "samples", yearOfRelease: 2024, duration: 66, startTime: 21, contentRating: "NR", isFeatured: true ), Video( id: 3, name: "The Lab", synopsis: """ After filling its backpack to the brim with dozens of plant samples, it�s time for the robot botanist to return to the lab \ and learn more about these mysterious alien plants. Hours of demanding research lie ahead as the botanist gets to work. """, categoryIDs: [ 1004, 1005 ], url: URL(string: "file://BOT-anist_video.mov")!, imageName: "lab", yearOfRelease: 2024, duration: 66, startTime: 35, contentRating: "NR", isFeatured: true ), Video( id: 4, name: "Discovering", synopsis: """ Always determined to discover new species of plants, the robot botanist explores further and further. Eventually, \ its mission brings it deep below the planet�s surface into a vast network of underground caves. \ Though the terrain may become challenging for a robot, the botanist pushes on. """, categoryIDs: [ 1004, 1005 ], url: URL(string: "file://BOT-anist_video.mov")!, imageName: "discovery", yearOfRelease: 2024, duration: 66, startTime: 51, contentRating: "NR", isFeatured: true ), Video( id: 5, name: "Dance", synopsis: """ Everyone needs a break from work sometimes, even the trusty robot botanist. \ Take a beat and unwind while the robot botanist breaks out its best dance moves during an impromptu dance party. """, categoryIDs: [ 1004 ], url: URL(string: "file://dance_video.mov")!, imageName: "dance", yearOfRelease: 2024, duration: 16, contentRating: "NR", isFeatured: true ), Video( id: 6, name: "A Beach", synopsis: """ From an award-winning producer and actor, �A Beach� is a sweeping, drama depicting waves crashing on a scenic California beach. \ Sit back and enjoy the sweet sounds of the ocean while relaxing on a soft, sandy beach. """, categoryIDs: [ 1002 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/beach/index.m3u8")!, imageName: "beach", yearOfRelease: 2023, duration: 61, contentRating: "NR", isFeatured: true ), Video( id: 7, name: "By the Lake", synopsis: """ The battle for the sunniest spot continues, as a group of turtles take their positions on the log. \ Find out who the last survivor is, and who swims away cold. """, categoryIDs: [ 1002, 1003 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/lake/index.m3u8")!, imageName: "lake", yearOfRelease: 2023, duration: 19, contentRating: "NR" ), Video( id: 8, name: "Camping in the Woods", synopsis: """ Come along for a journey of epic proportion as the perfect camp site is discovered. \ Listen to the magical wildlife and feel the gentle breeze of the wind as you watch the daisies dance in the field of flowers. """, categoryIDs: [ 1001 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/camping/index.m3u8")!, imageName: "camping", yearOfRelease: 2023, duration: 28, contentRating: "NR" ), Video( id: 9, name: "Birds in the Park", synopsis: """ On a dreamy spring day near the California hillside, some friendly little birds flutter about, \ hopping from stalk to stalk munching on some tasty seeds. Listen to them chatter as they go about their busy afternoon. """, categoryIDs: [ 1003 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/park/index.m3u8")!, imageName: "park", yearOfRelease: 2023, duration: 23, contentRating: "NR" ), Video( id: 10, name: "Mystery at the Creek", synopsis: """ A mystery is brewing on a rainy Wednesday in California, as a couple of friends head to a local campsite for a weekend in the woods. \ They never anticipated what could be living down by the trickling, rocky creek. """, categoryIDs: [ 1001, 1002 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/creek/index.m3u8")!, imageName: "creek", yearOfRelease: 2023, duration: 28, contentRating: "NR" ), Video( id: 11, name: "The Rolling Hills", synopsis: """ Discover the beauty beyond the highway, just steps away from your normal commute. \ What lies beyond is a stunning show of delicate fog rolling over the hillside. """, categoryIDs: [ 1000 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/hillside/index.m3u8")!, imageName: "hillside", yearOfRelease: 2023, duration: 80, contentRating: "NR", isFeatured: true ), Video( id: 12, name: "Ocean Breeze", synopsis: """ Experience the great flight of a black beetle, as it crawls along a giant rock near the lake preparing for takeoff. \ Where it will go, nobody knows! """, categoryIDs: [ 1000, 1002 ], url: URL(string: "https://playgrounds-cdn.apple.com/assets/ocean/index.m3u8")!, imageName: "ocean", yearOfRelease: 2023, duration: 14, contentRating: "NR" ) ] } ``` ## UpNextItem.swift ```swift /* Abstract: A model class that defines the properties of a video item in the up next queue. */ import Foundation import SwiftData /// A model class that defines the properties of anvideo item in the up next queue. @Model final class UpNextItem { @Attribute(.unique) private var videoID: Int @Relationship(deleteRule: .nullify) var video: Video? var createdAt: Date init(video: Video, createdAt: Date = .now) { self.videoID = video.id self.video = video self.createdAt = createdAt } } ``` ## Video.swift ```swift /* Abstract: A model class that defines the properties of a video. */ import Foundation import SwiftData import CoreMedia import SwiftUI /// A model class that defines the properties of a video. @Model final class Video: Identifiable { @Relationship(inverse: \Person.appearsIn) var actors: [Person] @Relationship(inverse: \Person.wrote) var writers: [Person] @Relationship(inverse: \Person.directed) var directors: [Person] @Relationship(inverse: \Genre.videos) var genres: [Genre] @Relationship(inverse: \UpNextItem.video) var upNextItem: UpNextItem? private var categoryIDs: [Int] @Transient var categories: [Category] { get { categoryIDs.compactMap { Category(rawValue: $0) } } set { categoryIDs = newValue.map(\.rawValue) } } var id: Int var url: URL var imageName: String var name: String var synopsis: String var yearOfRelease: Int var duration: Int var startTime: CMTimeValue var contentRating: String var isHero: Bool var isFeatured: Bool init( id: Int, name: String, synopsis: String, actors: [Person] = [], writers: [Person] = [], directors: [Person] = [], genres: [Genre] = [], categoryIDs: [Int] = [], url: URL, imageName: String, yearOfRelease: Int = 2023, duration: Int = 0, startTime: CMTimeValue = 0, contentRating: String = "NR", isHero: Bool = false, isFeatured: Bool = false ) { self.actors = actors self.writers = writers self.directors = directors self.genres = genres self.categoryIDs = categoryIDs self.id = id self.url = url self.imageName = imageName self.name = name self.synopsis = synopsis self.yearOfRelease = yearOfRelease self.duration = duration self.startTime = startTime self.contentRating = contentRating self.isHero = isHero self.isFeatured = isFeatured } } extension Video { var formattedDuration: String { Duration.seconds(duration) .formatted(.time(pattern: .minuteSecond(padMinuteToLength: 2))) } var formattedYearOfRelease: String { yearOfRelease .formatted(.number.grouping(.never)) } var landscapeImageName: String { "(imageName)_landscape" } var portraitImageName: String { "(imageName)_portrait" } var localizedName: String { String(localized: LocalizedStringResource(stringLiteral: self.name)) } var localizedSynopsis: String { String(localized: LocalizedStringResource(stringLiteral: self.synopsis)) } var localizedContentRating: String { String(localized: LocalizedStringResource(stringLiteral: self.contentRating)) } /// A url that resolves to specific local or remote media. var resolvedURL: URL { if url.isFileURL { guard let fileURL = Bundle.main .url(forResource: url.host(), withExtension: nil) else { fatalError("Attempted to load a nonexistent video: (String(describing: url.host()))") } return fileURL } else { return url } } /// A Boolean value that indicates whether the video is hosted in a remote location. var hasRemoteMedia: Bool { !url.isFileURL } var imageData: Data { PlatformImage(named: landscapeImageName)?.imageData ?? Data() } func toggleUpNext(in context: ModelContext) { if let upNextItem { context.delete(upNextItem) self.upNextItem = nil } else { let item = UpNextItem(video: self) context.insert(item) self.upNextItem = item } } } ``` ## NavigationNode.swift ```swift /* Abstract: A single unit in the app's navigation stack. */ import SwiftUI /// A single unit in the app's navigation stack. enum NavigationNode: Equatable, Hashable, Identifiable { case category(Int) case video(Int) var id: Int { switch self { case .category(let id): id case .video(let id): id } } } ``` ## Tabs.swift ```swift /* Abstract: A description of the tabs that the app can present. */ import SwiftUI /// A description of the tabs that the app can present. enum Tabs: Equatable, Hashable, Identifiable { case watchNow case new case favorites case library case search case collections(Category) case animations(Category) var id: Int { switch self { case .watchNow: 2001 case .new: 2002 case .favorites: 2003 case .library: 2004 case .search: 2005 case .collections(let category): category.id case .animations(let category): category.id } } var name: String { switch self { case .watchNow: String(localized: "Watch Now", comment: "Tab title") case .new: String(localized: "New", comment: "Tab title") case .library: String(localized: "Library", comment: "Tab title") case .favorites: String(localized: "Favorites", comment: "Tab title") case .search: String(localized: "Search", comment: "Tab title") case .collections(_): String(localized: "Collections", comment: "Tab title") case .animations(_): String(localized: "Animations", comment: "Tab title") } } var customizationID: String { return "com.example.apple-samplecode.DestinationVideo." + self.name } var symbol: String { switch self { case .watchNow: "play" case .new: "bell" case .library: "books.vertical" case .favorites: "heart" case .search: "magnifyingglass" case .collections(_): "list.and.film" case .animations(_): "list.and.film" } } var isSecondary: Bool { switch self { case .watchNow, .library, .new, .favorites, .search: false case .animations(_), .collections(_): true } } } ``` ## EnvironmentStateHandler.swift ```swift /* Abstract: A utility class that manages the state of an environment in an immersive space. */ import SwiftUI import RealityKit /// Describes the environment state. enum EnvironmentStateType: String { case light case dark case none var displayName: String { return switch self { case .light: String(localized: "Light", comment: "Label for Light environment") case .dark: String(localized: "Dark", comment: "Label for Dark environment") case .none: String(localized: "None", comment: "Label for environment that is neither dark nor light") } } var name: String { [self.rawValue.capitalized, "State"].joined() } } /// A utility class that manages the State of the Environment presented in the immersive space. @MainActor class EnvironmentStateHandler { static let commonEntityName = "Common" static let visualEntityName = "Visual" static let lightStateBlendParam: Float = 0.0 static let darkStateBlendParam: Float = 1.0 weak public private(set) var commonEntity: Entity? weak public private(set) var lightStateEntity: Entity? weak public private(set) var darkStateEntity: Entity? public private(set) var activeState: EnvironmentStateType = .none public func gatherEntities(from rootEntity: Entity?) { clear() guard var entity = rootEntity else { return } // Traverse the hierarchy until multiple children are found. while entity.children.count == 1 { entity = entity.children.first! } for childEntity in entity.children { let entityName = childEntity.name.lowercased() if entityName.contains(EnvironmentStateType.light.name.lowercased()) { lightStateEntity = childEntity } else if entityName.contains(EnvironmentStateType.dark.name.lowercased()) { darkStateEntity = childEntity } else if entityName.contains(Self.commonEntityName.lowercased()) { commonEntity = childEntity } } } public func setActiveState(_ state: EnvironmentStateType) { guard state != activeState else { return } guard state != .none else { logger.error("Active environment state can't be set to none") return } switch state { case .light: guard lightStateEntity != nil else { logger.error("Entity for light state not found, active state not changed") return } lightStateVisualEntity?.isEnabled = true darkStateVisualEntity?.isEnabled = false activeState = .light case .dark: guard darkStateEntity != nil else { logger.error("Entity for dark state not found, active state not changed") return } lightStateVisualEntity?.isEnabled = false darkStateVisualEntity?.isEnabled = true activeState = .dark default: break } } public func clear() { lightStateEntity = nil darkStateEntity = nil commonEntity = nil activeState = .none } private func getFirstChildByName(entity: Entity?, name: String) -> Entity? { entity?.children.first(where: { $0.name == name }) } public var lightStateVisualEntity: Entity? { getFirstChildByName(entity: lightStateEntity, name: Self.visualEntityName) } public var darkStateVisualEntity: Entity? { getFirstChildByName(entity: darkStateEntity, name: Self.visualEntityName) } } ``` ## ImmersiveEnvironment.swift ```swift /* Abstract: The model that manages the environment. */ import SwiftUI import RealityKit import Studio /// The model that manages the environment. @MainActor @Observable class ImmersiveEnvironment { /// A Boolean value that indicates whether the app is presenting an immersive space. public var immersiveSpaceIsShown: Bool = false /// A Boolean value that indicates whether to open an immersive space. public var showImmersiveSpace: Bool = false /// An object that handles the state of an environment opened in an immersive space. private var environmentStateHandler = EnvironmentStateHandler() /// The state to set an environment to after it finishes loading. private var requestedEnvironmentState: EnvironmentStateType = .light public var contentBrightness: ImmersiveContentBrightness { switch requestedEnvironmentState { case .light: .dim case .dark: .dark case .none: .automatic } } public var surroundingsEffect: SurroundingsEffect? { switch requestedEnvironmentState { case .light: .colorMultiply(Color(red: 1.15, green: 1.2, blue: 1.4)) case .dark: .colorMultiply(Color(red: 0.13, green: 0.12, blue: 0.09)) case .none: nil } } public private(set) var rootEntity: Entity? public func loadEnvironment() { Task { do { let entity = try await Entity(named: "AAA_MainScene", in: studioBundle) environmentStateHandler.gatherEntities(from: entity) setEnvironmentState(requestedEnvironmentState) showImmersiveSpace = true rootEntity = entity } catch { logger.error("Failed to load Studio bundle: (error.localizedDescription)") showImmersiveSpace = false rootEntity = nil } } } public func clearEnvironment() { environmentStateHandler.clear() rootEntity = nil } public func requestEnvironmentState(_ state: EnvironmentStateType) { guard state != .none else { logger.warning("Requested environment state can not be set to none") return } requestedEnvironmentState = state } private func setEnvironmentState(_ state: EnvironmentStateType) { guard state != .none else { logger.warning("Environment state can not be set to none") return } environmentStateHandler.setActiveState(state) switch state { case .light: setVirtualEnvironmentProbeComponent(blendParam: EnvironmentStateHandler.lightStateBlendParam) case .dark: setVirtualEnvironmentProbeComponent(blendParam: EnvironmentStateHandler.darkStateBlendParam) default: break } } private func findCommonEntityByName(_ name: String) -> Entity? { environmentStateHandler.commonEntity?.children.first(where: { $0.name == name }) } private func setVirtualEnvironmentProbeComponent(blendParam: Float) { let virtualEnvironmentProbeEntityName = "EnvironmentProbe" guard let virtualEnvironmentProbeEntity = findCommonEntityByName(virtualEnvironmentProbeEntityName) else { logger.warning("(virtualEnvironmentProbeEntityName) not found") return } if var probeComponent = virtualEnvironmentProbeEntity.components[VirtualEnvironmentProbeComponent.self] { if case VirtualEnvironmentProbeComponent.Source.blend(let firstProbe, let secondProbe, _) = probeComponent.source { probeComponent.source = .blend(from: firstProbe, to: secondProbe, t: blendParam) virtualEnvironmentProbeEntity.components[VirtualEnvironmentProbeComponent.self] = probeComponent } } } } ``` ## InlinePlayerView.swift ```swift /* Abstract: A view that displays a simple inline video player with custom controls. */ #if !os(macOS) import AVKit import SwiftUI /// A view that displays a simple inline video player with custom controls. struct InlinePlayerView: View { @Environment(PlayerModel.self) private var model var body: some View { ZStack { // A view that uses `AVPlayerViewController` to display the video content without controls. VideoContentView() // Custom inline controls to overlay on top of the video content. InlineControlsView() } .onDisappear { // If this view disappears, and it's not due to switching to full-window // presentation, clear the model's loaded media. if model.presentation != .fullWindow { model.reset() } } } } /// A view that defines a simple play/pause/replay button for the trailer player. struct InlineControlsView: View { @Environment(PlayerModel.self) private var player @State private var isShowingControls = false var body: some View { VStack { Image(systemName: player.isPlaying ? "pause.fill" : "play.fill") .padding(8) .background(.thinMaterial) .clipShape(.circle) } .font(.largeTitle) .frame(maxWidth: .infinity, maxHeight: .infinity) .contentShape(Rectangle()) .onTapGesture { player.togglePlayback() isShowingControls = true // Execute the code below on the next runloop cycle. Task { @MainActor in if player.isPlaying { dismissAfterDelay() } } } } func dismissAfterDelay() { Task { try! await Task.sleep(for: .seconds(3.0)) withAnimation(.easeOut(duration: 0.3)) { isShowingControls = false } } } } /// A view that presents the video content of an player object. /// /// This class is a view controller representable type that adapts the interface /// of `AVPlayerViewController`. It removes the view controller's default controls /// so it can draw custom controls over the video content. private struct VideoContentView: UIViewControllerRepresentable { @Environment(PlayerModel.self) private var model func makeUIViewController(context: Context) -> AVPlayerViewController { let controller = model.makePlayerUI() // Remove the default system playback controls. controller.showsPlaybackControls = false return controller } func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {} } #Preview(traits: .previewData) { InlineControlsView() } #endif ``` ## PlayerModel.swift ```swift /* Abstract: A model object that manages the playback of video. */ import AVKit import GroupActivities import SwiftData /// The presentation modes the player supports. enum Presentation { /// Presents the player as a child of a parent user interface. case inline /// Presents the player in full-window exclusive mode. case fullWindow } /// A model object that manages the playback of video. @MainActor @Observable class PlayerModel { /// A Boolean value that indicates whether playback is currently active. private(set) var isPlaying = false /// A Boolean value that indicates whether playback of the current item is complete. private(set) var isPlaybackComplete = false /// The presentation in which to display the current media. private(set) var presentation: Presentation = .inline /// The currently loaded video. private(set) var currentItem: Video? = nil /// A Boolean value that indicates whether the player should propose playing the next video in the Up Next list. private(set) var shouldProposeNextVideo = false /// An object that manages the playback of a video's media. private var player: AVPlayer /// The currently presented platform-specific video player user interface. /// /// On iOS, tvOS, and visionOS, the app uses `AVPlayerViewController` to present the video player user interface. /// The life cycle of an `AVPlayerViewController` object is different than a typical view controller. In addition /// to displaying the video player UI within your app, the view controller also manages the presentation of the media /// outside your app's UI such as when using AirPlay, Picture in Picture, or docked full window. To ensure the view /// controller instance is preserved in these cases, the app stores a reference to it here /// as an environment-scoped object. /// /// Call the `makePlayerUI()` method to set this value. private var playerUI: AnyObject? = nil private var playerUIDelegate: AnyObject? = nil private(set) var shouldAutoPlay = true /// An object that manages the app's SharePlay implementation. private var coordinator: WatchingCoordinator /// A token for periodic observation of the video player's time. private var timeObserver: Any? = nil private let modelContext: ModelContext private var playerObservationToken: NSKeyValueObservation? init(modelContainer: ModelContainer) { let player = AVPlayer() self.modelContext = ModelContext(modelContainer) self.coordinator = WatchingCoordinator( coordinator: player.playbackCoordinator, modelContainer: modelContainer ) self.player = player observePlayback() observeSharedVideo() configureAudioSession() } #if os(macOS) /// Creates a new player view object. /// - Returns: a configured player view. func makePlayerUI() -> AVPlayerView { let playerView = AVPlayerView() playerView.player = player // Set the model state playerUI = playerView playerUIDelegate = nil return playerView } #else /// Creates a new player view controller object. /// - Returns: a configured player view controller. func makePlayerUI() -> AVPlayerViewController { let controller = AVPlayerViewController() controller.player = player playerUI = controller #if os(visionOS) @MainActor class PlayerViewObserver: NSObject, AVPlayerViewControllerDelegate { private var continuation: CheckedContinuation<Void, Never>? func willEndFullScreenPresentation() async { await withCheckedContinuation { continuation = $0 } } nonisolated func playerViewController( _ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: any UIViewControllerTransitionCoordinator ) { Task { @MainActor in continuation?.resume() } } } let observer = PlayerViewObserver() controller.delegate = observer playerUIDelegate = observer Task { await observer.willEndFullScreenPresentation() reset() } #endif return controller } #endif private func observePlayback() { // Return early if the model calls this more than once. guard playerObservationToken == nil else { return } // Observe the time control status to determine whether playback is active. playerObservationToken = player.observe(\.timeControlStatus) { observed, _ in Task { @MainActor [weak self] in self?.isPlaying = observed.timeControlStatus == .playing if let startTime = self?.currentItem?.startTime { if startTime > 0 { self?.player.seek(to: CMTime(value: startTime, timescale: 1)) } } } } let center = NotificationCenter.default // Observe this notification to identify when a video plays to its end. Task { for await _ in center.notifications(named: .AVPlayerItemDidPlayToEndTime) { isPlaybackComplete = true } } #if !os(macOS) // Observe audio session interruptions. Task { for await notification in center.notifications(named: AVAudioSession.interruptionNotification) { guard let result = InterruptionResult(notification) else { continue } // Resume playback, if appropriate. if result.type == .ended && result.options == .shouldResume { player.play() } } } #endif // Add an observer of the player object's current time. The app observes // the player's current time to determine when to propose playing the next // video in the Up Next list. addTimeObserver() } /// Configures the audio session for video playback. private func configureAudioSession() { #if !os(macOS) let session = AVAudioSession.sharedInstance() do { // Configure the audio session for playback. Set the `moviePlayback` mode // to reduce the audio's dynamic range to help normalize audio levels. try session.setCategory(.playback, mode: .moviePlayback) } catch { logger.error("Unable to configure audio session: (error.localizedDescription)") } #endif } /// Monitors the coordinator's `sharedVideo` property. /// /// If this value changes due to a remote participant sharing a new activity, load and present the new video. private func observeSharedVideo() { Task { for await _ in NotificationCenter.default.notifications(named: .liveVideoDidChange) { guard let liveVideoID = coordinator.liveVideoID, liveVideoID != currentItem?.id else { continue } loadVideo(withID: liveVideoID, presentation: .fullWindow) } } } private func loadVideo( withID videoID: Video.ID, presentation: Presentation = .inline, autoplay: Bool = true ) { do { var descriptor = FetchDescriptor<Video>(predicate: #Predicate { $0.id == videoID }) descriptor.fetchLimit = 1 let results = try modelContext.fetch(descriptor) guard let video = results.first else { logger.debug("Unable to fetch video with id (videoID)") return } loadVideo(video, presentation: presentation) } catch { logger.debug("(error.localizedDescription)") } } /// Loads a video for playback in the requested presentation. /// - Parameters: /// - video: The video to load for playback. /// - presentation: The style in which to present the player. /// - autoplay: A Boolean value that indicates whether to automatically play the content when presented. func loadVideo(_ video: Video, presentation: Presentation = .inline, autoplay: Bool = true) { // Update the model state for the request. currentItem = video shouldAutoPlay = autoplay isPlaybackComplete = false switch presentation { case .fullWindow: Task { // Attempt to SharePlay this video if a FaceTime call is active. await coordinator.coordinatePlaybackOfVideo(withID: video.id) // After preparing for coordination, load the video into the player and present it. replaceCurrentItem(with: video) } case .inline: // Don't SharePlay the video when playing it from the inline player, // load the video into the player and present it. replaceCurrentItem(with: video) } // In visionOS, configure the spatial experience for either .inline or .fullWindow playback. configureAudioExperience(for: presentation) // Set the presentation, which typically presents the player full window. self.presentation = presentation } private func replaceCurrentItem(with video: Video) { // Create a new player item and set it as the player's current item. let playerItem = AVPlayerItem(url: video.resolvedURL) // Set external metadata on the player item for the current video. #if !os(macOS) playerItem.externalMetadata = createMetadataItems(for: video) #endif // Set the new player item as current, and begin loading its data. player.replaceCurrentItem(with: playerItem) logger.debug("? (video.name) enqueued for playback.") } /// Clears any loaded media and resets the player model to its default state. func reset() { currentItem = nil player.replaceCurrentItem(with: nil) playerUI = nil playerUIDelegate = nil // Reset the presentation state on the next cycle of the run loop. Task { presentation = .inline } } /// Creates metadata items from the video items data. /// - Parameter video: the video to create metadata for. /// - Returns: An array of `AVMetadataItem` to set on a player item. private func createMetadataItems(for video: Video) -> [AVMetadataItem] { let mapping: [AVMetadataIdentifier: Any] = [ .commonIdentifierTitle: video.localizedName, .commonIdentifierArtwork: video.imageData, .commonIdentifierDescription: video.localizedSynopsis, .commonIdentifierCreationDate: video.yearOfRelease, .iTunesMetadataContentRating: video.localizedContentRating, .quickTimeMetadataGenre: video.genres.map(\.name) ] return mapping.compactMap { createMetadataItem(for: $0, value: $1) } } /// Creates a metadata item for a the specified identifier and value. /// - Parameters: /// - identifier: an identifier for the item. /// - value: a value to associate with the item. /// - Returns: a new `AVMetadataItem` object. private func createMetadataItem(for identifier: AVMetadataIdentifier, value: Any) -> AVMetadataItem { let item = AVMutableMetadataItem() item.identifier = identifier item.value = value as? NSCopying & NSObjectProtocol // Specify "und" to indicate an undefined language. item.extendedLanguageTag = "und" return item.copy() as! AVMetadataItem } /// Configures the spatial audio experience to best fit the presentation. /// - Parameter presentation: the requested player presentation. private func configureAudioExperience(for presentation: Presentation) { #if os(visionOS) do { let experience: AVAudioSessionSpatialExperience switch presentation { case .inline: // Set a small, focused sound stage when watching trailers. experience = .headTracked(soundStageSize: .small, anchoringStrategy: .automatic) case .fullWindow: // Set a large sound stage size when viewing full window. experience = .headTracked(soundStageSize: .large, anchoringStrategy: .automatic) } try AVAudioSession.sharedInstance().setIntendedSpatialExperience(experience) } catch { logger.error("Unable to set the intended spatial experience. (error.localizedDescription)") } #endif } // MARK: - Transport Control func play() { player.play() } func seek() { player.play() } func pause() { player.pause() } func togglePlayback() { player.timeControlStatus == .paused ? play() : pause() } // MARK: - Time Observation private func addTimeObserver() { removeTimeObserver() // Observe the player's timing once every second. let timeInterval = CMTime(value: 1, timescale: 1) timeObserver = player .addPeriodicTimeObserver(forInterval: timeInterval, queue: .main) { time in Task { @MainActor in if let duration = self.player.currentItem?.duration { let isInProposalRange = time.seconds >= duration.seconds - 10.0 if self.shouldProposeNextVideo != isInProposalRange { self.shouldProposeNextVideo = isInProposalRange } } } } } private func removeTimeObserver() { guard let timeObserver = timeObserver else { return } player.removeTimeObserver(timeObserver) self.timeObserver = nil } } ``` ## PlayerView.swift ```swift /* Abstract: A view that presents the video player. */ import SwiftUI /// Constants that define the style of controls a player presents. enum PlayerControlsStyle { /// The player uses the system interface that AVPlayerViewController provides. case system /// The player uses compact controls that display a play/pause button. case custom } /// A view that presents the video player. struct PlayerView: View { static let identifier = "player-view" let controlsStyle: PlayerControlsStyle @State private var showContextualActions = false @Environment(PlayerModel.self) private var model /// Creates a new player view. init(controlsStyle: PlayerControlsStyle = .system) { self.controlsStyle = controlsStyle } private var systemPlayerView: some View { #if os(macOS) // Adds the drag gesture to a transparent overlay and inserts // the overlay between the video content and the playback controls. let overlay = Color.clear .contentShape(.rect) .gesture(WindowDragGesture()) // Enable the window drag gesture to receive events that activate the window. .allowsWindowActivationEvents(true) return SystemPlayerView(showContextualActions: showContextualActions, overlay: overlay) #else return SystemPlayerView(showContextualActions: showContextualActions) #endif } var body: some View { switch controlsStyle { case .system: systemPlayerView .onChange(of: model.shouldProposeNextVideo) { oldValue, newValue in if oldValue != newValue { showContextualActions = newValue } } case .custom: #if os(visionOS) InlinePlayerView() #endif } } } ``` ## SystemPlayerView.swift ```swift /* Abstract: A view that provides a platform-specific playback user interface. */ import AVKit import SwiftUI import SwiftData #if os(macOS) // A SwiftUI wrapper on `AVPlayerViewController`. struct SystemPlayerView<Overlay: View>: NSViewRepresentable { @Environment(PlayerModel.self) private var model let showContextualActions: Bool private let overlay: Overlay init(showContextualActions: Bool, overlay: Overlay) { self.showContextualActions = showContextualActions self.overlay = overlay } final class Coordinator: NSObject, AVPlayerViewDelegate { /// The hosting view for the SwiftUI content overlay view. weak var overlayHostingView: NSHostingView<Overlay>? } func makeCoordinator() -> Coordinator { Coordinator() } func makeNSView(context: Context) -> AVPlayerView { let playerView = model.makePlayerUI() playerView.controlsStyle = .floating playerView.delegate = context.coordinator // Create the hosting view for the SwiftUI content overlay view. if let contentOverlayView = playerView.contentOverlayView { let overlayHostingView = NSHostingView(rootView: overlay) context.coordinator.overlayHostingView = overlayHostingView // Add the hosting view to the player view's content overlay view. contentOverlayView.addSubview(overlayHostingView) overlayHostingView.translatesAutoresizingMaskIntoConstraints = false overlayHostingView.topAnchor.constraint(equalTo: contentOverlayView.topAnchor).isActive = true overlayHostingView.trailingAnchor.constraint(equalTo: contentOverlayView.trailingAnchor).isActive = true overlayHostingView.bottomAnchor.constraint(equalTo: contentOverlayView.bottomAnchor).isActive = true overlayHostingView.leadingAnchor.constraint(equalTo: contentOverlayView.leadingAnchor).isActive = true } return playerView } func updateNSView(_ nsView: NSViewType, context: Context) { context.coordinator.overlayHostingView?.rootView = overlay } } #else // A SwiftUI wrapper on `AVPlayerViewController`. struct SystemPlayerView: UIViewControllerRepresentable { @Environment(PlayerModel.self) private var model @Query(sort: \UpNextItem.createdAt) private var playlist: [UpNextItem] let showContextualActions: Bool init(showContextualActions: Bool) { self.showContextualActions = showContextualActions } func makeUIViewController(context: Context) -> AVPlayerViewController { // Create a player view controller. let controller = model.makePlayerUI() // Enable Picture in Picture in iOS and tvOS. controller.allowsPictureInPicturePlayback = true #if os(visionOS) || os(tvOS) // Display an Up Next tab in the player UI. if let upNextViewController { controller.customInfoViewControllers = [upNextViewController] } #endif // Return the configured controller object. return controller } func updateUIViewController(_ controller: UIViewControllerType, context: Context) { #if os(visionOS) || os(tvOS) Task { @MainActor in // Rebuild the list of related videos, if necessary. if let upNextViewController { controller.customInfoViewControllers = [upNextViewController] } if let upNextAction, showContextualActions { controller.contextualActions = [upNextAction] } else { controller.contextualActions = [] } } #endif } // A view controller that presents a list of Up Next videos. var upNextViewController: UIViewController? { guard let video = model.currentItem else { return nil } // Find the Up Next list for this video. Return early if there aren't any videos. let videos = playlist .compactMap(\.video) .filter { $0.id != video.id } if videos.isEmpty { return nil } let view = UpNextView(videos: videos, model: model) let controller = UIHostingController(rootView: view) // `AVPlayerViewController` uses the view controller's title as the tab name. // Specify the view controller's title before setting it as a `customInfoViewControllers` value. controller.title = view.title // Set the preferred content size for the tab. #if os(tvOS) controller.preferredContentSize = CGSize(width: 500, height: 250) #else controller.preferredContentSize = CGSize(width: 600, height: 150) #endif return controller } var upNextAction: UIAction? { // If there's no video loaded, return `nil`. guard let video = model.currentItem else { return nil } // Find the next video to play. guard let item = video.upNextItem, let index = playlist.firstIndex(of: item), playlist.indices.contains(index + 1), let nextVideo = playlist[index + 1].video else { return nil } return UIAction(title: String(localized: "Play Next"), image: UIImage(systemName: "play.fill")) { _ in // Load the video for full-window presentation. model.loadVideo(nextVideo, presentation: .fullWindow) } } } #endif ``` ## UpNextView.swift ```swift /* Abstract: A view that displays a list of videos related to the currently playing video. */ import SwiftUI /// A view that displays a list of videos related to the currently playing video. struct UpNextView: View { let title = String(localized: "Up Next", comment: "Used as window title") let videos: [Video] let model: PlayerModel @Namespace private var namespace var body: some View { VideoListView(videos: videos, cardStyle: .upNext, namespace: namespace) { video in model.loadVideo(video, presentation: .fullWindow) } } } ``` ## PlayerWindow.swift ```swift /* Abstract: A window that contains the video player for macOS. */ import SwiftUI /// A window that contains the video player for macOS. #if os(macOS) struct PlayerWindow: Scene { /// An object that controls the video playback behavior. var player: PlayerModel var body: some Scene { // The macOS client presents the player view in a separate window. WindowGroup(id: PlayerView.identifier) { PlayerView() .environment(player) .onAppear { player.play() } .onDisappear { player.reset() } // Set the minimum window size. .frame(minWidth: Constants.playerWindowWidth, maxWidth: .infinity, minHeight: Constants.playerWindowHeight, maxHeight: .infinity) .toolbar(removing: .title) .toolbarBackgroundVisibility(.hidden, for: .windowToolbar) // Allow the content to extend up the the window's edge, // past the safe area. .ignoresSafeArea(edges: .top) } .defaultPosition(.center) .restorationBehavior(.disabled) .windowResizability(.contentSize) .windowIdealPlacement { proxy, context in let displayBounds = context.defaultDisplay.visibleRect let idealSize = proxy.sizeThatFits(.unspecified) // Calculate the content's aspect ratio. let aspectRatio = aspectRatio(of: idealSize) // Determine the change between the display's size and the content's size. let deltas = deltas(of: displayBounds.size, idealSize) // Calculate the window's zoomed size while maintaining the aspect ratio // of the content. let size = calculateZoomedSize( of: idealSize, inBounds: displayBounds, withAspectRatio: aspectRatio, andDeltas: deltas ) // Position the window in the center of the display and return the // corresponding window placement. let position = position(of: size, centeredIn: displayBounds) return WindowPlacement(position, size: size) } } } #endif ``` ## WatchingActivity.swift ```swift /* Abstract: A group activity to watch a video with others. */ import GroupActivities import CoreTransferable import CoreGraphics /// A group activity to watch a video with others. struct WatchingActivity: GroupActivity, Transferable { let title: String let previewImageName: String let fallbackURL: URL? let videoID: Video.ID // Metadata that the system displays to participants. var metadata: GroupActivityMetadata { var metadata = GroupActivityMetadata() metadata.type = .watchTogether metadata.title = title metadata.previewImage = previewImage metadata.fallbackURL = fallbackURL metadata.supportsContinuationOnTV = true return metadata } var previewImage: CGImage? { PlatformImage(named: previewImageName)?.cgImage } } ``` ## WatchingCoordinator.swift ```swift /* Abstract: An actor that manages the coordinated playback of a video with participants in a group session. */ import Foundation import AVFoundation import SwiftData import GroupActivities /// An actor that manages the coordinated playback of a video with participants in a group session. @MainActor class WatchingCoordinator { private typealias WatchingSession = GroupSession<WatchingActivity> private weak var coordinator: AVPlayerPlaybackCoordinator? private var coordinatorDelegate: PlaybackCoordinatorDelegate? private var liveSession: WatchingSession? { didSet { guard let liveSession else { return } coordinator?.coordinateWithSession(liveSession) } } private var observers = [Task<Void, Never>]() private(set) var liveVideoID: Video.ID? { didSet { NotificationCenter.default.post( name: .liveVideoDidChange, object: nil ) } } private let modelContext: ModelContext init(coordinator: AVPlayerPlaybackCoordinator, modelContainer: ModelContainer) { self.coordinator = coordinator self.modelContext = ModelContext(modelContainer) Task { observeSessions() } } func coordinatePlaybackOfVideo(withID videoID: Video.ID) async { guard videoID != liveVideoID else { return } do { var descriptor = FetchDescriptor<Video>(predicate: #Predicate { $0.id == videoID }) descriptor.fetchLimit = 1 let results = try modelContext.fetch(descriptor) guard let video = results.first else { logger.debug("Unable to fetch video with id (videoID)") return } let activity = WatchingActivity( title: video.name, previewImageName: video.landscapeImageName, fallbackURL: video.hasRemoteMedia ? video.resolvedURL : nil, videoID: video.id ) switch await activity.prepareForActivation() { case .activationPreferred: do { _ = try await activity.activate() } catch { logger.debug("Unable to activate the activity: (error)") } case .activationDisabled: liveVideoID = nil case .cancelled: break @unknown default: break } } catch { logger.debug("(error.localizedDescription)") } } } extension WatchingCoordinator { private func observeSessions() { Task { for await session in WatchingActivity.sessions() { if let liveSession { leave(liveSession) } #if os(visionOS) await configureSystemCoordinator(for: session) #endif liveSession = session // Observe state changes. observers.append(Task { for await state in session.$state.values { guard case .invalidated = state else { continue } leave(session) } }) // Observe activity changes. observers.append(Task { for await activity in session.$activity.values { guard session === liveSession else { continue } updateLiveVideo(to: activity.videoID) } }) session.join() } } } #if os(visionOS) private nonisolated func configureSystemCoordinator(for session: WatchingSession) async { // Retrieve the new session's system coordinator object to update its configuration. guard let systemCoordinator = await session.systemCoordinator else { return } // Create a new configuration that enables all participants to share the same immersive space. var configuration = SystemCoordinator.Configuration() // Enable showing Spatial Personas inside an immersive space. configuration.supportsGroupImmersiveSpace = true // Use the side-by-side template to arrange participants in a line with the content in front. configuration.spatialTemplatePreference = .sideBySide // Update the coordinator's configuration. systemCoordinator.configuration = configuration } #endif private func updateLiveVideo(to videoID: Video.ID) { coordinatorDelegate = PlaybackCoordinatorDelegate(videoID: videoID) coordinator?.delegate = coordinatorDelegate liveVideoID = videoID } private func leave(_ session: WatchingSession) { guard session === liveSession else { return } session.leave() liveSession = nil observers.forEach { $0.cancel() } observers = [] } } extension WatchingCoordinator { private final class PlaybackCoordinatorDelegate: NSObject, AVPlayerPlaybackCoordinatorDelegate { private let videoID: Video.ID init(videoID: Video.ID) { self.videoID = videoID } func playbackCoordinator( _ coordinator: AVPlayerPlaybackCoordinator, identifierFor playerItem: AVPlayerItem ) -> String { String(videoID) } } } extension Notification.Name { static let liveVideoDidChange = Notification.Name("liveVideoDidChange") } ``` ## ButtonStyle.swift ```swift /* Abstract: Custom button styles that the app defines. */ import SwiftUI /// A custom button style. struct CustomButtonStyle: PrimitiveButtonStyle { @Environment(\.horizontalSizeClass) var horizontalSizeClass func makeBody(configuration: Configuration) -> some View { Button(configuration) .buttonStyle(.bordered) .buttonBorderShape(.capsule) .fontWeight(.medium) #if !os(tvOS) .controlSize(horizontalSizeClass == .compact ? .small : .regular) #endif } } /// A custom button style for buttons in the app library. struct PickerButtonStyle: PrimitiveButtonStyle { @Environment(\.horizontalSizeClass) var horizontalSizeClass var isSelected: Bool func makeBody(configuration: Configuration) -> some View { if isSelected { Button(configuration) #if os(macOS) .buttonStyle(MacOSButtonStyle(isSelected: isSelected)) #else .buttonStyle(.borderedProminent) .foregroundStyle(.black) .background { RoundedRectangle(cornerRadius: 10) .fill(.white) } #endif .modifier(PickerButtonModifier(isSelected: false)) } else { Button(configuration) #if os(macOS) .buttonStyle(MacOSButtonStyle(isSelected: isSelected)) #else .buttonStyle(.bordered) #endif .modifier(PickerButtonModifier(isSelected: true)) } } struct PickerButtonModifier: ViewModifier { @Environment(\.horizontalSizeClass) var horizontalSizeClass var isSelected: Bool func body(content: Content) -> some View { content .fontWeight(.medium) .buttonBorderShape(.roundedRectangle) #if !os(tvOS) .controlSize(horizontalSizeClass == .compact ? .small : .regular) #endif } } private struct MacOSButtonStyle: ButtonStyle { var isSelected: Bool func makeBody(configuration: Self.Configuration) -> some View { configuration.label .padding(.horizontal, 10) .padding(.vertical, 5) .foregroundColor(isSelected ? .black : .white) .background(isSelected ? .white : .black) .cornerRadius(5) } } } ``` ## CategoryListView.swift ```swift /* Abstract: A view that presents a horizontally scrollable list of collections. */ import SwiftUI /// A view that presents a horizontally scrollable list of collections. struct CategoryListView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass var isCompact: Bool { horizontalSizeClass == .compact } let title: LocalizedStringKey let categoryList: [Category] let namespace: Namespace.ID var body: some View { Section { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: Constants.cardSpacing) { ForEach(categoryList) { category in NavigationLink(value: NavigationNode.category(category.id)) { let image = Image(category.image).resizable() PosterCard(image: image, title: category.name) #if os(iOS) || os(visionOS) .hoverEffect() #endif } .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth) .accessibilityLabel(category.name) .buttonStyle(buttonStyle) .transitionSource(id: category.id, namespace: namespace) } } .padding(.vertical, Constants.listTitleVerticalPadding) .padding(.leading, Constants.outerPadding) } .scrollClipDisabled() } header: { Text(title) .font(.title3.bold()) .padding(.leading, Constants.outerPadding) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) } } var buttonStyle: some PrimitiveButtonStyle { #if os(tvOS) .card #else .plain #endif } } #Preview { @Previewable @Namespace var namespace CategoryListView(title: "Collections", categoryList: Category.collectionsList, namespace: namespace) .frame(height: 200) } ``` ## CategoryView.swift ```swift /* Abstract: A view that displays the videos in a playlist. */ import SwiftUI import SwiftData /// A view that displays the videos in a playlist. struct CategoryView: View { @Environment(PlayerModel.self) private var player @Environment(\.modelContext) private var context @State private var navigationPath: [NavigationNode] @State private var videos: [Video] = [] private let category: Category private let namespace: Namespace.ID init( category: Category, namespace: Namespace.ID, navigationPath: [NavigationNode]? = nil ) { self.category = category self.namespace = namespace self._navigationPath = State(initialValue: navigationPath ?? [NavigationNode]()) } var body: some View { // Wrap the content in a vertically scrolling view. NavigationStack(path: $navigationPath) { ScrollView(showsIndicators: false) { VStack(alignment: .leading) { Text(category.name) .font(.title.bold()) Text(category.description) .font(.body) Button("Play", systemImage: "play.fill") { if let firstVideo = videos.first { /// Load the media item for full-window presentation. player.loadVideo(firstVideo, presentation: .fullWindow) } } .buttonStyle(CustomButtonStyle()) .padding(.bottom) VStack(spacing: Constants.cardSpacing) { ForEach(videos.filter { $0.categories.contains(category) }) { video in NavigationLink(value: NavigationNode.video(video.id)) { VideoCardView(video: video, style: .stack) } .accessibilityLabel(category.name) .transitionSource(id: video.id, namespace: namespace) } .buttonStyle(buttonStyle) } } .padding([.horizontal, .bottom], Constants.outerPadding) .frame(maxWidth: .infinity, alignment: .leading) .navigationDestinationVideo(in: namespace) } .scrollClipDisabled() .toolbarBackground(.hidden) .padding(.top, Constants.categoryTopPadding) .onAppear { do { // Show videos in the category. var descriptor = FetchDescriptor<Video>() descriptor.sortBy = [SortDescriptor(\.id)] self.videos = try context.fetch(descriptor) .filter { $0.categories.contains(category) } } catch { print(error.localizedDescription) } } #if os(tvOS) .background(Color("tvBackground")) #endif } } var buttonStyle: some PrimitiveButtonStyle { #if os(tvOS) .card #else .plain #endif } } #Preview(traits: .previewData) { @Previewable @Namespace var namespace return CategoryView(category: .extraordinary, namespace: namespace) } ``` ## DetailView.swift ```swift /* Abstract: A view that presents the video content details. */ import SwiftUI import SwiftData /// A view that presents the video content details. struct DetailView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(PlayerModel.self) private var player @Environment(\.modelContext) private var context private var isCompact: Bool { horizontalSizeClass == .compact } @State var video: Video @State private var viewSize: CGSize = CGSize(width: 0, height: 0) var body: some View { ScrollView(showsIndicators: false) { VStack { VStack(alignment: .leading, spacing: Constants.verticalTextSpacing) { Text(video.localizedName) .font(isCompact ? .title : .largeTitle) .bold() Text("(video.formattedYearOfRelease) | (video.localizedContentRating) | (video.formattedDuration)", comment: "Release Year | Rating | Duration") .font(.headline) .accessibilityLabel(""" Released (video.formattedYearOfRelease), rated (video.localizedContentRating), \ (video.duration) seconds """) GenreView(genres: video.genres) Text(video.localizedSynopsis) .multilineTextAlignment(.leading) .font(isCompact ? .body : .headline) .fontWeight(.semibold) HStack { // A button that plays the video in a full-window presentation. Button { /// Load the media item for full-window presentation. player.loadVideo(video, presentation: .fullWindow) } label: { Label("Play Movie", systemImage: "play.fill") } // A button that toggles whether the video is in the Up Next queue. Button { video.toggleUpNext(in: context) } label: { let isQueued = video.upNextItem != nil Label(isQueued ? "In Up Next" : "Add to Up Next", systemImage: isQueued ? "checkmark" : "plus") } Spacer() } .buttonStyle(CustomButtonStyle()) // Make the buttons the same width. .fixedSize(horizontal: true, vertical: false) .frame(maxWidth: .infinity, alignment: .leading) } .padding(isCompact ? Constants.detailCompactPadding : Constants.detailPadding) .padding(.bottom, isCompact ? Constants.detailCompactPadding : 0) .padding(.trailing, isCompact ? 0 : Constants.detailTrailingPadding) .frame(height: viewSize.height, alignment: .bottom) .background(alignment: .bottom) { backgroundView } #if !os(tvOS) VStack(alignment: .leading, spacing: Constants.verticalTextSpacing) { #if os(visionOS) Text("Extras") .font(.headline) // A view that plays video in an inline presentation. TrailerView(video: video) .aspectRatio(16 / 9, contentMode: .fit) .frame(maxWidth: Constants.trailerHeight) .cornerRadius(Constants.cornerRadius) #endif Text("Cast & Crew") .font(.headline) RoleView(role: String(localized: "Stars", comment: "A participant in making a video."), people: video.actors) RoleView(role: String(localized: "Director", comment: "A participant in making a video."), people: video.directors) RoleView(role: String(localized: "Writers", comment: "A participant in making a video."), people: video.writers) } .padding(isCompact ? Constants.detailCompactPadding : Constants.detailPadding) .padding(.bottom, isCompact ? Constants.detailCompactPadding : 0) .frame(maxWidth: .infinity, alignment: .leading) #endif } #if os(iOS) .background(.black) #endif } .scrollClipDisabled() .padding(.top, isCompact ? -Constants.compactDetailSafeAreaHeight : -Constants.detailSafeAreaHeight) .onGeometryChange(for: CGSize.self) { proxy in return proxy.size } action: { size in let heightPadding = (isCompact ? Constants.compactDetailSafeAreaHeight : Constants.detailSafeAreaHeight) + Constants.extendSafeAreaTV let widthPadding = Constants.extendSafeAreaTV viewSize = CGSize(width: size.width + widthPadding, height: size.height + heightPadding) } // Don't show a navigation title in iOS. .navigationTitle("") .toolbarBackground(.hidden) } /// Returns a background image for the view orientation. private var backgroundImage: Image { let usePortrait = viewSize.height > viewSize.width return Image(decorative: usePortrait ? video.portraitImageName : video.landscapeImageName).resizable() } private var backgroundView: some View { Group { backgroundImage .scaledToFill() .frame(width: viewSize.width, height: viewSize.height) .clipped() // Add a subtle gradient to make the text stand out. #if os(iOS) GradientView(style: .black.opacity(0.6), direction: .horizontal, width: Constants.gradientSize, startPoint: .leading) GradientView(style: .black, height: Constants.gradientSize, startPoint: .bottom) #else GradientView(style: .black.opacity(0.4), direction: .horizontal, width: Constants.gradientSize, startPoint: .leading) GradientView(style: .black.opacity(0.5), height: Constants.gradientSize, startPoint: .bottom) #endif } .padding([.horizontal, .bottom], -Constants.extendSafeAreaTV) } } #Preview(traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] DetailView(video: videos.first!) } ``` ## GradientView.swift ```swift /* Abstract: A gradient view. */ import SwiftUI /// A view that displays a horizontal and vertical gradient. struct GradientView: View { /// A fill style for the gradient. let style: any ShapeStyle /// Thje direction of the gradient. var direction: Axis = .vertical /// The height of the view in points. var height: CGFloat? = nil /// The width of the view in points. var width: CGFloat? = nil /// The start point of the gradient. /// /// This value can be `.top` or .`bottom`. let startPoint: UnitPoint var endPoint: UnitPoint { if direction == .horizontal { return startPoint == .leading ? .trailing : .leading } else { return startPoint == .top ? .bottom : .top } } var body: some View { Rectangle() .fill(AnyShapeStyle(style)) .frame(height: height) .frame(width: width) .mask { LinearGradient(colors: [.black, .clear], startPoint: startPoint, // Set the end point to be the opposite of the start. endPoint: endPoint) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) } } #Preview("vertical") { GradientView(style: .blue.opacity(0.5), height: 200, startPoint: .bottom) .ignoresSafeArea() } #Preview("horizontal") { GradientView(style: .blue.opacity(0.5), direction: .horizontal, startPoint: .leading) .ignoresSafeArea() } ``` ## HeroView.swift ```swift /* Abstract: A view that displays the hero video banner. */ import SwiftUI import SwiftData /// A view that displays the hero video banner. struct HeroView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass private var isCompact: Bool { horizontalSizeClass == .compact } let video: Video let namespace: Namespace.ID var body: some View { ZStack(alignment: .leading) { Group { Image(decorative: video.landscapeImageName) .resizable() .aspectRatio(contentMode: .fill) .frame(maxHeight: Constants.heroViewHeight) .clipped() // Add a subtle gradient to make the text stand out. GradientView(style: .black.opacity(0.6), startPoint: .leading) #if os(iOS) GradientView(style: .black, height: isCompact ? Constants.compactGradientSize : Constants.gradientSize / 2, startPoint: .bottom) #endif } VStack(alignment: .leading, spacing: Constants.verticalTextSpacing) { Text(video.localizedName) .font(isCompact ? .title : .largeTitle) .fontWeight(.bold) Text(video.localizedSynopsis) .font(isCompact ? .caption : .body) .fontWeight(isCompact ? .regular : .semibold) NavigationLink("Details", value: NavigationNode.video(video.id)) #if os(iOS) .buttonStyle(CustomButtonStyle()) #endif } .frame(maxWidth: Constants.heroTextMargin, alignment: .leading) .padding(Constants.outerPadding) .padding(Constants.extendSafeAreaTV) } .transitionSource(id: video.id, namespace: namespace) .padding(.bottom, isCompact ? 0 : nil) .padding(.top, isCompact ? -Constants.compactSafeAreaHeight : -Constants.heroSafeAreaHeight) .padding(.horizontal, -Constants.extendSafeAreaTV) #if os(tvOS) .focusSection() #endif } } #Preview(traits: .previewData) { @Previewable @Query(filter: #Predicate<Video> { $0.isHero }, sort: \.id) var heroVideos: [Video] @Previewable @Namespace var namespace return NavigationStack { ScrollView { if let heroVideo = heroVideos.first { HeroView(video: heroVideo, namespace: namespace) } } } } ``` ## LibraryView.swift ```swift /* Abstract: A view that displays the list of videos the library contains in a grid. */ import SwiftUI import SwiftData /// A view that displays the list of videos the library contains in a grid. struct LibraryView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Query(sort: \Video.name) private var allVideos: [Video] @Query(sort: \Genre.name) private var genres: [Genre] @Namespace private var namespace @State private var navigationPath = [NavigationNode]() @State private var selectedGenre: Genre? // Adapt the number columns based on platform and size class. private var columns: [GridItem] { let gridItem = GridItem(.flexible(), spacing: Constants.cardSpacing) let count = horizontalSizeClass == .compact ? Constants.libraryColumnCountCompact : Constants.libraryColumnCount return [GridItem](repeating: gridItem, count: count) } var body: some View { NavigationStack(path: $navigationPath) { // Wrap the content in a vertically scrolling view. ScrollView(showsIndicators: false) { VStack { // Wrap the content in a horizontally scrolling view. ScrollView(.horizontal, showsIndicators: false) { HStack { Button("All") { selectedGenre = nil } .buttonStyle(PickerButtonStyle(isSelected: selectedGenre == nil)) ForEach(genres.sorted { $0.localizedName < $1.localizedName }) { genre in Button(genre.localizedName) { selectedGenre = genre } .buttonStyle(PickerButtonStyle(isSelected: selectedGenre == genre)) } } } .defaultScrollAnchor(.center) .scrollClipDisabled() .padding(.bottom) // Filter videos using the genre a person selects. let videos = selectedGenre?.videos.sorted(by: { $0.id < $1.id }) ?? allVideos.sorted { $0.localizedName < $1.localizedName } LazyVGrid(columns: columns, spacing: Constants.cardSpacing) { ForEach(videos) { video in NavigationLink(value: NavigationNode.video(video.id)) { VideoCardView(video: video, style: .grid) } .transitionSource(id: video.id, namespace: namespace) .accessibilityLabel(video.localizedName) .buttonStyle(buttonStyle) } } } .navigationDestinationVideo(in: namespace) .padding(Constants.outerPadding) } .scrollClipDisabled() } } var buttonStyle: some PrimitiveButtonStyle { #if os(tvOS) .card #else .plain #endif } } #Preview(traits: .previewData) { LibraryView() } ``` ## VideoCardView.swift ```swift /* Abstract: A view that represents a video card. */ import SwiftUI import SwiftData /// Constants that represent the supported styles for video cards. enum VideoCardStyle { /// A style for a full video card. /// /// This style presents a poster image on top and information about the video /// below, including video description and genres. case full /// A style for cards in the Up Next list. /// /// This style presents a medium-sized poster image on top and a title string below. case upNext /// A style for cards in library view. /// /// This style presents a medium sized poster image with a title string below. case grid /// A style for cards in a collection list /// /// This style presents an image on the leading edge with information about /// the video the trailing edge, including video description and genres. case stack /// A style for up next cards in the watch now view. /// /// This style presents a medium-sized poster image on top and a title string below. case half } /// A view that represents a video in the library. /// /// A user can select a video card to view the video details. struct VideoCardView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass private var isCompact: Bool { horizontalSizeClass == .compact } var video: Video var style: VideoCardStyle = .full var image: Image { Image(video.landscapeImageName) .resizable() } var body: some View { switch style { case .half: PosterCard(image: image, title: video.localizedName) .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) #if os(iOS) || os(visionOS) .hoverEffect() #endif case .upNext: PosterCard(image: image, title: video.localizedName) .frame(width: Constants.upNextVideoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) #if os(iOS) || os(visionOS) .hoverEffect() #endif case .full: VStack { image.scaledToFill() InfoView(video: video) } #if os(macOS) .background(.quaternary) #else .background(.ultraThinMaterial) #endif #if os(iOS) || os(visionOS) .hoverEffect() #endif .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) case .grid: PosterCard(image: image, title: video.localizedName) #if os(iOS) || os(visionOS) .hoverEffect() #endif case .stack: HStack(spacing: 0) { image .scaledToFill() .frame(maxWidth: isCompact ? Constants.stackImageCompactWidth : Constants.stackImageWidth) .cornerRadius(Constants.cornerRadius) .padding([.leading, .vertical], Constants.cardPadding) InfoView(video: video) } #if os(macOS) .background(.quaternary) #else .background(.ultraThinMaterial) #endif #if os(iOS) || os(visionOS) .hoverEffect() #endif .cornerRadius(Constants.cornerRadius) } } } #Preview("Full", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .full) .frame(height: 350) } #Preview("Grid", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .grid) .frame(width: 200, height: 200) } #Preview("Half", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .half) .frame(width: 200, height: 200) } #Preview("Stack", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .stack) .frame(height: 200) } #Preview("UpNext", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .upNext) .frame(height: 150) } ``` ## VideoInfoView.swift ```swift /* Abstract: A view that displays information about a video including its title, description, and genre. */ import SwiftUI import SwiftData /// A view that displays information about a video including its title, description, and genre. struct InfoView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass private var isCompact: Bool { horizontalSizeClass == .compact } let video: Video var body: some View { VStack(alignment: .leading) { Text("(video.formattedYearOfRelease) | (video.localizedContentRating) | (video.formattedDuration)", comment: "Release Year | Rating | Duration") #if os(tvOS) .font(.caption) #else .font(isCompact ? .caption : .headline) #endif .foregroundStyle(.secondary) Text(video.localizedName) .font(isCompact ? .body : .title3) Text(video.localizedSynopsis) .font(isCompact ? .caption : .body) .lineLimit(2, reservesSpace: true) GenreView(genres: video.genres) } .padding(Constants.cardPadding) .frame(maxWidth: .infinity, alignment: .leading) } } /// A view that displays a list of genres for a video. struct GenreView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass private var isCompact: Bool { horizontalSizeClass == .compact } let genres: [Genre] var body: some View { HStack(spacing: Constants.genreSpacing) { ForEach(genres) { Text($0.localizedName) .fixedSize() .font(isCompact ? .caption2 : .caption) .padding(.horizontal, Constants.genreHorizontalPadding) .padding(.vertical, Constants.genreVerticalPadding) .background(Capsule().stroke()) } } } } /// A view that displays the name of a position, followed by one or more people who hold the position in the video. struct RoleView: View { let role: String let people: [Person] var body: some View { let peopleString = people.map { $0.displayName } VStack(alignment: .leading) { Text(role) Text(peopleString.formatted()) } } } /// A view that displays a the video poster image with its title.. struct PosterCard: View { let image: Image let title: String var body: some View { #if os(tvOS) ZStack(alignment: .bottom) { image .scaledToFill() // Material gradient GradientView(style: .ultraThinMaterial, height: 90, startPoint: .bottom) Text(title) .font(.caption.bold()) .padding() } .cornerRadius(Constants.cornerRadius) #else VStack { image .scaledToFill() .cornerRadius(Constants.cornerRadius) Text(title) #if os(visionOS) .font(.title3) #else .font(.body) #endif .lineLimit(1) } #endif } } #Preview(traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return InfoView(video: videos.first!) .frame(width: Constants.videoCardWidth) } ``` ## VideoListView.swift ```swift /* Abstract: A view the presents a horizontally scrollable list of video cards. */ import SwiftUI import SwiftData /// A view the presents a horizontally scrollable list of video cards. struct VideoListView: View { typealias SelectionAction = (Video) -> Void private let title: LocalizedStringKey? private let videos: [Video] private let cardStyle: VideoCardStyle private let selectionAction: SelectionAction? let namespace: Namespace.ID /// Creates a view to display the specified list of videos. /// /// - Parameters: /// - title: An optional title to display above the list. /// - videos: The list of videos to display. /// - cardStyle: The style for the video cards. /// - selectionAction: An optional action that you can specify to directly handle the card selection. /// - namespace: The namespace id of the parent view. /// /// When the app doesn't specify a selection action, the view presents the card as a `NavigationLink. init( title: LocalizedStringKey? = nil, videos: [Video], cardStyle: VideoCardStyle, namespace: Namespace.ID, selectionAction: SelectionAction? = nil ) { self.title = title self.videos = videos self.cardStyle = cardStyle self.namespace = namespace self.selectionAction = selectionAction } var body: some View { Section { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: Constants.cardSpacing) { ForEach(videos) { video in Group { // If the app initializes the view with a selection action closure, // display a video card button that calls it. if let selectionAction { Button { selectionAction(video) } label: { VideoCardView(video: video, style: cardStyle) } } // Otherwise, create a navigation link. else { NavigationLink(value: NavigationNode.video(video.id)) { VideoCardView(video: video, style: cardStyle) } } } .accessibilityLabel(video.localizedName) .transitionSource(id: video.id, namespace: namespace) } } .buttonStyle(buttonStyle) .padding(.leading, Constants.outerPadding) } .scrollClipDisabled() } header: { if let title { Text(title) .font(.title3.bold()) .padding(.vertical, Constants.listTitleVerticalPadding) .padding(.leading, Constants.outerPadding) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) } } } var buttonStyle: some PrimitiveButtonStyle { #if os(tvOS) .card #else .plain #endif } } #Preview("Full", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] @Previewable @Namespace var namespace return NavigationStack { VideoListView(title: "Featured", videos: videos, cardStyle: .full, namespace: namespace) .frame(height: 380) } } ``` ## ViewModifiers.swift ```swift /* Abstract: Custom view modifiers that the app defines. */ import SwiftUI import SwiftData extension View { #if os(visionOS) // A custom modifier in visionOS that manages the presentation and dismissal of the app's environment. func immersionManager() -> some View { self.modifier(ImmersiveSpacePresentationModifier()) } #else // Only used in iOS and tvOS for full-window modal presentation. func presentVideoPlayer() -> some View { #if os(macOS) self.modifier(OpenVideoPlayerModifier()) #else self.modifier(FullScreenCoverModifier()) #endif } #endif func navigationDestinationVideo(in namespace: Namespace.ID) -> some View { self.modifier(NavigationDestinationVideo(namespace: namespace)) } func transitionSource(id: Int, namespace: Namespace.ID) -> some View { self.modifier(TransitionSourceModifier(id: id, namespace: namespace)) } } #if os(visionOS) private struct ImmersiveSpacePresentationModifier: ViewModifier { @Environment(ImmersiveEnvironment.self) private var immersiveEnvironment @Environment(\.openImmersiveSpace) private var openImmersiveSpace @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace func body(content: Content) -> some View { content .onChange(of: immersiveEnvironment.showImmersiveSpace) { _, show in Task { @MainActor in if !immersiveEnvironment.immersiveSpaceIsShown, show { switch await openImmersiveSpace(id: ImmersiveEnvironmentView.id) { case .opened: immersiveEnvironment.immersiveSpaceIsShown = true case .error, .userCancelled: fallthrough @unknown default: immersiveEnvironment.immersiveSpaceIsShown = false immersiveEnvironment.showImmersiveSpace = false } } else if immersiveEnvironment.immersiveSpaceIsShown { await dismissImmersiveSpace() } } } } } #endif #if !os(macOS) private struct FullScreenCoverModifier: ViewModifier { @Environment(PlayerModel.self) private var player @State private var isPresentingPlayer = false func body(content: Content) -> some View { content .fullScreenCover(isPresented: $isPresentingPlayer) { PlayerView() .onAppear { player.play() } .onDisappear { player.reset() } .frame(maxWidth: .infinity, maxHeight: .infinity) .ignoresSafeArea() } // Observe the player's presentation property. .onChange(of: player.presentation, { _, newPresentation in isPresentingPlayer = newPresentation == .fullWindow }) } } #endif private struct NavigationDestinationVideo: ViewModifier { @Environment(\.modelContext) private var context var namespace: Namespace.ID func body(content: Content) -> some View { content .navigationDestination(for: NavigationNode.self) { node in switch node { case .category(let id): if let category = Category(rawValue: id) { CategoryView( category: category, namespace: namespace, navigationPath: [NavigationNode.category(id)]) #if os(iOS) .toolbarRole(.editor) .navigationTransition(.zoom(sourceID: category.id, in: namespace)) #endif } else { ContentUnavailableView("This category isn�t available", systemImage: "list.and.film") } case .video(let id): let descriptor = FetchDescriptor<Video>(predicate: #Predicate<Video> { $0.id == id }) if let video = try? context.fetch(descriptor).first { DetailView(video: video) #if os(iOS) .toolbarRole(.editor) .navigationTransition(.zoom(sourceID: video.id, in: namespace)) #endif } else { ContentUnavailableView("This video isn�t available", systemImage: "list.and.film") } } } } } private struct TransitionSourceModifier: ViewModifier { var id: Int var namespace: Namespace.ID func body(content: Content) -> some View { content #if os(iOS) .matchedTransitionSource(id: id, in: namespace) { src in src .clipShape(.rect(cornerRadius: 10.0)) .shadow(radius: 12.0) .background(.black) } #endif } } #if os(macOS) private struct OpenVideoPlayerModifier: ViewModifier { @Environment(PlayerModel.self) private var player @Environment(\.openWindow) private var openWindow func body(content: Content) -> some View { content .onChange(of: player.presentation, { oldValue, newValue in if newValue == .fullWindow { openWindow(id: PlayerView.identifier) } }) } } #endif ``` ## WatchNowView.swift ```swift /* Abstract: A view that presents the app's content library. */ import SwiftUI import SwiftData /// A view that presents the app's content library. struct WatchNowView: View { @State private var navigationPath = [NavigationNode]() @Namespace private var namespace @Query(filter: #Predicate<Video> { $0.isHero }, sort: \.id) private var heroVideos: [Video] @Query(filter: #Predicate<Video> { $0.isFeatured }, sort: \.id) private var featuredVideos: [Video] @Query(sort: \UpNextItem.createdAt) private var playlist: [UpNextItem] var body: some View { // Wrap the content in a vertically scrolling view. NavigationStack(path: $navigationPath) { ScrollView(showsIndicators: false) { VStack { if let heroVideo = heroVideos.first { HeroView(video: heroVideo, namespace: namespace) } // Display a horizontally scrolling list of videos and playlists. VStack(spacing: 20) { VideoListView(title: "Featured", videos: featuredVideos, cardStyle: .full, namespace: namespace) CategoryListView(title: "Collections", categoryList: Category.collectionsList, namespace: namespace) CategoryListView(title: "Animations", categoryList: Category.animationsList, namespace: namespace) if !playlist.isEmpty { VideoListView(title: "Up Next", videos: playlist.compactMap(\.video), cardStyle: .half, namespace: namespace) } } .padding(.bottom, Constants.outerPadding) } } .scrollClipDisabled() .navigationDestinationVideo(in: namespace) .toolbarBackground(.hidden) #if os(visionOS) .overlay(alignment: .topLeading) { ProfileButtonView() } #endif } } } #Preview(traits: .previewData) { WatchNowView() } ``` ## ImmersiveEnvironmentPickerView.swift ```swift /* Abstract: A view that adds the custom environments to the immersive environment picker in an undocked video player view controller. */ import SwiftUI /// A view that populates the ImmersiveEnvironmentPicker in an undocked AVPlayerViewController. struct ImmersiveEnvironmentPickerView: View { var body: some View { StudioButton(state: .dark) StudioButton(state: .light) } } /// A view for the buttons that appear in the environment picker menu. private struct StudioButton: View { @Environment(ImmersiveEnvironment.self) private var immersiveEnvironment var state: EnvironmentStateType var body: some View { Button { immersiveEnvironment.requestEnvironmentState(state) immersiveEnvironment.loadEnvironment() } label: { Label { Text("Studio", comment: "Show Studio environment") } icon: { Image(["studio_thumbnail", state.displayName.lowercased()].joined(separator: "_")) } Text(state.displayName) } } } ``` ## ImmersiveEnvironmentView.swift ```swift /* Abstract: A view that presents an environment. */ import SwiftUI import RealityKit /// A view that presents an environment. struct ImmersiveEnvironmentView: View { static let id: String = "ImmersiveEnvironmentView" @Environment(ImmersiveEnvironment.self) private var immersiveEnvironment var body: some View { RealityView { content in if let rootEntity = immersiveEnvironment.rootEntity { content.add(rootEntity) } } .onDisappear { immersiveEnvironment.immersiveSpaceIsShown = false immersiveEnvironment.showImmersiveSpace = false immersiveEnvironment.clearEnvironment() } .transition(.opacity) } } ``` ## ProfileButton.swift ```swift /* Abstract: A view that presents an expanding profile button. */ import SwiftUI /// A view that presents an expanding profile button. struct ProfileButtonView: View { var action: () -> Void = {} var body: some View { Button(action: action) { ProfileDetailView() } .buttonStyle(ExpandingProfileButtonStyle()) .padding(Constants.outerPadding) } } /// A view that displays the icon of the profile button. private struct ProfileIconView: View { var body: some View { Image(systemName: "person.crop.circle") .resizable() .scaledToFit() .frame( width: Constants.profileIconSize.width, height: Constants.profileIconSize.height ) } } /// A view that displays the expanded profile button. private struct ProfileDetailView: View { var body: some View { VStack(alignment: .leading) { Text("Anne Johnson") .font(.body) .foregroundStyle(.primary) Text("Switch profiles") .font(.footnote) .foregroundStyle(.tertiary) } } } private struct ExpandingProfileButtonStyle: ButtonStyle { @Environment(\.accessibilityReduceMotion) var reduceMotion func makeBody(configuration: Configuration) -> some View { HStack(spacing: 0) { // Reserve space for the icon. The icon appears in an overlay // so it doesn't scale with the background. Color.clear .frame( width: Constants.collapsedSize.width, height: Constants.collapsedSize.height ) configuration.label .padding(.trailing, 24) .hoverEffect(FadeEffect()) } .hoverEffect(reduceMotion ? HoverEffect(.empty) : HoverEffect(ExpandEffect())) .overlay(alignment: .leading) { // Center the icon over the collapsed button area. ZStack { ProfileIconView().offset(x: 0.5, y: 0.5) } .frame( width: Constants.collapsedSize.width, height: Constants.collapsedSize.height ) } .background { if reduceMotion { // When reduceMotion is enabled, cross-fade between the // collapsed and expanded backgrounds. ZStack(alignment: .leading) { Circle() .fill(.thinMaterial) .hoverEffect(.highlight) .hoverEffect(FadeEffect(opacityFrom: 1, opacityTo: 0)) Capsule() .fill(.thinMaterial) .hoverEffect(.highlight) .hoverEffect(FadeEffect()) } } else { // Otherwise, scale and expand the background. Use a Rectangle // because the expand effect applies a clipShape. Rectangle() .fill(.thinMaterial) .hoverEffect(.highlight) .hoverEffect(ExpandEffect()) } } // Group all effects so they activate together. .hoverEffectGroup() // Scale the button down to provide feedback when a // person presses the button. .scaleEffect(configuration.isPressed ? 0.95 : 1.0) } } /// Expands and scales content on hover. private struct ExpandEffect: CustomHoverEffect { func body(content: Content) -> some CustomHoverEffect { content.hoverEffect { effect, isActive, proxy in // Reveal content after a delay. effect.animation(.default.delay(isActive ? 0.8 : 0.2)) { $0.clipShape( .capsule.size( width: isActive ? proxy.size.width : proxy.size.height, height: proxy.size.height, anchor: .leading ) ) } // Immediately scale the content on hover. .animation(isActive ? .easeOut(duration: 0.8) : .easeIn(duration: 0.2).delay(0.4)) { $0.scaleEffect( isActive ? 1.1 : 1, // Anchor the scale in the center of the collapsed // button frame. anchor: UnitPoint(x: (proxy.size.height / 2) / proxy.size.width, y: 0.5) ) } } } } /// Fades content between the `from` and `to` properties on hover. private struct FadeEffect: CustomHoverEffect { var opacityFrom: Double = 0 var opacityTo: Double = 1 func body(content: Content) -> some CustomHoverEffect { content.hoverEffect { effect, isActive, _ in effect.animation(.default.delay(isActive ? 0.8 : 0.2)) { $0.opacity(isActive ? opacityTo : opacityFrom) } } } } extension Constants { fileprivate static let profileIconSize = CGSize(width: 44, height: 44) fileprivate static let profileIconPadding: CGFloat = 6 fileprivate static let collapsedSize = CGSize( width: profileIconPadding + profileIconSize.width + profileIconPadding, height: profileIconPadding + profileIconSize.height + profileIconPadding ) } ``` ## TrailerView.swift ```swift /* Abstract: A view that displays a poster image that you tap to watch a trailer. */ import SwiftUI import SwiftData /// A view that displays a poster image that you tap to watch a trailer. struct TrailerView: View { @State private var isPosterVisible = true @Environment(PlayerModel.self) private var model let video: Video var body: some View { if isPosterVisible { Button { // Loads the video for inline playback. model.loadVideo(video) withAnimation { isPosterVisible = false } } label: { TrailerPosterView(video: video) } .buttonStyle(.plain) .buttonBorderShape(.roundedRectangle) } else { PlayerView(controlsStyle: .custom) .onAppear { if model.shouldAutoPlay { model.play() } } } } } /// A view that displays the poster image with a play button image over it. private struct TrailerPosterView: View { let video: Video var body: some View { ZStack { Image(video.landscapeImageName) .resizable() .frame(maxWidth: .infinity, maxHeight: .infinity) VStack(spacing: 2) { Image(systemName: "play.fill") .font(.system(size: 24.0)) .padding(12) .background(.thinMaterial) .clipShape(.circle) Text("Preview") .font(.title3) .shadow(color: .black.opacity(0.5), radius: 3, x: 1, y: 1) } } } } #Preview("Trailer View", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return TrailerView(video: videos.first!) } #Preview("Trailer Poster View", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return TrailerPosterView(video: videos.first!) } ``` ## Package.swift ```swift // swift-tools-version:6.0 /* Abstract: Extensions to the Studio asset. */ // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Studio", platforms: [ .visionOS(.v2), .macOS(.v15), .iOS(.v18) ], products: [ .library( name: "Studio", targets: ["Studio"]) ], dependencies: [ ], targets: [ .target( name: "Studio", dependencies: []) ] ) ``` ## Studio.swift ```swift /* Abstract: Studio project bundle. */ import Foundation /// Bundle for the Studio project. public let studioBundle = Bundle.module ``` ## FocusCookbookApp.swift ```swift /* Abstract: The main app, which creates a scene that contains a window group, displaying the root content view. */ import SwiftUI @main struct FocusCookbookApp: App { var body: some Scene { WindowGroup { ContentView() } #if os(macOS) .defaultSize(width: 800, height: 600) #endif .commands { SidebarCommands() RecipeCommands() } } } ``` ## ChecklistToggleStyle.swift ```swift /* Abstract: A toggle style that appears as a dashed gray circle symbol when toggled off and a green checkmark symbol when toggled on. */ import SwiftUI struct ChecklistToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { Button { configuration.isOn.toggle() } label: { Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle.dashed") .foregroundStyle(configuration.isOn ? .green : .gray) .font(.system(size: 20)) .contentTransition(.symbolEffect) .animation(.linear, value: configuration.isOn) } .buttonStyle(.plain) .contentShape(.circle) } } extension ToggleStyle where Self == ChecklistToggleStyle { static var checklist: ChecklistToggleStyle { .init() } } ``` ## GroceryList.swift ```swift /* Abstract: A data model for a grocery list. */ import SwiftUI struct GroceryList: Codable { struct Item: Codable, Hashable, Identifiable { var id = UUID() var name: String var isObtained: Bool = false } var items: [Item] = [] mutating func addItem() -> Item { let item = GroceryList.Item(name: "") items.append(item) return item } } extension GroceryList { static var sample = GroceryList(items: [ GroceryList.Item(name: "Apples"), GroceryList.Item(name: "Lasagna"), GroceryList.Item(name: "") ]) } ``` ## GroceryListButton.swift ```swift /* Abstract: An button that presents a Grocery List when its action is invoked. */ import SwiftUI struct GroceryListButton: View { @Binding var isActive: Bool var body: some View { Button { isActive = true } label: { Label("Grocery List", systemImage: "checklist") } .help("Show grocery list") } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { GroceryListButton(isActive: .constant(false)) } ``` ## GroceryListView.swift ```swift /* Abstract: A view that displays an editable list of grocery items. */ import SwiftUI struct GroceryListView: View { @Environment(\.dismiss) private var dismiss @Binding var list: GroceryList @FocusState private var currentItemID: GroceryList.Item.ID? var body: some View { List($list.items) { $item in HStack { Toggle("Obtained", isOn: $item.isObtained) TextField("Item Name", text: $item.name) .onSubmit { addEmptyItem() } .focused($currentItemID, equals: item.id) } } .toolbar { ToolbarItem(placement: .cancellationAction) { doneButton } ToolbarItem(placement: .primaryAction) { newItemButton } } .defaultFocus($currentItemID, list.items.last?.id) } // MARK: New item private func addEmptyItem() { let newItem = list.addItem() currentItemID = newItem.id } private var newItemButton: some View { Button { addEmptyItem() } label: { Label("New Item", systemImage: "plus") } } private var doneButton: some View { Button { dismiss() } label: { Text("Done") } } } /// The main content view for the Grocery List sheet. struct GroceryListContentView: View { @Binding var list: GroceryList var body: some View { NavigationStack { GroceryListView(list: $list) .toggleStyle(.checklist) .navigationTitle("Grocery List") #if os(macOS) .frame(minWidth: 500, minHeight: 400) #endif } } } ``` ## Category.swift ```swift /* Abstract: An enumeration of recipe groupings used to display sidebar items. */ import SwiftUI enum Category: Int, Hashable, CaseIterable, Identifiable, Codable { case dessert case pancake case salad case sandwich var id: Int { rawValue } var localizedName: LocalizedStringKey { switch self { case .dessert: return "Dessert" case .pancake: return "Pancake" case .salad: return "Salad" case .sandwich: return "Sandwich" } } } ``` ## DataModel.swift ```swift /* Abstract: An observable data model of published recipes and miscellaneous groupings. */ import SwiftUI import Observation @Observable final class DataModel { private var recipes: [Recipe] = [] private var recipesByID: [Recipe.ID: Recipe]? = nil static let shared: DataModel = DataModel() private init() { recipes = builtInRecipes } func recipes(in category: Category?) -> [Recipe] { recipes .filter { $0.category == category } .sorted { $0.name < $1.name } } func recipes(relatedTo recipe: Recipe) -> [Recipe] { recipes .filter { recipe.related.contains($0.id) } .sorted { $0.name < $1.name } } subscript(recipeID: Recipe.ID?) -> Recipe? { guard let recipeID else { return nil } if recipesByID == nil { recipesByID = Dictionary( uniqueKeysWithValues: recipes.map { ($0.id, $0) }) } return recipesByID![recipeID] } var recipeOfTheDay: Recipe { recipes[0] } } private let builtInRecipes: [Recipe] = { var recipes = [ "Apple Pie": Recipe( name: "Apple Pie", category: .dessert, ingredients: applePie.ingredients ), "Baklava": Recipe( name: "Baklava", category: .dessert, ingredients: [] ), "Bolo de Rolo": Recipe( name: "Bolo de Rolo", category: .dessert, ingredients: [] ), "Chocolate Crackles": Recipe( name: "Chocolate Crackles", category: .dessert, ingredients: [] ), "Cr�me Br�l�e": Recipe( name: "Cr�me Br�l�e", category: .dessert, ingredients: [] ), "Fruit Pie Filling": Recipe( name: "Fruit Pie Filling", category: .dessert, ingredients: [] ), "Kanom Thong Ek": Recipe( name: "Kanom Thong Ek", category: .dessert, ingredients: [] ), "Mochi": Recipe( name: "Mochi", category: .dessert, ingredients: [] ), "Marzipan": Recipe( name: "Marzipan", category: .dessert, ingredients: [] ), "Pie Crust": Recipe( name: "Pie Crust", category: .dessert, ingredients: pieCrust.ingredients ), "Shortbread Biscuits": Recipe( name: "Shortbread Biscuits", category: .dessert, ingredients: [] ), "Tiramisu": Recipe( name: "Tiramisu", category: .dessert, ingredients: [] ), "Cr�pe": Recipe( name: "Cr�pe", category: .pancake, ingredients: []), "Jianbing": Recipe( name: "Jianbing", category: .pancake, ingredients: []), "American": Recipe( name: "American", category: .pancake, ingredients: []), "Dosa": Recipe( name: "Dosa", category: .pancake, ingredients: []), "Injera": Recipe( name: "Injera", category: .pancake, ingredients: []), "Acar": Recipe( name: "Acar", category: .salad, ingredients: []), "Ambrosia": Recipe( name: "Ambrosia", category: .salad, ingredients: []), "Bok L'hong": Recipe( name: "Bok L'hong", category: .salad, ingredients: []), "Caprese": Recipe( name: "Caprese", category: .salad, ingredients: []), "Ceviche": Recipe( name: "Ceviche", category: .salad, ingredients: []), "�oban Salatas�": Recipe( name: "�oban Salatas�", category: .salad, ingredients: []), "Fiambre": Recipe( name: "Fiambre", category: .salad, ingredients: []), "Kachumbari": Recipe( name: "Kachumbari", category: .salad, ingredients: []), "Ni�oise": Recipe( name: "Ni�oise", category: .salad, ingredients: []) ] recipes["Apple Pie"]!.related = [ recipes["Pie Crust"]!.id, recipes["Fruit Pie Filling"]!.id ] recipes["Pie Crust"]!.related = [recipes["Fruit Pie Filling"]!.id] recipes["Fruit Pie Filling"]!.related = [recipes["Pie Crust"]!.id] return Array(recipes.values) }() let applePie = """ 3�4 cup white sugar 2 Tbsp. all-purpose flour 1�2 tsp. ground cinnamon 1�4 tsp. ground nutmeg 1�2 tsp. lemon zest 7 cups thinly sliced apples 2 tsp. lemon juice 1 Tbsp. butter 1 recipe pastry for a 9-inch double-crust pie 4 Tbsp. milk """ let pieCrust = """ 2 1�2 cups all-purpose flour 1 Tbsp. powdered sugar 1 tsp. sea salt 1�2 cup shortening 1�2 cup butter (cold, cut into small pieces) ? cup cold water (plus more as needed) """ extension String { var ingredients: [Ingredient] { split(separator: "\n", omittingEmptySubsequences: true) .map { Ingredient(description: String($0)) } } } ``` ## Ingredient.swift ```swift /* Abstract: A data model for an ingredient for a given recipe. */ import SwiftUI struct Ingredient: Hashable, Identifiable { let id = UUID() var description: String } ``` ## NavigationModel.swift ```swift /* Abstract: A navigation model used to persist and restore the navigation state. */ import SwiftUI import Observation @Observable final class NavigationModel: Codable { var selectedCategory: Category? = nil var recipePath: [Recipe.ID] = [] var groceryList: GroceryList = GroceryList() private var decoder = JSONDecoder() private var encoder = JSONEncoder() init(selectedCategory: Category? = nil, recipePath: [Recipe.ID] = [], groceryList: GroceryList = GroceryList() ) { self.selectedCategory = selectedCategory self.recipePath = recipePath self.groceryList = groceryList } var selectedRecipeID: Recipe.ID? { get { recipePath.first } set { recipePath = [newValue].compactMap { $0 } } } var jsonData: Data? { get { try? encoder.encode(self) } set { guard let data = newValue, let model = try? decoder.decode(Self.self, from: data) else { return } selectedCategory = model.selectedCategory recipePath = model.recipePath groceryList = model.groceryList } } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.selectedCategory = try container.decodeIfPresent( Category.self, forKey: .selectedCategory) let recipePathIDs = try container.decode( [Recipe.ID].self, forKey: .recipePathIDs) self.recipePath = recipePathIDs self.groceryList = try container.decode( GroceryList.self, forKey: .groceryList) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(selectedCategory, forKey: .selectedCategory) try container.encode(recipePath, forKey: .recipePathIDs) try container.encode(groceryList, forKey: .groceryList) } enum CodingKeys: String, CodingKey { case selectedCategory case recipePathIDs case groceryList } } ``` ## Recipe.swift ```swift /* Abstract: A data model for a recipe and its metadata, including its related recipes. */ import SwiftUI struct Recipe: Hashable, Identifiable { let id = UUID() var name: String var category: Category var ingredients: [Ingredient] var related: [Recipe.ID] = [] var imageName: String? = nil var rating: Rating? } extension Recipe { static var mock: Recipe { DataModel.shared.recipeOfTheDay } } ``` ## Rating.swift ```swift /* Abstract: An enumeration that represents sentiment about an individual recipe. */ import SwiftUI enum Rating: Int, CaseIterable, Identifiable { case meh case yummy case delicious var id: RawValue { rawValue } var emoji: String { switch self { case .meh: return "?" case .yummy: return "?" case .delicious: return "?" } } var localizedName: LocalizedStringKey { switch self { case .meh: return "Meh" case .yummy: return "Yummy" case .delicious: return "Delicious" } } var previous: Rating? { let ratings = Rating.allCases let index = ratings.firstIndex(of: self)! guard index != ratings.startIndex else { return nil } let previousIndex = ratings.index(before: index) return ratings[previousIndex] } var next: Rating? { let ratings = Rating.allCases let index = ratings.firstIndex(of: self)! let nextIndex = ratings.index(after: index) guard nextIndex != ratings.endIndex else { return nil } return ratings[nextIndex] } } ``` ## RatingPicker.swift ```swift /* Abstract: A custom control to select the sentiment about a recipe. */ import SwiftUI /// The shape of the rating picker control. private let shape: some Shape = Capsule() struct RatingPicker<Label: View>: View { @Environment(\.layoutDirection) private var layoutDirection /// A view that describes the use of the rating picker. private var label: Label /// A binding of the rating represented by the control, if any. @Binding private var rating: Rating? /// The last selected rating; used to restore the rating when toggled /// with the Space key. @State private var lastRatingSelection: Rating? /// Creates an instance of a rating picker. /// /// - Parameters: /// - rating: A `Binding` to the variable that holds the selected /// `Rating` or `nil` if none is selected. /// - label: A view that describes the use of the rating picker., init( rating: Binding<Rating?>, @ViewBuilder label: () -> Label ) { _rating = rating self.label = label() } var body: some View { LabeledContent { content } label: { Text("Rating") } } private var content: some View { EmojiContainer { ratingOptions } .contentShape(shape) .focusable(interactions: .activate) #if os(macOS) .onMoveCommand { direction in selectRating(in: direction, layoutDirection: layoutDirection) } .onKeyPress(.space) { rating = rating == nil ? (lastRatingSelection ?? .yummy) : nil return .handled } #endif } /// A view that displays the rating picker's options. private var ratingOptions: some View { HStack(spacing: 2) { ForEach(Rating.allCases) { rating in EmojiView( rating: rating, isSelected: self.rating == rating ) { self.rating = self.rating != rating ? rating : nil } .zIndex(self.rating == rating ? 0 : 1) } } .onChange(of: rating) { oldValue, newValue in if let rating = newValue { lastRatingSelection = rating } } } #if os(macOS) /// Selects the rating in the given direction, taking into account the /// layout direction for right-to-left language environments. private func selectRating( in direction: MoveCommandDirection, layoutDirection: LayoutDirection ) { let direction = direction.transform(from: layoutDirection) if let rating { switch direction { case .left: guard let previousRating = rating.previous else { return } self.rating = previousRating case .right: guard let nextRating = rating.next else { return } self.rating = nextRating default: break } } else { // If no rating is already selected, select one. switch direction { case .left: self.rating = lastRatingSelection ?? Rating.allCases.last case .right: self.rating = lastRatingSelection ?? Rating.allCases.first default: break } } } #endif } /// A container view that provides the base styling of the control. private struct EmojiContainer<Content: View>: View { @Environment(\.isFocused) private var isFocused private var content: Content /// The control's border color. private var strokeColor: Color { #if os(watchOS) isFocused ? .green : .clear #else .clear #endif } init(@ViewBuilder content: @escaping () -> Content) { self.content = content() } var body: some View { content .frame(height: 32) .font(.system(size: 24)) .padding(.horizontal, 8) .padding(.vertical, 6) .background(.quaternary) .clipShape(shape) #if os(watchOS) .overlay( RatingPicker.shape .strokeBorder(strokeColor, lineWidth: 1.5) ) #endif } } /// A view that displays an emoji representing a rating and performs the /// given action when the emoji is tapped or clicked. private struct EmojiView: View { /// The rating that the emoji represents. private var rating: Rating /// Whether this rating is selected. private var isSelected: Bool /// An action to perform when the emoji is tapped or clicked. private var action: () -> Void init(rating: Rating, isSelected: Bool, action: @escaping () -> Void) { self.rating = rating self.isSelected = isSelected self.action = action } var body: some View { ZStack { Circle() .fill(isSelected ? Color.accentColor : Color.clear) Text(verbatim: rating.emoji) .onTapGesture { action() } .accessibilityLabel(rating.localizedName) } } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { Group { RatingPicker(rating: .constant(.delicious)) { Text("Rating") } .labelsHidden() RatingPicker(rating: .constant(.delicious)) { Text("Rating") } .labelsHidden() .environment(\.layoutDirection, .rightToLeft) } } ``` ## ContentView.swift ```swift /* Abstract: The main content view the app uses to present the navigation experience picker and change the app navigation architecture based on the user selection. */ import SwiftUI struct ContentView: View { @State private var showGroceryList: Bool = false @SceneStorage("model") private var model: Data? @State private var navigationModel = NavigationModel(groceryList: .sample) var body: some View { RecipeNavigationView(navigationModel: navigationModel, showGroceryList: $showGroceryList) .environment(navigationModel) .sheet(isPresented: $showGroceryList) { GroceryListContentView(list: $navigationModel.groceryList) } #if os(macOS) .toolbar { GroceryListButton(isActive: $showGroceryList) } #endif .onAppear { if let jsonData = model { navigationModel.jsonData = jsonData } model = navigationModel.jsonData } } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { ContentView() } ``` ## RecipeCommands.swift ```swift /* Abstract: Commands that act upon a recipe. */ import SwiftUI struct SelectedRecipeKey: FocusedValueKey { typealias Value = Recipe } extension FocusedValues { var selectedRecipe: SelectedRecipeKey.Value? { get { self[SelectedRecipeKey.self] } set { self[SelectedRecipeKey.self] = newValue } } } struct RecipeCommands: Commands { @FocusedValue(\.selectedRecipe) private var selectedRecipe: Recipe? var body: some Commands { CommandMenu("Recipe") { Group { Button { addStep(for: selectedRecipe) } label: { if let selectedRecipe { Text("Add Step for (selectedRecipe.name)�") } else { Text("Add Step�") } } Divider() Button("Favorite") { favorite(selectedRecipe) } Divider() Button("Add to Grocery List") { addIngredientsToGroceryList(for: selectedRecipe) } } .disabled(selectedRecipe == nil) } } private func addStep(for recipe: Recipe?) { // ... } private func favorite(_ recipe: Recipe?) { // ... } private func addIngredientsToGroceryList(for recipe: Recipe?) { // ... } } ``` ## RecipeDetail.swift ```swift /* Abstract: A detail view the app uses to display the metadata for a given recipe, as well as its related recipes. */ import SwiftUI struct RecipeDetail<Link: View>: View { var recipe: Recipe var relatedLink: (Recipe) -> Link var body: some View { Content(recipe: recipe, relatedLink: relatedLink) .focusedSceneValue(\.selectedRecipe, recipe) } } private struct Content<Link: View>: View { var recipe: Recipe var dataModel = DataModel.shared var relatedLink: (Recipe) -> Link var body: some View { ScrollView { ViewThatFits(in: .horizontal) { wideDetails narrowDetails } .scenePadding() } .navigationTitle(recipe.name) } private var wideDetails: some View { VStack(alignment: .leading, spacing: 22) { HStack(alignment: .top) { VStack { image ratingPicker } VStack(alignment: .leading) { title.padding(.bottom) ingredients } .padding() } Divider() relatedRecipes } } private var narrowDetails: some View { let alignment: HorizontalAlignment #if os(macOS) alignment = .leading #else alignment = .center #endif return VStack(alignment: alignment, spacing: 22) { title VStack { image ratingPicker } ingredients Divider() relatedRecipes } } private var title: some View { #if os(macOS) Text(recipe.name) .font(.largeTitle.bold()) #else EmptyView() #endif } private var image: some View { RecipePhoto(recipe: recipe) .frame(width: 300, height: 300) .clipShape(.rect(cornerRadius: 20)) } @State private var rating: Rating? private var ratingPicker: some View { RatingPicker(rating: $rating) { Text("Rating") } .labelsHidden() } @ViewBuilder private var ingredients: some View { VStack(alignment: .leading) { Text("Ingredients") .font(.title2.bold()) .padding(.bottom, 8) VStack(alignment: .leading) { ForEach(recipe.ingredients) { ingredient in HStack(alignment: .firstTextBaseline) { Text("�") Text(ingredient.description) } } } } .frame(minWidth: 300, alignment: .leading) } @ViewBuilder private var relatedRecipes: some View { if !recipe.related.isEmpty { VStack(alignment: .leading) { Text("Related Recipes") .font(.headline) .padding(.bottom, 8) LazyVGrid(columns: columns, alignment: .leading) { let relatedRecipes = dataModel.recipes(relatedTo: recipe) ForEach(relatedRecipes) { relatedRecipe in relatedLink(relatedRecipe) } } } } } private var columns: [GridItem] { [ GridItem(.adaptive(minimum: 120, maximum: 120), spacing: 20) ] } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { RecipeDetail(recipe: .mock) { _ in EmptyView() } } ``` ## RecipeGrid.swift ```swift /* Abstract: A grid of recipe tiles, based on a given recipe category. */ import SwiftUI struct RecipeGrid: View { var dataModel = DataModel.shared /// The category of recipes to display. let category: Category? /// The recipes of the category. private var recipes: [Recipe] { dataModel.recipes(in: category) } /// A `Binding` to the identifier of the selected recipe. @Binding var selection: Recipe.ID? @Environment(\.layoutDirection) private var layoutDirection @Environment(NavigationModel.self) private var navigationModel /// The currently-selected recipe. private var selectedRecipe: Recipe? { dataModel[selection] } private func gridItem(for recipe: Recipe) -> some View { RecipeTile(recipe: recipe, isSelected: selection == recipe.id) .id(recipe.id) .padding(Self.spacing) #if os(macOS) .onTapGesture { selection = recipe.id } .simultaneousGesture(TapGesture(count: 2).onEnded { navigationModel.selectedRecipeID = recipe.id }) #else .onTapGesture { navigationModel.selectedRecipeID = recipe.id } #endif } var body: some View { if let category = category { container { geometryProxy, scrollViewProxy in LazyVGrid(columns: columns) { ForEach(recipes) { recipe in gridItem(for: recipe) } } .padding(Self.spacing) .focusable() .focusEffectDisabled() .focusedValue(\.selectedRecipe, selectedRecipe) #if os(macOS) .onMoveCommand { direction in return selectRecipe( in: direction, layoutDirection: layoutDirection, geometryProxy: geometryProxy, scrollViewProxy: scrollViewProxy) } #endif .onKeyPress(.return, action: { if let recipe = selectedRecipe { navigate(to: recipe) return .handled } else { return .ignored } }) .onKeyPress(.escape) { selection = nil return .handled } .onKeyPress(characters: .alphanumerics, phases: .down) { keyPress in selectRecipe( matching: keyPress.characters, scrollViewProxy: scrollViewProxy) } } .navigationTitle(category.localizedName) .navigationDestination(for: Recipe.ID.self) { recipeID in if let recipe = dataModel[recipeID] { RecipeDetail(recipe: recipe) { relatedRecipe in RelatedRecipeLink(recipe: relatedRecipe) } } } } else { ContentUnavailableView("Choose a category", systemImage: "fork.knife") .navigationTitle("") } } private func container<Content: View>( @ViewBuilder content: @escaping ( _ geometryProxy: GeometryProxy, _ scrollViewProxy: ScrollViewProxy) -> Content ) -> some View { GeometryReader { geometryProxy in ScrollViewReader { scrollViewProxy in ScrollView { content(geometryProxy, scrollViewProxy) } } } } // MARK: Keyboard selection private func navigate(to recipe: Recipe) { navigationModel.selectedRecipeID = recipe.id } #if os(macOS) private func selectRecipe( in direction: MoveCommandDirection, layoutDirection: LayoutDirection, geometryProxy: GeometryProxy, scrollViewProxy: ScrollViewProxy ) { let direction = direction.transform(from: layoutDirection) let rowWidth = geometryProxy.size.width - RecipeGrid.spacing * 2 let recipesPerRow = Int(floor(rowWidth / RecipeTile.size)) var newIndex: Int if let currentIndex = recipes.firstIndex(where: { $0.id == selection }) { switch direction { case .left: if currentIndex % recipesPerRow == 0 { return } newIndex = currentIndex - 1 case .right: if currentIndex % recipesPerRow == recipesPerRow - 1 { return } newIndex = currentIndex + 1 case .up: newIndex = currentIndex - recipesPerRow case .down: newIndex = currentIndex + recipesPerRow @unknown default: return } } else { newIndex = 0 } if newIndex >= 0 && newIndex < recipes.count { selection = recipes[newIndex].id scrollViewProxy.scrollTo(selection) } } #endif private func selectRecipe( matching characters: String, scrollViewProxy: ScrollViewProxy ) -> KeyPress.Result { if let matchedRecipe = recipes.first(where: { recipe in recipe.name.lowercased().starts(with: characters) }) { selection = matchedRecipe.id scrollViewProxy.scrollTo(selection) return .handled } return .ignored } // MARK: Grid layout private static let spacing: CGFloat = 10 private var columns: [GridItem] { [ GridItem(.adaptive(minimum: RecipeTile.size), spacing: 0) ] } } #if os(macOS) extension MoveCommandDirection { /// Flip direction for right-to-left language environments. /// Learn more: https://developer.apple.com/design/human-interface-guidelines/right-to-left func transform(from layoutDirection: LayoutDirection) -> MoveCommandDirection { if layoutDirection == .rightToLeft { switch self { case .left: return .right case .right: return .left default: break } } return self } } #endif ``` ## RecipeNavigationView.swift ```swift /* Abstract: The content view for the two-column navigation split view experience. */ import SwiftUI struct RecipeNavigationView: View { @Bindable var navigationModel: NavigationModel @Binding var showGroceryList: Bool var categories = Category.allCases var dataModel = DataModel.shared @State private var selectedRecipe: Recipe.ID? var body: some View { NavigationSplitView { List(categories, selection: $navigationModel.selectedCategory) { category in NavigationLink(category.localizedName, value: category) } .navigationTitle("Categories") #if os(iOS) .toolbar { GroceryListButton(isActive: $showGroceryList) } #endif } detail: { NavigationStack(path: $navigationModel.recipePath) { RecipeGrid(category: navigationModel.selectedCategory, selection: $selectedRecipe) } } } } ``` ## RecipePhoto.swift ```swift /* Abstract: A photo view for a given recipe, displaying the recipe's image or a placeholder. */ import SwiftUI struct RecipePhoto: View { var recipe: Recipe var body: some View { if let imageName = recipe.imageName { Image(imageName) .resizable() .aspectRatio(contentMode: .fit) } else { ZStack { Rectangle() .fill(.tertiary) Image(systemName: "camera") .font(.system(size: 64)) .foregroundStyle(.secondary) } } } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { RecipePhoto(recipe: .mock) } ``` ## RecipeTile.swift ```swift /* Abstract: A recipe tile, displaying the recipe's photo and name. */ import SwiftUI struct RecipeTile: View { var recipe: Recipe var isSelected: Bool private var strokeStyle: AnyShapeStyle { isSelected ? AnyShapeStyle(.selection) : AnyShapeStyle(.clear) } var body: some View { VStack { photoView captionView } } } extension RecipeTile { private var photoView: some View { RecipePhoto(recipe: recipe) .frame(minWidth: 120, maxWidth: Self.size) .aspectRatio(1, contentMode: .fill) .clipShape(.containerRelative) .padding(Self.selectionStrokeWidth) .overlay( ContainerRelativeShape() .inset(by: -Self.selectionStrokeWidth / 1.5) .strokeBorder( strokeStyle, lineWidth: Self.selectionStrokeWidth) ) .shadow(color: .black.opacity(0.05), radius: 0.5, x: 0, y: -1) .shadow(color: .black.opacity(0.1), radius: 3, x: 0, y: 2) .containerShape(.rect(cornerRadius: 20)) } private var captionView: some View { Text(recipe.name) .lineLimit(1) .truncationMode(.tail) .font(.headline) } } extension RecipeTile { static let size: CGFloat = 240 static let selectionStrokeWidth: CGFloat = 4 } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { RecipeTile(recipe: .mock, isSelected: true) } ``` ## RelatedRecipeLink.swift ```swift /* Abstract: A recipe tile, displaying the recipe's photo and name, that displays related recipes in the recipe detail view. */ import SwiftUI struct RelatedRecipeButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .contentShape(.rect(cornerRadius: 20)) .opacity(configuration.isPressed ? 0.8 : 1.0) } } struct RelatedRecipeLink: View { var recipe: Recipe private var imageShape: RoundedRectangle { .rect(cornerRadius: 20) } var body: some View { NavigationLink(value: recipe.id) { VStack { RecipePhoto(recipe: recipe) .frame(width: 120) .aspectRatio(1, contentMode: .fill) .clipShape(imageShape) .overlay( imageShape .stroke(.gray.opacity(0.3), lineWidth: 0.5) ) Text(recipe.name) .lineLimit(1) .truncationMode(.tail) .font(.caption) } } .buttonStyle(RelatedRecipeButtonStyle()) } } @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) #Preview { RelatedRecipeLink(recipe: .mock) } ``` ## AccountView.swift ```swift /* Abstract: The account view where the user can sign in and out. */ import SwiftUI import FoodTruckKit import StoreKit import AuthenticationServices struct AccountView: View { @ObservedObject var model: FoodTruckModel @EnvironmentObject private var accountStore: AccountStore @Environment(\.authorizationController) private var authorizationController @State private var isSignUpSheetPresented = false @State private var isSignOutAlertPresented = false var body: some View { Form { if case let .authenticated(username) = accountStore.currentUser { Section { HStack { Image(systemName: "person.fill") .font(.system(.largeTitle, design: .rounded)) .fontWeight(.semibold) .foregroundColor(.white) .frame(width: 60, height: 60) .background(Color.accentColor.gradient, in: Circle()) Text(username) .font(.system(.title3, design: .rounded)) .fontWeight(.medium) } } } #if os(iOS) NavigationLink(value: "In-app purchase support") { Label("In-app purchase support", systemImage: "questionmark.circle") } #else Section { LabeledContent("Purchases") { Button("Restore missing purchases") { Task(priority: .userInitiated) { try await AppStore.sync() } } } } #endif Section { if accountStore.isSignedIn { LabeledContent("Sign out") { Button("Sign Out", role: .destructive) { isSignOutAlertPresented = true } .frame(maxWidth: .infinity) } .labelsHidden() } else { LabeledContent("Use existing account") { Button("Sign In") { Task { await signIn() } } } LabeledContent("Create new account") { Button("Sign Up") { isSignUpSheetPresented = true } } } } } .formStyle(.grouped) .navigationTitle("Account") #if os(iOS) .navigationDestination(for: String.self) { _ in StoreSupportView() } #else .frame(maxWidth: 500, maxHeight: .infinity) #endif .sheet(isPresented: $isSignUpSheetPresented) { NavigationStack { SignUpView(model: model) } } .alert(isPresented: $isSignOutAlertPresented) { signOutAlert } } private func signIn() async { await accountStore.signIntoPasskeyAccount(authorizationController: authorizationController) } private var signOutAlert: Alert { Alert( title: Text("Are you sure you want to sign out?"), primaryButton: .destructive(Text("Sign Out")) { accountStore.signOut() }, secondaryButton: .cancel() ) } } struct AccountView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() @StateObject private var accountStore = AccountStore() var body: some View { AccountView(model: model) .environmentObject(accountStore) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## SignUpView.swift ```swift /* Abstract: The view where the user can sign up for an account. */ import SwiftUI import FoodTruckKit import AuthenticationServices struct SignUpView: View { private enum FocusElement { case username case password } private enum SignUpType { case passkey case password } @ObservedObject var model: FoodTruckModel @EnvironmentObject private var accountStore: AccountStore @Environment(\.authorizationController) private var authorizationController @Environment(\.dismiss) private var dismiss @FocusState private var focusedElement: FocusElement? @State private var usePasskey: Bool = true @State private var username = "" @State private var password = "" var body: some View { Form { Section { LabeledContent("User name") { TextField("User name", text: $username) .textContentType(.username) .multilineTextAlignment(.trailing) #if os(iOS) .textInputAutocapitalization(.never) .keyboardType(.emailAddress) #endif .focused($focusedElement, equals: .username) .labelsHidden() } if !usePasskey { LabeledContent("Password") { SecureField("Password", text: $password) #if os(macOS) .textContentType(.password) #elseif os(iOS) .textContentType(.newPassword) #endif .multilineTextAlignment(.trailing) .focused($focusedElement, equals: .password) .labelsHidden() } } LabeledContent("Use Passkey") { Toggle("Use Passkey", isOn: $usePasskey) .labelsHidden() } } header: { Text("Create an account") } footer: { Label(""" When you sign up with a passkey, all you need is a user name. \ The passkey will be available on all of your devices. """, systemImage: "person.badge.key.fill") } } .formStyle(.grouped) .animation(.default, value: usePasskey) #if !os(iOS) .frame(maxWidth: 500) #endif .navigationTitle("Sign up") .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Sign Up") { Task { await signUp() } } .disabled(!isFormValid) } ToolbarItem(placement: .cancellationAction) { Button("Cancel", role: .cancel) { print("Canceled sign up.") dismiss() } } } .onAppear { focusedElement = .username } } private func signUp() async { Task { if usePasskey { await accountStore.createPasskeyAccount(authorizationController: authorizationController, username: username) } else { await accountStore.createPasswordAccount(username: username, password: password) } dismiss() } } private var isFormValid: Bool { if usePasskey { return !username.isEmpty } else { return !username.isEmpty && !password.isEmpty } } } struct SignUpView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() @StateObject private var accountStore = AccountStore() var body: some View { SignUpView(model: model) .environmentObject(accountStore) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## App.swift ```swift /* Abstract: The single entry point for the Food Truck app on iOS and macOS. */ import SwiftUI import FoodTruckKit /// The app's entry point. /// /// The `FoodTruckApp` object is the app's entry point. Additionally, this is the object that keeps the app's state in the `model` and `store` parameters. /// @main struct FoodTruckApp: App { /// The app's state. @StateObject private var model = FoodTruckModel() /// The in-app purchase store's state. @StateObject private var accountStore = AccountStore() /// The app's body function. /// /// This app uses a [`WindowGroup`](https://developer.apple.com/documentation/swiftui/windowgroup) scene, which contains the root view of the app, ``ContentView``. /// On macOS, the [`defaultSize(width:height)`](https://developer.apple.com/documentation/swiftui/scene/defaultsize(_:)) modifier /// gives the app an appropriate default size on launch. Similarly, a [`MenuBarExtra`](https://developer.apple.com/documentation/swiftui/menubarextra) /// scene is used on macOS to insert a menu into the right side of the menu bar. var body: some Scene { WindowGroup { ContentView(model: model, accountStore: accountStore) } #if os(macOS) .defaultSize(width: 1000, height: 650) #endif #if os(macOS) MenuBarExtra { ScrollView { VStack(spacing: 0) { BrandHeader(animated: false, size: .reduced) Text("Donut stuff!") } } } label: { Label("Food Truck", systemImage: "box.truck") } .menuBarExtraStyle(.window) #endif } } ``` ## CityView.swift ```swift /* Abstract: A view that shows details about a city. */ import SwiftUI import FoodTruckKit @preconcurrency import WeatherKit @preconcurrency import CoreLocation /// The view that displays weather information about a city. /// /// This view is presented by the ``DetailColumn`` view. struct CityView: View { var city: City @State private var spot: ParkingSpot = City.cupertino.parkingSpots[0] /// The current weather condition for the city. @State private var condition: WeatherCondition? /// Indicates whether it will rain soon. @State private var willRainSoon: Bool? @State private var cloudCover: Double? @State private var temperature: Measurement<UnitTemperature>? @State private var symbolName: String? @State private var attributionLink: URL? @State private var attributionLogo: URL? @Environment(\.colorScheme) var colorScheme: ColorScheme /// The body function. /// /// The body function implements a [`VStack` ](https://developer.apple.com/documentation/swiftui/vstack) to /// display various information about thee city and the parking spot. It presents the following views: /// - ``ParkingSpotShowcaseView`` /// - ``CityWeatherCard`` /// - ``RecommendedParkingSpotCard`` /// - A [`Group`](https://developer.apple.com/documentation/swiftui/group) showing relevant information /// about the parking spot in the city. var body: some View { ScrollView { VStack(spacing: 10) { ZStack { Text("Beautiful Map Goes Here") .hidden() .frame(height: 350) .frame(maxWidth: .infinity) } .background(alignment: .bottom) { ParkingSpotShowcaseView(spot: spot, topSafeAreaInset: 0) #if os(iOS) .mask { LinearGradient( stops: [ .init(color: .clear, location: 0), .init(color: .black.opacity(0.15), location: 0.1), .init(color: .black, location: 0.6), .init(color: .black, location: 1) ], startPoint: .top, endPoint: .bottom ) } .padding(.top, -150) #endif } .overlay(alignment: .bottomTrailing) { if let currentWeatherCondition = condition, let willRainSoon = willRainSoon, let symbolName = symbolName { CityWeatherCard( condition: currentWeatherCondition, willRainSoon: willRainSoon, symbolName: symbolName ) .padding(.bottom) } } VStack { RecommendedParkingSpotCard( parkingSpot: spot, condition: condition ?? .clear, temperature: temperature ?? Measurement(value: 72, unit: .fahrenheit), symbolName: symbolName ?? "sun.max" ) Group { Text("Cloud cover percentage is currently (String(format: "%.0f", (cloudCover ?? 0) * 100))% in (city.name)") Text("Popular donuts this season include Custard, Super Lemon, and Rainbow") Text("Recommendation to stock up on cold ingredients and popular toppings to be prepared for the season") } .frame(maxWidth: .infinity, alignment: .leading) .padding() .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 16, style: .continuous)) } .padding() VStack { AsyncImage(url: attributionLogo) { image in image .resizable() .scaledToFit() } placeholder: { ProgressView() .controlSize(.mini) } .frame(width: 20, height: 20) Link("Other data sources", destination: attributionLink ?? URL(string: "https://weather-data.apple.com/legal-attribution.html")!) } .font(.footnote) } .padding(.bottom) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background() .navigationTitle(city.name) .onChange(of: city) { newValue in spot = newValue.parkingSpots[0] } .onAppear { spot = city.parkingSpots[0] } .task(id: city.id) { for parkingSpot in city.parkingSpots { do { let weather = try await WeatherService.shared.weather(for: parkingSpot.location) condition = weather.currentWeather.condition willRainSoon = weather.minuteForecast?.contains(where: { $0.precipitationChance >= 0.3 }) cloudCover = weather.currentWeather.cloudCover temperature = weather.currentWeather.temperature symbolName = weather.currentWeather.symbolName let attribution = try await WeatherService.shared.attribution attributionLink = attribution.legalPageURL attributionLogo = colorScheme == .light ? attribution.combinedMarkLightURL : attribution.combinedMarkDarkURL if willRainSoon == false { spot = parkingSpot break } } catch { print("Could not gather weather information...", error.localizedDescription) condition = .clear willRainSoon = false cloudCover = 0.15 } } } } } struct CityView_Previews: PreviewProvider { static var previews: some View { CityView(city: .cupertino) } } ``` ## CityWeatherCard.swift ```swift /* Abstract: A card view to show the weather. */ import SwiftUI import WeatherKit struct CityWeatherCard: View { var condition: WeatherCondition var willRainSoon: Bool var symbolName: String var body: some View { HStack { Image(systemName: symbolName) .foregroundStyle(.secondary) .imageScale(.large) VStack(alignment: .leading) { Text(condition.description) .font(.headline) Text(willRainSoon ? "Will rain soon..." : "No chance of rain today") .foregroundStyle(.secondary) .font(.subheadline) } } .padding() .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) .frame(maxWidth: 400, alignment: .trailing) .padding() } } struct CityWeatherCard_Previews: PreviewProvider { static var previews: some View { CityWeatherCard(condition: .partlyCloudy, willRainSoon: true, symbolName: "sun.max") } } ``` ## DetailedMapView.swift ```swift /* Abstract: A map view configured for this app. */ import SwiftUI import MapKit #if os(iOS) private typealias ViewControllerRepresentable = UIViewControllerRepresentable #elseif os(macOS) private typealias ViewControllerRepresentable = NSViewControllerRepresentable #endif struct DetailedMapView: ViewControllerRepresentable { #if os(iOS) typealias ViewController = UIViewController #elseif os(macOS) typealias ViewController = NSViewController #endif var location: CLLocation var distance: Double = 1000 var pitch: Double = 0 var heading: Double = 0 var topSafeAreaInset: Double class Controller: ViewController { var mapView: MKMapView { guard let tempView = view as? MKMapView else { fatalError("View could not be cast as MapView.") } return tempView } override func loadView() { let mapView = MKMapView() view = mapView #if os(iOS) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] #elseif os(macOS) view.autoresizingMask = [.width, .height] #endif let configuration = MKStandardMapConfiguration(elevationStyle: .realistic, emphasisStyle: .default) configuration.pointOfInterestFilter = .excludingAll configuration.showsTraffic = false mapView.preferredConfiguration = configuration mapView.isZoomEnabled = false mapView.isPitchEnabled = false mapView.isScrollEnabled = false mapView.isRotateEnabled = false mapView.showsCompass = false } } #if os(iOS) func makeUIViewController(context: Context) -> Controller { Controller() } func updateUIViewController(_ controller: Controller, context: Context) { update(controller: controller) } #elseif os(macOS) func makeNSViewController(context: Context) -> Controller { Controller() } func updateNSViewController(_ controller: Controller, context: Context) { update(controller: controller) } #endif func update(controller: Controller) { #if os(iOS) controller.additionalSafeAreaInsets.top = topSafeAreaInset #endif controller.mapView.camera = MKMapCamera( lookingAtCenter: location.coordinate, fromDistance: distance, pitch: pitch, heading: heading ) } } struct DetailedMapView_Previews: PreviewProvider { static var previews: some View { DetailedMapView(location: CLLocation(latitude: 37.335_690, longitude: -122.013_330), topSafeAreaInset: 0) } } ``` ## ParkingSpotShowcaseView.swift ```swift /* Abstract: An animated map view. */ import SwiftUI import FoodTruckKit struct ParkingSpotShowcaseView: View { var spot: ParkingSpot var topSafeAreaInset: Double var animated = true var body: some View { GeometryReader { proxy in TimelineView(.animation(paused: !animated)) { context in let seconds = context.date.timeIntervalSince1970 let rotationPeriod = 240.0 let headingDelta = seconds.percent(truncation: rotationPeriod) let pitchPeriod = 60.0 let pitchDelta = seconds .percent(truncation: pitchPeriod) .symmetricEaseInOut() let viewWidthPercent = (350.0 ... 1000).percent(for: proxy.size.width) let distanceMultiplier = (1 - viewWidthPercent) * 0.5 + 1 DetailedMapView( location: spot.location, distance: distanceMultiplier * spot.cameraDistance, pitch: (50...60).value(percent: pitchDelta), heading: 360 * headingDelta, topSafeAreaInset: topSafeAreaInset ) } } } } struct ParkingSpotShowcaseView_Previews: PreviewProvider { static var previews: some View { ParkingSpotShowcaseView(spot: City.cupertino.parkingSpots[0], topSafeAreaInset: 0) } } ``` ## RecommendedParkingSpotCard.swift ```swift /* Abstract: A view showing the recommended parking spot. */ import SwiftUI import FoodTruckKit import WeatherKit struct RecommendedParkingSpotCard: View { var parkingSpot: ParkingSpot var condition: WeatherCondition var temperature: Measurement<UnitTemperature> var symbolName: String var body: some View { HStack { VStack(alignment: .leading) { Text("Recommended") .font(.subheadline.weight(.medium)) .foregroundStyle(.tertiary) Text(parkingSpot.name) Text("Parking Spot") .font(.caption) .foregroundStyle(.secondary) } .layoutPriority(1) Spacer() ViewThatFits { HStack { Label(temperature.formatted(), systemImage: symbolName) Label("Popular", systemImage: "person.3") Label("Trending", systemImage: "chart.line.uptrend.xyaxis") } HStack { Label(temperature.formatted(), systemImage: symbolName) Label("Popular", systemImage: "person.3") } Label(temperature.formatted(), systemImage: symbolName) } .labelStyle(RecommendedSpotSummaryLabelStyle()) } .padding() .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 20, style: .continuous)) } } struct RecommendedParkingSpotCard_Previews: PreviewProvider { static var previews: some View { RecommendedParkingSpotCard( parkingSpot: City.sanFrancisco.parkingSpots[0], condition: .clear, temperature: Measurement(value: 72, unit: .fahrenheit), symbolName: "sun.max" ) } } struct RecommendedSpotSummaryLabelStyle: LabelStyle { func makeBody(configuration: Configuration) -> some View { VStack { configuration.icon .font(.system(size: 18)) .imageScale(.large) .frame(width: 30, height: 30) .foregroundStyle(.secondary) configuration.title .foregroundStyle(.secondary) .font(.footnote) } } } ``` ## DonutEditor.swift ```swift /* Abstract: The donut editor view. */ import SwiftUI import FoodTruckKit struct DonutEditor: View { @Binding var donut: Donut var body: some View { ZStack { #if os(macOS) HSplitView { donutViewer .layoutPriority(1) Form { editorContent } .formStyle(.grouped) .padding() .frame(minWidth: 300, idealWidth: 350, maxHeight: .infinity, alignment: .top) } #else WidthThresholdReader { proxy in if proxy.isCompact { Form { donutViewer editorContent } } else { HStack(spacing: 0) { donutViewer Divider().ignoresSafeArea() Form { editorContent } .formStyle(.grouped) .frame(width: 350) } } } #endif } .toolbar { ToolbarTitleMenu { Button { } label: { Label("My Action", systemImage: "star") } } } .navigationTitle(donut.name) #if os(iOS) .navigationBarTitleDisplayMode(.inline) .toolbarRole(.editor) // We don't want store messages to interrupt any donut editing. .storeMessagesDeferred(true) #endif } var donutViewer: some View { DonutView(donut: donut) .frame(minWidth: 100, maxWidth: .infinity, minHeight: 100, maxHeight: .infinity) .listRowInsets(.init()) .padding(.horizontal, 40) .padding(.vertical) .background() } @ViewBuilder var editorContent: some View { Section("Donut") { TextField("Name", text: $donut.name, prompt: Text("Donut Name")) } Section("Flavor Profile") { Grid { let (topFlavor, topFlavorValue) = donut.flavors.mostPotent ForEach(Flavor.allCases) { flavor in let isTopFlavor = topFlavor == flavor let flavorValue = max(donut.flavors[flavor], 0) GridRow { flavor.image .foregroundStyle(isTopFlavor ? .primary : .secondary) Text(flavor.name) .gridCellAnchor(.leading) .foregroundStyle(isTopFlavor ? .primary : .secondary) Gauge(value: Double(flavorValue), in: 0...Double(topFlavorValue)) { EmptyView() } .tint(isTopFlavor ? Color.accentColor : Color.secondary) .labelsHidden() Text(flavorValue.formatted()) .gridCellAnchor(.trailing) .foregroundStyle(isTopFlavor ? .primary : .secondary) } } } } Section("Ingredients") { Picker("Dough", selection: $donut.dough) { ForEach(Donut.Dough.all) { dough in Text(dough.name) .tag(dough) } } Picker("Glaze", selection: $donut.glaze) { Section { Text("None") .tag(nil as Donut.Glaze?) } ForEach(Donut.Glaze.all) { glaze in Text(glaze.name) .tag(glaze as Donut.Glaze?) } } Picker("Topping", selection: $donut.topping) { Section { Text("None") .tag(nil as Donut.Topping?) } Section { ForEach(Donut.Topping.other) { topping in Text(topping.name) .tag(topping as Donut.Topping?) } } Section { ForEach(Donut.Topping.lattices) { topping in Text(topping.name) .tag(topping as Donut.Topping?) } } Section { ForEach(Donut.Topping.lines) { topping in Text(topping.name) .tag(topping as Donut.Topping?) } } Section { ForEach(Donut.Topping.drizzles) { topping in Text(topping.name) .tag(topping as Donut.Topping?) } } } } } } struct DonutEditor_Previews: PreviewProvider { struct Preview: View { @State private var donut = Donut.preview var body: some View { DonutEditor(donut: $donut) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## DonutGallery.swift ```swift /* Abstract: The donut gallery view. */ import SwiftUI import FoodTruckKit struct DonutGallery: View { @ObservedObject var model: FoodTruckModel @State private var layout = BrowserLayout.grid @State private var sort = DonutSortOrder.popularity(.week) @State private var popularityTimeframe = Timeframe.week @State private var sortFlavor = Flavor.sweet @State private var selection = Set<Donut.ID>() @State private var searchText = "" var filteredDonuts: [Donut] { model.donuts(sortedBy: sort).filter { $0.matches(searchText: searchText) } } var tableImageSize: Double { #if os(macOS) return 30 #else return 60 #endif } var body: some View { ZStack { if layout == .grid { grid } else { table } } .background() #if os(iOS) .toolbarRole(.browser) #endif .toolbar { ToolbarItemGroup { toolbarItems } } .onChange(of: popularityTimeframe) { newValue in if case .popularity = sort { sort = .popularity(newValue) } } .onChange(of: sortFlavor) { newValue in if case .flavor = sort { sort = .flavor(newValue) } } .searchable(text: $searchText) .navigationTitle("Donuts") .navigationDestination(for: Donut.ID.self) { donutID in DonutEditor(donut: model.donutBinding(id: donutID)) } .navigationDestination(for: String.self) { _ in DonutEditor(donut: $model.newDonut) } } var grid: some View { GeometryReader { geometryProxy in ScrollView { DonutGalleryGrid(donuts: filteredDonuts, width: geometryProxy.size.width) } } } var table: some View { Table(filteredDonuts, selection: $selection) { TableColumn("Name") { donut in NavigationLink(value: donut.id) { HStack { DonutView(donut: donut) .frame(width: tableImageSize, height: tableImageSize) Text(donut.name) } } } } } @ViewBuilder var toolbarItems: some View { NavigationLink(value: "New Donut") { Label("Create Donut", systemImage: "plus") } Menu { Picker("Layout", selection: $layout) { ForEach(BrowserLayout.allCases) { option in Label(option.title, systemImage: option.imageName) .tag(option) } } .pickerStyle(.inline) Picker("Sort", selection: $sort) { Label("Name", systemImage: "textformat") .tag(DonutSortOrder.name) Label("Popularity", systemImage: "trophy") .tag(DonutSortOrder.popularity(popularityTimeframe)) Label("Flavor", systemImage: "fork.knife") .tag(DonutSortOrder.flavor(sortFlavor)) } .pickerStyle(.inline) if case .popularity = sort { Picker("Timeframe", selection: $popularityTimeframe) { Text("Today") .tag(Timeframe.today) Text("Week") .tag(Timeframe.week) Text("Month") .tag(Timeframe.month) Text("Year") .tag(Timeframe.year) } .pickerStyle(.inline) } else if case .flavor = sort { Picker("Flavor", selection: $sortFlavor) { ForEach(Flavor.allCases) { flavor in Text(flavor.name) .tag(flavor) } } .pickerStyle(.inline) } } label: { Label("Layout Options", systemImage: layout.imageName) .labelStyle(.iconOnly) } } } enum BrowserLayout: String, Identifiable, CaseIterable { case grid case list var id: String { rawValue } var title: LocalizedStringKey { switch self { case .grid: return "Icons" case .list: return "List" } } var imageName: String { switch self { case .grid: return "square.grid.2x2" case .list: return "list.bullet" } } } struct DonutBakery_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel.preview var body: some View { DonutGallery(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## DonutGalleryGrid.swift ```swift /* Abstract: The grid view used in the DonutGallery. */ import SwiftUI import FoodTruckKit struct DonutGalleryGrid: View { var donuts: [Donut] var width: Double #if os(iOS) @Environment(\.horizontalSizeClass) private var sizeClass #endif @Environment(\.dynamicTypeSize) private var dynamicTypeSize var useReducedThumbnailSize: Bool { #if os(iOS) if sizeClass == .compact { return true } #endif if dynamicTypeSize >= .xxxLarge { return true } #if os(iOS) if width <= 390 { return true } #elseif os(macOS) if width <= 520 { return true } #endif return false } var cellSize: Double { useReducedThumbnailSize ? 100 : 150 } var thumbnailSize: Double { #if os(iOS) return useReducedThumbnailSize ? 60 : 100 #else return useReducedThumbnailSize ? 40 : 80 #endif } var gridItems: [GridItem] { [GridItem(.adaptive(minimum: cellSize), spacing: 20, alignment: .top)] } var body: some View { LazyVGrid(columns: gridItems, spacing: 20) { ForEach(donuts) { donut in NavigationLink(value: donut.id) { VStack { DonutView(donut: donut) .frame(width: thumbnailSize, height: thumbnailSize) VStack { let flavor = donut.flavors.mostPotentFlavor Text(donut.name) HStack(spacing: 4) { flavor.image Text(flavor.name) } .font(.subheadline) .foregroundStyle(.secondary) } .multilineTextAlignment(.center) } } .buttonStyle(.plain) } } .padding() } } struct DonutGalleryGrid_Previews: PreviewProvider { struct Preview: View { @State private var donuts = Donut.all var body: some View { GeometryReader { geometryProxy in ScrollView { DonutGalleryGrid(donuts: donuts, width: geometryProxy.size.width) } } } } static var previews: some View { Preview() } } ``` ## ShowTopDonutsIntent.swift ```swift /* Abstract: The "Show Top Donuts" intent. */ import FoodTruckKit import AppIntents import SwiftUI struct ShowTopDonutsIntent: AppIntent { static var title: LocalizedStringResource = "Show Top Donuts" @Parameter(title: "Timeframe") var timeframe: ShowTopDonutsIntentTimeframe @MainActor func perform() async throws -> some IntentResult & ShowsSnippetView { .result(view: ShowTopDonutsIntentView(timeframe: timeframe.asTimeframe)) } } enum ShowTopDonutsIntentTimeframe: String, CaseIterable, AppEnum { case today case week case month case year public static var typeDisplayRepresentation: TypeDisplayRepresentation = "Timeframe" public static var caseDisplayRepresentations: [ShowTopDonutsIntentTimeframe: DisplayRepresentation] = [ .today: "Today", .week: "This Week", .month: "This Month", .year: "This Year" ] var asTimeframe: Timeframe { switch self { case .today: return .today case .week: return .week case .month: return .month case .year: return .year } } } struct FoodTruckShortcuts: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { AppShortcut(intent: ShowTopDonutsIntent(), phrases: [ "(.applicationName) Trends for (\.$timeframe)" ]) } } extension ShowTopDonutsIntent { init(timeframe: Timeframe) { self.timeframe = timeframe.asIntentTimeframe } } extension Timeframe { var asIntentTimeframe: ShowTopDonutsIntentTimeframe { switch self { case .today: return .today case .week: return .week case .month: return .month case .year: return .year } } } ``` ## ShowTopDonutsIntentView.swift ```swift /* Abstract: The "Show Top Donuts Intent" view. */ import SwiftUI import FoodTruckKit struct ShowTopDonutsIntentView: View { var timeframe: Timeframe @StateObject private var model = FoodTruckModel() var body: some View { TopFiveDonutsChart(model: model, timeframe: timeframe) .padding() } } struct TopFiveDonutsIntentView_Previews: PreviewProvider { static var previews: some View { ShowTopDonutsIntentView(timeframe: .week) } } ``` ## TopDonutSalesChart.swift ```swift /* Abstract: The "Top Five Sales Chart" view. */ import SwiftUI import Charts import FoodTruckKit struct TopDonutSalesChart: View { var sales: [DonutSales] var sortedSales: [DonutSales] { sales.sorted() } var totalSales: Int { sales.map(\.sales).reduce(0, +) } var body: some View { VStack(alignment: .leading) { Text("Total Sales") .font(.subheadline) .foregroundColor(.secondary) Text("(totalSales.formatted()) Donuts") .font(.headline) chart } } var chart: some View { Chart { ForEach(sortedSales) { sale in BarMark( x: .value("Donut", sale.donut.name), y: .value("Sales", sale.sales) ) .cornerRadius(6, style: .continuous) .foregroundStyle(.linearGradient(colors: [Color("BarBottomColor"), .accentColor], startPoint: .bottom, endPoint: .top)) .annotation(position: .top, alignment: .top) { Text(sale.sales.formatted()) .padding(.vertical, 4) .padding(.horizontal, 8) .background(.quaternary.opacity(0.5), in: Capsule()) .background(in: Capsule()) .font(.caption) } } } .chartYAxis { AxisMarks { value in AxisGridLine() AxisTick() AxisValueLabel(format: IntegerFormatStyle<Int>()) } } .chartXAxis { AxisMarks { value in AxisValueLabel { let donut = donutFromAxisValue(for: value) VStack { DonutView(donut: donut) .frame(height: 35) Text(donut.name) .lineLimit(2, reservesSpace: true) .multilineTextAlignment(.center) } .frame(idealWidth: 80) .padding(.horizontal, 4) } } } .frame(height: 300) .padding(.top, 20) } func donutFromAxisValue(for value: AxisValue) -> Donut { guard let name = value.as(String.self) else { fatalError("Could not convert axis value to expected String type") } guard let result = sales.first(where: { $0.donut.name == name }) else { fatalError("No top performing DonutSales with given donut name: (name)") } return result.donut } } struct TopDonutSalesChart_Previews: PreviewProvider { static var previews: some View { TopDonutSalesChart(sales: Array(DonutSales.previewArray.prefix(5))) .padding() .previewLayout(.sizeThatFits) } } ``` ## TopFiveDonutsChart.swift ```swift /* Abstract: A container view for the "Top Five Chart" view. */ import SwiftUI import FoodTruckKit struct TopFiveDonutsChart: View { @ObservedObject var model: FoodTruckModel var timeframe: Timeframe var topSales: [DonutSales] { Array(model.donutSales(timeframe: timeframe).sorted().reversed().prefix(5)) } var body: some View { TopDonutSalesChart(sales: topSales) } } struct TopFiveDonutsChart_Previews: PreviewProvider { struct Preview: View { var timeframe: Timeframe @StateObject private var model = FoodTruckModel() var body: some View { TopFiveDonutsChart(model: model, timeframe: timeframe) } } static var previews: some View { Preview(timeframe: .today) .previewDisplayName("Today") Preview(timeframe: .week) .previewDisplayName("Week") Preview(timeframe: .month) .previewDisplayName("Month") Preview(timeframe: .year) .previewDisplayName("Year") } } ``` ## TopFiveDonutsView.swift ```swift /* Abstract: The "Top Five Donuts" view. */ import Charts import SwiftUI import FoodTruckKit import AppIntents struct TopFiveDonutsView: View { @ObservedObject var model: FoodTruckModel @State private var timeframe: Timeframe = .week let today = Calendar.current.startOfDay(for: .now) var body: some View { ScrollView { VStack(alignment: .leading) { Picker("Timeframe", selection: $timeframe) { Text("Day") .tag(Timeframe.today) Text("Week") .tag(Timeframe.week) Text("Month") .tag(Timeframe.month) Text("Year") .tag(Timeframe.year) } .pickerStyle(.segmented) .padding(.bottom, 10) TopFiveDonutsChart(model: model, timeframe: timeframe) #if os(iOS) SiriTipView(intent: ShowTopDonutsIntent(timeframe: timeframe)) .padding(.top, 20) #endif } .padding() } .navigationTitle("Top 5 Donuts") .background() } } struct TopFiveDonutsView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() var body: some View { TopFiveDonutsView(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## FlowLayout.swift ```swift /* Abstract: A flow layout for SwiftUI's layout. */ import SwiftUI struct FlowLayout: Layout { var alignment: Alignment = .center var spacing: CGFloat? func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize { let result = FlowResult( in: proposal.replacingUnspecifiedDimensions().width, subviews: subviews, alignment: alignment, spacing: spacing ) return result.bounds } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) { let result = FlowResult( in: proposal.replacingUnspecifiedDimensions().width, subviews: subviews, alignment: alignment, spacing: spacing ) for row in result.rows { let rowXOffset = (bounds.width - row.frame.width) * alignment.horizontal.percent for index in row.range { let xPos = rowXOffset + row.frame.minX + row.xOffsets[index - row.range.lowerBound] + bounds.minX let rowYAlignment = (row.frame.height - subviews[index].sizeThatFits(.unspecified).height) * alignment.vertical.percent let yPos = row.frame.minY + rowYAlignment + bounds.minY subviews[index].place(at: CGPoint(x: xPos, y: yPos), anchor: .topLeading, proposal: .unspecified) } } } struct FlowResult { var bounds = CGSize.zero var rows = [Row]() struct Row { var range: Range<Int> var xOffsets: [Double] var frame: CGRect } init(in maxPossibleWidth: Double, subviews: Subviews, alignment: Alignment, spacing: CGFloat?) { var itemsInRow = 0 var remainingWidth = maxPossibleWidth.isFinite ? maxPossibleWidth : .greatestFiniteMagnitude var rowMinY = 0.0 var rowHeight = 0.0 var xOffsets: [Double] = [] for (index, subview) in zip(subviews.indices, subviews) { let idealSize = subview.sizeThatFits(.unspecified) if index != 0 && widthInRow(index: index, idealWidth: idealSize.width) > remainingWidth { // Finish the current row without this subview. finalizeRow(index: max(index - 1, 0), idealSize: idealSize) } addToRow(index: index, idealSize: idealSize) if index == subviews.count - 1 { // Finish this row; it's either full or we're on the last view anyway. finalizeRow(index: index, idealSize: idealSize) } } func spacingBefore(index: Int) -> Double { guard itemsInRow > 0 else { return 0 } return spacing ?? subviews[index - 1].spacing.distance(to: subviews[index].spacing, along: .horizontal) } func widthInRow(index: Int, idealWidth: Double) -> Double { idealWidth + spacingBefore(index: index) } func addToRow(index: Int, idealSize: CGSize) { let width = widthInRow(index: index, idealWidth: idealSize.width) xOffsets.append(maxPossibleWidth - remainingWidth + spacingBefore(index: index)) // Allocate width to this item (and spacing). remainingWidth -= width // Ensure the row height is as tall as the tallest item. rowHeight = max(rowHeight, idealSize.height) // Can fit in this row, add it. itemsInRow += 1 } func finalizeRow(index: Int, idealSize: CGSize) { let rowWidth = maxPossibleWidth - remainingWidth rows.append( Row( range: index - max(itemsInRow - 1, 0) ..< index + 1, xOffsets: xOffsets, frame: CGRect(x: 0, y: rowMinY, width: rowWidth, height: rowHeight) ) ) bounds.width = max(bounds.width, rowWidth) let ySpacing = spacing ?? ViewSpacing().distance(to: ViewSpacing(), along: .vertical) bounds.height += rowHeight + (rows.count > 1 ? ySpacing : 0) rowMinY += rowHeight + ySpacing itemsInRow = 0 rowHeight = 0 xOffsets.removeAll() remainingWidth = maxPossibleWidth } } } } private extension HorizontalAlignment { var percent: Double { switch self { case .leading: return 0 case .trailing: return 1 default: return 0.5 } } } private extension VerticalAlignment { var percent: Double { switch self { case .top: return 0 case .bottom: return 1 default: return 0.5 } } } ``` ## WidthThresholdReader.swift ```swift /* Abstract: Reports whether the view is horizontally compact. */ import SwiftUI /** A view useful for determining if a child view should act like it is horizontally compressed. Several elements are used to decide if a view is compressed: - Width - Dynamic Type size - Horizontal size class (on iOS) */ struct WidthThresholdReader<Content: View>: View { var widthThreshold: Double = 400 var dynamicTypeThreshold: DynamicTypeSize = .xxLarge @ViewBuilder var content: (WidthThresholdProxy) -> Content #if os(iOS) @Environment(\.horizontalSizeClass) private var sizeClass #endif @Environment(\.dynamicTypeSize) private var dynamicType var body: some View { GeometryReader { geometryProxy in let compressionProxy = WidthThresholdProxy( width: geometryProxy.size.width, isCompact: isCompact(width: geometryProxy.size.width) ) content(compressionProxy) .frame(maxWidth: .infinity, maxHeight: .infinity) } } func isCompact(width: Double) -> Bool { #if os(iOS) if sizeClass == .compact { return true } #endif if dynamicType >= dynamicTypeThreshold { return true } if width < widthThreshold { return true } return false } } struct WidthThresholdProxy: Equatable { var width: Double var isCompact: Bool } struct WidthThresholdReader_Previews: PreviewProvider { static var previews: some View { VStack(spacing: 40) { WidthThresholdReader { proxy in Label { Text("Standard") } icon: { compactIndicator(proxy: proxy) } } .border(.quaternary) WidthThresholdReader { proxy in Label { Text("200 Wide") } icon: { compactIndicator(proxy: proxy) } } .frame(width: 200) .border(.quaternary) WidthThresholdReader { proxy in Label { Text("X Large Type") } icon: { compactIndicator(proxy: proxy) } } .dynamicTypeSize(.xxxLarge) .border(.quaternary) #if os(iOS) WidthThresholdReader { proxy in Label { Text("Manually Compact Size Class") } icon: { compactIndicator(proxy: proxy) } } .border(.quaternary) .environment(\.horizontalSizeClass, .regular) #endif } } @ViewBuilder static func compactIndicator(proxy: WidthThresholdProxy) -> some View { if proxy.isCompact { Image(systemName: "arrowtriangle.right.and.line.vertical.and.arrowtriangle.left.fill") .foregroundStyle(.red) } else { Image(systemName: "checkmark.circle") .foregroundStyle(.secondary) } } } ``` ## ContentView.swift ```swift /* Abstract: The app's root view. */ import SwiftUI import FoodTruckKit import os /// The root view in Food Truck. /// /// This view is the root view in ``FoodTruckApp``'s scene. /// On macOS, and iPadOS it presents a split navigation view, while on iOS devices it presents a navigation stack, as the main interface of the app. struct ContentView: View { /// The app's model that the containing scene passes in. @ObservedObject var model: FoodTruckModel /// The in-app store state that the containing scene passes in. @ObservedObject var accountStore: AccountStore @State private var selection: Panel? = Panel.truck @State private var path = NavigationPath() #if os(iOS) @Environment(\.displayStoreKitMessage) private var displayStoreMessage @Environment(\.scenePhase) private var scenePhase #endif /// The view body. /// /// This view embeds a [`NavigationSplitView`](https://developer.apple.com/documentation/swiftui/navigationsplitview), /// which displays the ``Sidebar`` view in the /// left column, and a [`NavigationStack`](https://developer.apple.com/documentation/swiftui/navigationstack) /// in the detail column, which consists of ``DetailColumn``, on macOS and iPadOS. /// On iOS the [`NavigationSplitView`](https://developer.apple.com/documentation/swiftui/navigationsplitview) /// display a navigation stack with the ``Sidebar`` view as the root. var body: some View { NavigationSplitView { Sidebar(selection: $selection) } detail: { NavigationStack(path: $path) { DetailColumn(selection: $selection, model: model) } } .onChange(of: selection) { _ in path.removeLast(path.count) } .environmentObject(accountStore) #if os(macOS) .frame(minWidth: 600, minHeight: 450) #elseif os(iOS) .onChange(of: scenePhase) { newValue in // If this view becomes active, tell the Messages manager to display // store messages in this window. if newValue == .active { StoreMessagesManager.shared.displayAction = displayStoreMessage } } .onPreferenceChange(StoreMessagesDeferredPreferenceKey.self) { newValue in StoreMessagesManager.shared.sensitiveViewIsPresented = newValue } .onOpenURL { url in let urlLogger = Logger(subsystem: "com.example.apple-samplecode.Food-Truck", category: "url") urlLogger.log("Received URL: (url, privacy: .public)") let order = "Order#(url.lastPathComponent)" var newPath = NavigationPath() selection = Panel.truck Task { newPath.append(Panel.orders) newPath.append(order) path = newPath } } #endif } } struct ContentView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() @StateObject private var accountStore = AccountStore() var body: some View { ContentView(model: model, accountStore: accountStore) } } static var previews: some View { Preview() } } ``` ## DetailColumn.swift ```swift /* Abstract: The detail column of the navigation interface. */ import SwiftUI import FoodTruckKit /// The detail view of the app's navigation interface. /// /// The ``ContentView`` presents this view in the detail column on macOS and iPadOS, and in the navigation stack on iOS. /// The superview passes the person's selection in the ``Sidebar`` as the ``selection`` binding. struct DetailColumn: View { /// The person's selection in the sidebar. /// /// This value is a binding, and the superview must pass in its value. @Binding var selection: Panel? /// The app's model the superview must pass in. @ObservedObject var model: FoodTruckModel @State var timeframe: Timeframe = .today /// The body function /// /// This view presents the appropriate view in response to the person's selection in the ``Sidebar``. See ``Panel`` /// for the views that `DetailColumn` presents. var body: some View { switch selection ?? .truck { case .truck: TruckView(model: model, navigationSelection: $selection) case .orders: OrdersView(model: model) case .socialFeed: SocialFeedView() #if EXTENDED_ALL case .account: AccountView(model: model) #endif case .salesHistory: SalesHistoryView(model: model) case .donuts: DonutGallery(model: model) case .donutEditor: DonutEditor(donut: $model.newDonut) case .topFive: TopFiveDonutsView(model: model) case .city(let id): CityView(city: City.identified(by: id)) } } } struct DetailColumn_Previews: PreviewProvider { struct Preview: View { @State private var selection: Panel? = .truck @StateObject private var model = FoodTruckModel.preview var body: some View { DetailColumn(selection: $selection, model: model) } } static var previews: some View { Preview() } } ``` ## Sidebar.swift ```swift /* Abstract: The sidebar and the root of the navigation interface. */ import SwiftUI import FoodTruckKit /// An enum that represents the person's selection in the app's sidebar. /// /// The `Panel` enum encodes the views the person can select in the sidebar, and hence appear in the detail view. enum Panel: Hashable { /// The value for the ``TruckView``. case truck /// The value for the ``SocialFeedView``. case socialFeed #if EXTENDED_ALL /// The value for the ``AccountView``. case account #endif /// The value for the ``OrdersView``. case orders /// The value for the ``SalesHistoryView``. case salesHistory /// The value for the ``DonutGallery``. case donuts /// The value for the ``DonutEditor``. case donutEditor /// The value for the ``TopFiveDonutsView``. case topFive /// The value for the ``CityView``. case city(City.ID) } /// The navigation sidebar view. /// /// The ``ContentView`` presents this view as the navigation sidebar view on macOS and iPadOS, and the root of the navigation stack on iOS. /// The superview passes the person's selection in the ``Sidebar`` as the ``selection`` binding. struct Sidebar: View { /// The person's selection in the sidebar. /// /// This value is a binding, and the superview must pass in its value. @Binding var selection: Panel? /// The view body. /// /// The `Sidebar` view presents a `List` view, with a `NavigationLink` for each possible selection. var body: some View { List(selection: $selection) { NavigationLink(value: Panel.truck) { Label("Truck", systemImage: "box.truck") } NavigationLink(value: Panel.orders) { Label("Orders", systemImage: "shippingbox") } NavigationLink(value: Panel.socialFeed) { Label("Social Feed", systemImage: "text.bubble") } #if EXTENDED_ALL NavigationLink(value: Panel.account) { Label("Account", systemImage: "person.crop.circle") } #endif NavigationLink(value: Panel.salesHistory) { Label("Sales History", systemImage: "clock") } Section("Donuts") { NavigationLink(value: Panel.donuts) { Label { Text("Donuts") } icon: { Image.donutSymbol } } NavigationLink(value: Panel.donutEditor) { Label("Donut Editor", systemImage: "slider.horizontal.3") } NavigationLink(value: Panel.topFive) { Label("Top 5", systemImage: "trophy") } } Section("Cities") { ForEach(City.all) { city in NavigationLink(value: Panel.city(city.id)) { Label(city.name, systemImage: "building.2") } .listItemTint(.secondary) } } } .navigationTitle("Food Truck") #if os(macOS) .navigationSplitViewColumnWidth(min: 200, ideal: 200) #endif } } struct Sidebar_Previews: PreviewProvider { struct Preview: View { @State private var selection: Panel? = Panel.truck var body: some View { Sidebar(selection: $selection) } } static var previews: some View { NavigationSplitView { Preview() } detail: { Text("Detail!") } } } ``` ## OrderCompleteView.swift ```swift /* Abstract: The order complete view. */ import SwiftUI import FoodTruckKit struct OrderCompleteView: View { @Environment(\.requestReview) private var requestReview @AppStorage("versionPromptedForReview") private var versionPromptedForReview: String? @AppStorage("datePromptedForReview") private var datePromptedForReview: TimeInterval? @State private var boxClosed = false @State private var boxBounce = false var order: Order @Environment(\.dismiss) private var dismiss var currentAppVersion: String? { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } var body: some View { NavigationStack { VStack { DonutBoxView(isOpen: boxClosed) { DonutView(donut: order.donuts.first!) } .offset(y: boxBounce ? 15 : 0) .aspectRatio(1, contentMode: .fit) .frame(maxWidth: 300) .onTapGesture { Task { @MainActor in await toggleBoxAnimation() } } Text("(order.id) completed!") .font(.headline) HStack(spacing: 4) { Text("(order.totalSales.formatted()) donuts") Text("�") Text(Date.now.formatted(date: .omitted, time: .shortened)) } .foregroundStyle(.secondary) } .padding() #if os(macOS) .frame(minWidth: 300, minHeight: 300) #endif .task { @MainActor in try? await Task.sleep(nanoseconds: .secondsToNanoseconds(0.75)) await toggleBoxAnimation() // Wait 1.5 seconds before displaying. try? await Task.sleep(nanoseconds: .secondsToNanoseconds(1.5)) if shouldRequestReview { requestReview() didRequestReview() } } .navigationTitle(order.id) .toolbar { ToolbarItemGroup(placement: .confirmationAction) { Button("Done") { dismiss() } } } } } func toggleBoxAnimation() async { // Animate the box closing with a slow spring without bounce. withAnimation(.spring(response: 0.35, dampingFraction: 1)) { boxClosed.toggle() } if boxClosed { try? await Task.sleep(nanoseconds: .secondsToNanoseconds(0.15)) // Move the box downward with a spring around the time it closes. withAnimation(.spring()) { boxBounce = true } try? await Task.sleep(nanoseconds: .secondsToNanoseconds(0.15)) // Move the box back with a spring to complete the look. withAnimation(.spring()) { boxBounce = false } } } var shouldRequestReview: Bool { guard let versionPromptedForReview = versionPromptedForReview, let datePromptedForReview = datePromptedForReview else { // If we've never asked the user to review, we'll prompt for a review. return true } guard let currentAppVersion = self.currentAppVersion else { return false } let dateLastAsked = Date(timeIntervalSince1970: datePromptedForReview) var dateComponent = DateComponents() dateComponent.month = 4 guard let fourMonthsLater = Calendar.current.date(byAdding: dateComponent, to: dateLastAsked) else { return false } return fourMonthsLater < .now && versionPromptedForReview != currentAppVersion } func didRequestReview() { versionPromptedForReview = self.currentAppVersion datePromptedForReview = Date().timeIntervalSince1970 } } struct OrderCompleteView_Previews: PreviewProvider { static var previews: some View { OrderCompleteView(order: .preview) } } ``` ## OrderDetailView.swift ```swift /* Abstract: The order detail view. */ import SwiftUI import FoodTruckKit #if canImport(ActivityKit) import ActivityKit #endif struct OrderDetailView: View { @Binding var order: Order @State private var presentingCompletionSheet = false var body: some View { List { Section("Status") { HStack { Text(order.status.title) Spacer() Image(systemName: order.status.iconSystemName) .foregroundColor(.secondary) } HStack { Text("Order Started") Spacer() Text(order.formattedDate) .foregroundColor(.secondary) } } Section("Donuts") { ForEach(order.donuts) { donut in Label { Text(donut.name) } icon: { DonutView(donut: donut) } .badge(order.sales[donut.id]!) } } Text("Total Donuts") .badge(order.totalSales) } .navigationTitle(order.id) .sheet(isPresented: $presentingCompletionSheet) { OrderCompleteView(order: order) } .onChange(of: order.status) { status in if status == .completed { presentingCompletionSheet = true } } .toolbar { ToolbarItemGroup { Button { order.markAsNextStep { status in if status == .preparing { #if canImport(ActivityKit) print("Start live activity.") prepareOrder() #endif } else if status == .completed { #if canImport(ActivityKit) print("Stop live activity.") endActivity() #endif } } } label: { Label(order.status.buttonTitle, systemImage: order.status.iconSystemName) .symbolVariant(order.isComplete ? .fill : .none) } .labelStyle(.iconOnly) .disabled(order.isComplete) } } } #if canImport(ActivityKit) func prepareOrder() { let timerSeconds = 60 let activityAttributes = TruckActivityAttributes( orderID: String(order.id.dropFirst(6)), order: order.donuts.map(\.id), sales: order.sales, activityName: "Order preparation activity." ) let future = Date(timeIntervalSinceNow: Double(timerSeconds)) let initialContentState = TruckActivityAttributes.ContentState(timerRange: Date.now...future) let activityContent = ActivityContent(state: initialContentState, staleDate: Calendar.current.date(byAdding: .minute, value: 2, to: Date())!) do { let myActivity = try Activity<TruckActivityAttributes>.request(attributes: activityAttributes, content: activityContent, pushType: nil) print(" Requested MyActivity live activity. ID: (myActivity.id)") postNotification() } catch let error { print("Error requesting live activity: (error.localizedDescription)") } } func endActivity() { Task { for activity in Activity<TruckActivityAttributes>.activities { // Check if this is the activity associated with this order. if activity.attributes.orderID == String(order.id.dropFirst(6)) { await activity.end(nil, dismissalPolicy: .immediate) } } } } #endif #if os(iOS) func postNotification() { let timerSeconds = 60 let content = UNMutableNotificationContent() content.title = "Donuts are done!" content.body = "Time to take them out of the oven." let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timerSeconds), repeats: false) let uuidString = UUID().uuidString let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger) let notificationCenter = UNUserNotificationCenter.current() notificationCenter.add(request) { (error) in if error != nil { // Handle any errors. print("Error posting local notification: (error?.localizedDescription ?? "no description")") } else { print("Posted local notification.") } } } #endif } struct OrderDetailView_Previews: PreviewProvider { struct Preview: View { @State private var order = Order.preview var body: some View { OrderDetailView(order: $order) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## OrderRow.swift ```swift /* Abstract: The order row view. */ import SwiftUI import FoodTruckKit struct OrderRow: View { var order: Order var body: some View { HStack { let iconShape = RoundedRectangle(cornerRadius: 4, style: .continuous) DonutStackView(donuts: order.donuts) .padding(2) #if os(iOS) .frame(width: 40, height: 40) #else .frame(width: 20, height: 20) #endif .background(in: iconShape) .overlay { iconShape.strokeBorder(.quaternary, lineWidth: 0.5) } Text(order.id) } } } struct OrderRow_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() var body: some View { OrderRow(order: .preview) } } static var previews: some View { Preview() } } ``` ## OrdersTable.swift ```swift /* Abstract: The orders table. */ import SwiftUI import FoodTruckKit struct OrdersTable: View { @ObservedObject var model: FoodTruckModel @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] @Binding var selection: Set<Order.ID> @Binding var completedOrder: Order? @Binding var searchText: String var orders: [Order] { model.orders.filter { order in order.matches(searchText: searchText) || order.donuts.contains(where: { $0.matches(searchText: searchText) }) } .sorted(using: sortOrder) } var body: some View { Table(selection: $selection, sortOrder: $sortOrder) { TableColumn("Order", value: \.id) { order in OrderRow(order: order) .frame(maxWidth: .infinity, alignment: .leading) .layoutPriority(1) } TableColumn("Donuts", value: \.totalSales) { order in Text(order.totalSales.formatted()) .monospacedDigit() #if os(macOS) .frame(maxWidth: .infinity, alignment: .trailing) .foregroundStyle(.secondary) #endif } TableColumn("Status", value: \.status) { order in order.status.label #if os(macOS) .foregroundStyle(.secondary) #endif } TableColumn("Date", value: \.creationDate) { order in Text(order.formattedDate) #if os(macOS) .foregroundStyle(.secondary) #endif } TableColumn("Details") { order in Menu { NavigationLink(value: order.id) { Label("View Details", systemImage: "list.bullet.below.rectangle") } if !order.isComplete { Section { Button { model.markOrderAsCompleted(id: order.id) completedOrder = order } label: { Label("Complete Order", systemImage: "checkmark") } } } } label: { Label("Details", systemImage: "ellipsis.circle") .labelStyle(.iconOnly) .contentShape(Rectangle()) } .menuStyle(.borderlessButton) .menuIndicator(.hidden) .fixedSize() .foregroundColor(.secondary) } .width(60) } rows: { Section { ForEach(orders) { order in TableRow(order) } } } } } struct OrdersTable_Previews: PreviewProvider { @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] struct Preview: View { @StateObject private var model = FoodTruckModel.preview var body: some View { OrdersTable( model: FoodTruckModel.preview, selection: .constant([]), completedOrder: .constant(nil), searchText: .constant("") ) } } static var previews: some View { Preview() } } //struct OrdersTable_Previews: PreviewProvider { // static var previews: some View { // OrdersTable() // } //} ``` ## OrdersView.swift ```swift /* Abstract: The orders view. */ import SwiftUI import FoodTruckKit struct OrdersView: View { @ObservedObject var model: FoodTruckModel @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] @State private var searchText = "" @State private var selection: Set<Order.ID> = [] @State private var completedOrder: Order? #if os(iOS) @Environment(\.horizontalSizeClass) private var sizeClass @Environment(\.editMode) private var editMode #endif var displayAsList: Bool { #if os(iOS) return sizeClass == .compact #else return false #endif } var orders: [Order] { model.orders.filter { order in order.matches(searchText: searchText) || order.donuts.contains(where: { $0.matches(searchText: searchText) }) } .sorted(using: sortOrder) } var orderSections: [OrderStatus: [Order]] { var result: [OrderStatus: [Order]] = [:] orders.forEach { order in result[order.status, default: []].append(order) } return result } var body: some View { ZStack { if displayAsList { list } else { OrdersTable(model: model, selection: $selection, completedOrder: $completedOrder, searchText: $searchText) .tableStyle(.inset) } } .navigationTitle("Orders") .navigationDestination(for: Order.ID.self) { id in OrderDetailView(order: model.orderBinding(for: id)) } .toolbar { if !displayAsList { toolbarButtons } } .searchable(text: $searchText) .sheet(item: $completedOrder) { order in OrderCompleteView(order: order) } } var list: some View { List { if let orders = orderSections[.placed] { Section("New") { orderRows(orders) } } if let orders = orderSections[.preparing] { Section("Preparing") { orderRows(orders) } } if let orders = orderSections[.ready] { Section("Ready") { orderRows(orders) } } if let orders = orderSections[.completed] { Section("Completed") { orderRows(orders) } } } .headerProminence(.increased) } func orderRows(_ orders: [Order]) -> some View { ForEach(orders) { order in NavigationLink(value: order.id) { OrderRow(order: order) .badge(order.totalSales) } } } @ViewBuilder var toolbarButtons: some View { NavigationLink(value: selection.first) { Label("View Details", systemImage: "list.bullet.below.rectangle") } .disabled(selection.isEmpty) Button { for orderID in selection { model.markOrderAsCompleted(id: orderID) } if let orderID = selection.first { completedOrder = model.orderBinding(for: orderID).wrappedValue } } label: { Label("View Details", systemImage: "checkmark.circle") } .disabled(selection.isEmpty) #if os(iOS) if editMode?.wrappedValue.isEditing == false { Button("Select") { editMode?.wrappedValue = .active } } else { EditButton() } #endif } } struct OrdersView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel.preview var body: some View { OrdersView(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## RefundView.swift ```swift /* Abstract: The in-app purchase refund view. */ import SwiftUI import StoreKit import FoodTruckKit import Foundation struct RefundView: View { @State private var recentTransactions: [StoreKit.Transaction] = [] @State private var selectedTransactionID: UInt64? @State private var refundSheetIsPresented = false @Environment(\.dismiss) private var dismiss var body: some View { List(recentTransactions, selection: $selectedTransactionID) { transaction in TransactionRowView(transaction: transaction) } .safeAreaInset(edge: .bottom) { VStack(spacing: 0) { Text("Select a purchase to refund") .font(.subheadline) .foregroundColor(.secondary) .padding() Button { refundSheetIsPresented = true } label: { Text("Request a refund") .bold() .padding(.vertical, 5) .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) .padding([.horizontal, .bottom]) .disabled(selectedTransactionID == nil) } } .task { @MainActor in for await transaction in StoreKit.Transaction.all { // Ignore the already refunded transactions. if transaction.unsafePayloadValue.isRevoked { continue } recentTransactions.append(transaction.unsafePayloadValue) if recentTransactions.count >= 10 { break } } } .refundRequestSheet( for: selectedTransactionID ?? 0, isPresented: $refundSheetIsPresented ) { result in if case .success(.success) = result { dismiss() } } .navigationTitle("Refund purchases") } } struct TransactionRowView: View { let transaction: StoreKit.Transaction @State private var product: Product? var title: String { product?.displayName ?? transaction.productID } var subtitle: String { let purchaseDate = transaction.purchaseDate .formatted(date: .long, time: .omitted) if transaction.productType == .autoRenewable { return String(localized: "Subscribed (purchaseDate)") } else { return String(localized: "Purchased (purchaseDate)") } } var body: some View { VStack(alignment: .leading) { Text(title) .font(.headline) .bold() Text(subtitle) .font(.subheadline) .foregroundColor(.secondary) } .task { @MainActor in product = await StoreActor.shared .product(identifiedBy: transaction.productID) } } } struct RefundView_Previews: PreviewProvider { static var previews: some View { NavigationStack { RefundView() } } } ``` ## SocialFeedPlusSettings.swift ```swift /* Abstract: The social feed settings view. */ import SwiftUI import StoreKit import FoodTruckKit struct SocialFeedPlusSettings: View { @ObservedObject var controller: StoreSubscriptionController @AppStorage("showPlusPosts") private var showPlusPosts = false @AppStorage("advancedTools") private var advancedTools = true @Environment(\.dismiss) private var dismiss var body: some View { List { SubscriptionStatusView(controller: controller) Section("Settings") { Toggle("Highlight Social Feed+ posts", isOn: $showPlusPosts) Toggle("Advanced engagement tools", isOn: $advancedTools) NavigationLink("Social-media providers") { EmptyView() } } #if os(iOS) Section { NavigationLink { StoreSupportView() } label: { Label("Subscription support", systemImage: "questionmark.circle") } } #else Section("Subscription support") { Button("Restore missing purchases") { Task(priority: .userInitiated) { try await AppStore.sync() } } } #endif } .navigationTitle("Manage Social Feed+") .toolbar { #if os(iOS) let placement = ToolbarItemPlacement.navigationBarTrailing #else let placement = ToolbarItemPlacement.cancellationAction #endif ToolbarItemGroup(placement: placement) { Button { dismiss() } label: { Label("Dismiss", systemImage: "xmark") #if os(macOS) .labelStyle(.titleOnly) #endif } } } .onAppear { // The user might lose their entitlement while this view is in the // navigation stack. In this case you need to dismiss the view. if controller.entitledSubscription == nil { dismiss() } } } } struct SubscriptionStatusView: View { @ObservedObject var controller: StoreSubscriptionController #if os(iOS) @State private var manageSubscriptionIsPresented = false #else @Environment(\.openURL) private var openURL #endif var currentSubscriptionName: String { controller.entitledSubscription?.displayName ?? String(localized: "None") } var newNextSubscriptionName: String? { if controller.entitledSubscriptionID != controller.autoRenewPreference { return controller.nextSubscription?.displayName } return nil } var renewalText: String { let expiration = controller.expirationDate?.formatted( date: .abbreviated, time: .omitted ) ?? String(localized: "None") guard let nextSubscription = controller.nextSubscription else { return String(localized: "Expires on (expiration)") } let prefix: String if let newNextSubscriptionName = newNextSubscriptionName { prefix = String(localized: "Renews to (newNextSubscriptionName)") } else { prefix = String(localized: "Renews") } let price = nextSubscription.displayPrice return String(localized: "(prefix) for (price) on (expiration)") } var body: some View { Section("Your subscription") { VStack(alignment: .leading) { Text(currentSubscriptionName) .font(.headline) .bold() Text(renewalText) .font(.subheadline) .foregroundColor(.secondary) } Button("Manage subscription") { #if os(iOS) manageSubscriptionIsPresented = true #else if let url = URL(string: "https://apps.apple.com/account/subscriptions") { openURL(url) } #endif } #if os(iOS) .manageSubscriptionsSheet(isPresented: $manageSubscriptionIsPresented) #endif } } } struct SocialFeedPlusSettings_Previews: PreviewProvider { static var previews: some View { NavigationStack { SocialFeedPlusSettings( controller: StoreActor.shared.subscriptionController ) } } } ``` ## StoreSupportView.swift ```swift /* Abstract: The in-app purchase support view. */ import SwiftUI import StoreKit import FoodTruckKit struct StoreSupportView: View { #if os(iOS) @State private var manageSubscriptionSheetIsPresented = false #endif @Environment(\.dismiss) private var dismiss var body: some View { List { #if os(iOS) Button("Manage subscription") { manageSubscriptionSheetIsPresented = true } .manageSubscriptionsSheet(isPresented: $manageSubscriptionSheetIsPresented) NavigationLink("Refund purchases") { RefundView() } .foregroundColor(.accentColor) #endif Button("Restore missing purchases") { Task(priority: .userInitiated) { try await AppStore.sync() } } } .navigationTitle("Help with purchases") } } struct StoreSupportView_Previews: PreviewProvider { static var previews: some View { NavigationStack { StoreSupportView() } } } ``` ## SubscriptionStoreView.swift ```swift /* Abstract: The in-app purchase subscription view. */ import SwiftUI import StoreKit import FoodTruckKit struct SubscriptionStoreView: View { @ObservedObject var controller: StoreSubscriptionController @State private var selectedSubscription: Subscription? @State private var errorAlertIsPresented = false @Environment(\.dismiss) private var dismiss var body: some View { Group { #if os(macOS) VStack(spacing: 0) { SubscriptionStoreHeaderView() .frame(maxWidth: .infinity) .background(.indigo.gradient) subscriptionCellsView } .safeAreaInset(edge: .bottom) { subscriptionPurchaseView } .overlay(alignment: .topTrailing) { dismissButton .padding() } #else GeometryReader { proxy in if proxy.size.height > proxy.size.width { VStack(spacing: 0) { SubscriptionStoreHeaderView() .frame(maxWidth: .infinity) .background(.indigo.gradient) subscriptionCellsView } .safeAreaInset(edge: .bottom) { subscriptionPurchaseView } .overlay(alignment: .topTrailing) { dismissButton .padding() } } else { HStack(spacing: 0) { SubscriptionStoreHeaderView() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.indigo.gradient) Divider().ignoresSafeArea() VStack { subscriptionCellsView .padding(.top, 30) .frame(width: 400) .ignoresSafeArea() subscriptionPurchaseView .padding(.horizontal, 30) } } .ignoresSafeArea() .overlay(alignment: .topTrailing) { dismissButton .padding(.top, 8) } } } #endif } #if os(iOS) .background(Color(uiColor: .systemGray6)) #endif .onAppear { selectedSubscription = controller.subscriptions.first } .alert( controller.purchaseError?.errorDescription ?? "", isPresented: $errorAlertIsPresented, actions: {} ) } var dismissButton: some View { Button { dismiss() } label: { Image(systemName: "xmark.circle.fill") .symbolRenderingMode(.palette) #if os(iOS) .foregroundStyle( .secondary, .clear, Color(uiColor: .systemGray5) ) #elseif os(macOS) .foregroundStyle( .secondary, .clear, Color(nsColor: .lightGray) ) #endif } .buttonStyle(.borderless) .opacity(0.8) .font(.title) } var subscriptionPurchaseView: some View { SubscriptionPurchaseView(selectedSubscription: selectedSubscription) { if let subscription = selectedSubscription { Task(priority: .userInitiated) { @MainActor in let action = await controller.purchase(option: subscription) switch action { case .dismissStore: dismiss() case .displayError: errorAlertIsPresented = true case .noAction: break } } } } .backgroundStyle(.ultraThinMaterial) } var subscriptionCellsView: some View { ScrollView(.vertical) { SubscriptionStoreOptionsView( subscriptions: controller.subscriptions, selectedOption: $selectedSubscription ) .padding(.top) } } } struct SubscriptionStoreHeaderView: View { var body: some View { VStack { Text("Social Feed+") .font(.largeTitle) .bold() .padding() Group { Text("Top social-media providers.") Text("Advanced engagement tools.") Text("All in one place.") } .font(.headline) } .padding(.top, 5) .padding(.bottom, 30) .foregroundColor(.white) } } struct SubscriptionStoreOptionsView: View { let subscriptions: [Subscription] @Binding var selectedOption: Subscription? func binding(for subscription: Subscription) -> Binding<Bool> { Binding { selectedOption?.id == subscription.id } set: { newValue in selectedOption = newValue ? subscription : nil } } var body: some View { VStack { ForEach(subscriptions) { subscription in subscriptionOptionCell(for: subscription) } } } func subscriptionOptionCell(for subscription: Subscription) -> some View { var savingsInfo: SubscriptionSavings? if subscription.id == StoreActor.socialFeedYearlyID { savingsInfo = self.savings() } return SubscriptionOptionView( subscription: subscription, savings: savingsInfo, isOn: binding(for: subscription) ) } func savings() -> SubscriptionSavings? { guard let yearlySubscription = subscriptions.first(where: { $0.id == StoreActor.socialFeedYearlyID }) else { return nil } guard let monthlySubscription = subscriptions.first(where: { $0.id == StoreActor.socialFeedMonthlyID }) else { return nil } let yearlyPriceForMonthlySubscription = 12 * monthlySubscription.price let amountSaved = yearlyPriceForMonthlySubscription - yearlySubscription.price guard amountSaved > 0 else { return nil } let percentSaved = amountSaved / yearlyPriceForMonthlySubscription let monthlyPrice = yearlySubscription.price / 12 return SubscriptionSavings(percentSavings: percentSaved, granularPrice: monthlyPrice, granularPricePeriod: .month) } } struct SubscriptionOptionView: View { let subscription: Subscription let savings: SubscriptionSavings? @Binding var isOn: Bool @Environment(\.colorScheme) private var colorScheme private var savingsText: String? { savings.map { "($0.formattedPrice(for: subscription)) (Save ($0.formattedPercent))" } } private static var backgroundColor: Color { #if canImport(UIKit) Color(uiColor: .tertiarySystemBackground) #elseif canImport(AppKit) Color(nsColor: .windowBackgroundColor) #endif } private static var backgroundShape: some InsettableShape { RoundedRectangle(cornerRadius: 16, style: .continuous) } var body: some View { HStack(alignment: .firstTextBaseline) { VStack(alignment: .leading) { Text(subscription.displayName) .font(.headline) Text(subscription.description) .padding(.bottom, 2) Text(applyKerning(to: "/", in: subscription.priceText)) if let savingsText = savingsText { Text(applyKerning(to: "/()", in: savingsText)) .foregroundColor(.accentColor) } } Spacer() checkmarkImage } .padding() .frame(maxWidth: .infinity) .background(Self.backgroundColor, in: Self.backgroundShape) .overlay { Self.backgroundShape #if os(iOS) .strokeBorder( Color.accentColor, lineWidth: isOn ? 1 : 0 ) #elseif os(macOS) .strokeBorder( isOn ? Color.accentColor : .gray.opacity(0.1), lineWidth: 1 ) #endif } .onTapGesture { isOn.toggle() } .background( .shadow(.drop( color: .black.opacity(colorScheme == .dark ? 0.5 : 0.2), radius: 10 )), in: Self.backgroundShape.scale(0.99) ) .padding(.horizontal) .padding(.vertical, 5) } private var checkmarkImage: some View { Image(systemName: isOn ? "checkmark.circle.fill" : "circle") .symbolRenderingMode(.palette) .foregroundStyle( isOn ? Color.white : Color.secondary, Color.clear, Color.accentColor ) .font(.title2) } private func applyKerning(to symbols: String, in text: String, kerningValue: CGFloat = 1.0) -> AttributedString { var attributedString = AttributedString(text) let characters = symbols.map(String.init) for character in characters { if let range = attributedString.range(of: character) { attributedString[range].kern = kerningValue } } return attributedString } } struct SubscriptionPurchaseView: View { @State private var canRedeemIntroOffer = false #if os(iOS) @State private var redeemSheetIsPresented = false #endif @Environment(\.dismiss) private var dismiss let selectedSubscription: Subscription? let onPurchase: () -> Void var body: some View { VStack { Button { onPurchase() } label: { Group { if canRedeemIntroOffer { Text("Start trial offer") } else { Text("Subscribe") } } .bold() .padding(5) #if os(iOS) .frame(maxWidth: .infinity) #endif } .buttonStyle(.borderedProminent) .disabled(selectedSubscription == nil) .padding(.horizontal) #if os(macOS) .tint(.accentColor) .controlSize(.large) #endif #if os(iOS) Button("Redeem an offer") { redeemSheetIsPresented = true } .buttonStyle(.borderless) .padding(.top) #endif } .frame(maxWidth: .infinity) .padding(.vertical) #if os(iOS) .offerCodeRedemption(isPresented: $redeemSheetIsPresented) { _ in dismiss() } #endif .onChange(of: selectedSubscription) { newValue in guard let selectedSubscription = newValue?.subscriptionInfo else { return } Task(priority: .utility) { @MainActor in canRedeemIntroOffer = await selectedSubscription.isEligibleForIntroOffer } } } } struct SubscriptionStoreView_Previews: PreviewProvider { static var previews: some View { SubscriptionStoreView( controller: StoreActor.shared.subscriptionController ) } } ``` ## UnlockFeatureView.swift ```swift /* Abstract: The unlock feature view. */ import SwiftUI import StoreKit import FoodTruckKit struct UnlockFeatureView: View { @ObservedObject var controller: StoreProductController @State private var isExpanded = true @Environment(\.colorScheme) private var colorScheme private static var backgroundColor: Color { #if canImport(UIKit) Color(uiColor: .systemBackground) #elseif canImport(AppKit) Color(nsColor: .windowBackgroundColor) #endif } private static var backgroundShape: some InsettableShape { RoundedRectangle(cornerRadius: 15, style: .continuous) } var body: some View { if let product = controller.product, !controller.isEntitled { Group { if isExpanded { UnlockFeatureExpandedView(product: product) { Task(priority: .userInitiated) { await controller.purchase() } } onDismiss: { isExpanded = false } } else { UnlockFeatureSimpleView(product: product) { isExpanded = true Task(priority: .userInitiated) { await controller.purchase() } } .onTapGesture { isExpanded = true } } } .frame(maxWidth: 400) .background( UnlockFeatureView.backgroundColor, in: UnlockFeatureView.backgroundShape ) .background( .shadow(.drop( color: .black.opacity(colorScheme == .dark ? 0.5 : 0.2), radius: 10 )), in: UnlockFeatureView.backgroundShape.scale(0.99) ) .padding() } } } struct UnlockFeatureExpandedView: View { let product: Product let onPurchase: () -> Void let onDismiss: () -> Void var body: some View { VStack(spacing: 15) { Text(""" Unlock a (product.displayName.localizedLowercase) \ for only (product.displayPrice) """) .fontWeight(.semibold) .foregroundColor(.accentColor) Text("Get the full picture with data and insights that cover an entire year.") .font(.subheadline) Button(action: onPurchase) { Text("Unlock") .padding(.vertical, 2) .padding(.horizontal, 10) } .buttonStyle(.borderedProminent) #if os(iOS) .buttonBorderShape(.capsule) #endif } .multilineTextAlignment(.center) .padding() .padding(.top, 30) .padding(.bottom) .overlay(alignment: .topTrailing) { Button(action: onDismiss) { Label("Dismiss", systemImage: "xmark") .labelStyle(.iconOnly) } .controlSize(.mini) .foregroundColor(.secondary) .padding(.top) .padding(.trailing, 10) } } } struct UnlockFeatureSimpleView: View { let product: Product let onPurchase: () -> Void var body: some View { HStack { VStack(alignment: .leading, spacing: 3) { Text("Unlock a (product.displayName.localizedLowercase)") .font(.subheadline.weight(.semibold)) Text("for only (product.displayPrice)") .font(.footnote) .foregroundColor(.secondary) } Spacer() Button(action: onPurchase) { Text("Unlock") .font(.subheadline) .padding(2) } .buttonStyle(.borderedProminent) #if os(iOS) .buttonBorderShape(.capsule) #endif } .padding() } } struct UnlockFeatureView_Previews: PreviewProvider { static var previews: some View { VStack { Spacer() UnlockFeatureView( controller: StoreActor.shared.productController ) } } } ``` ## CardNavigationHeader.swift ```swift /* Abstract: The header view for the cards in the Truck view. */ import SwiftUI struct CardNavigationHeader<Label: View>: View { var panel: Panel var navigation: TruckCardHeaderNavigation @ViewBuilder var label: Label var body: some View { HStack { switch navigation { case .navigationLink: NavigationLink(value: panel) { label } case .selection(let selection): Button { selection.wrappedValue = panel } label: { label } } Spacer() } .buttonStyle(.borderless) .labelStyle(.cardNavigationHeader) } } struct CardNavigationHeader_Previews: PreviewProvider { static var previews: some View { NavigationStack { CardNavigationHeader(panel: .orders, navigation: .navigationLink) { Label("Orders", systemImage: "shippingbox") } .padding() } } } ``` ## CardNavigationHeaderLabelStyle.swift ```swift /* Abstract: The header view label style for the cards in the Truck view. */ import SwiftUI struct CardNavigationHeaderLabelStyle: LabelStyle { func makeBody(configuration: Configuration) -> some View { HStack(alignment: .firstTextBaseline, spacing: 4) { configuration.icon .foregroundStyle(.secondary) configuration.title Image(systemName: "chevron.forward") .foregroundStyle(.tertiary) .fontWeight(.semibold) .imageScale(.small) .padding(.leading, 2) } .font(.headline) .imageScale(.large) .foregroundColor(.accentColor) } } extension LabelStyle where Self == CardNavigationHeaderLabelStyle { static var cardNavigationHeader: CardNavigationHeaderLabelStyle { CardNavigationHeaderLabelStyle() } } struct CardNavigationHeaderLabelStyle_Previews: PreviewProvider { static var previews: some View { VStack { Label("Title 1", systemImage: "star") Label("Title 2", systemImage: "square") Label("Title 3", systemImage: "circle") } .labelStyle(.cardNavigationHeader) } } ``` ## TruckDonutsCard.swift ```swift /* Abstract: The donuts card showing in the Truck view. */ import SwiftUI import FoodTruckKit struct TruckDonutsCard: View { var donuts: [Donut] var navigation: TruckCardHeaderNavigation = .navigationLink var body: some View { VStack { CardNavigationHeader(panel: .donuts, navigation: navigation) { Label { Text("Donuts") } icon: { Image.donutSymbol } } (DonutLatticeLayout()) { ForEach(donuts.prefix(14)) { donut in DonutView(donut: donut) } } .frame(minHeight: 180, maxHeight: .infinity) } .padding(10) .background() } struct DonutLatticeLayout: Layout { var columns: Int var rows: Int var spacing: Double init() { self.init(columns: 5, rows: 3, spacing: 10) } init(columns: Int, rows: Int, spacing: Double) { self.columns = columns self.rows = rows self.spacing = spacing } var defaultAxesSize: CGSize { CGSize( width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude ) } func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize { let size = proposal.replacingUnspecifiedDimensions(by: defaultAxesSize) let cellLength = min(size.width / Double(columns), size.height / Double(rows)) return CGSize( width: cellLength * Double(columns), height: cellLength * Double(rows) ) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) { let size = proposal.replacingUnspecifiedDimensions(by: defaultAxesSize) let cellLength = min(size.width / Double(columns), size.height / Double(rows)) let rectSize = CGSize(width: cellLength * Double(columns), height: cellLength * Double(rows)) let origin = CGPoint( x: bounds.minX + (bounds.width - rectSize.width), y: bounds.minY + (bounds.height - rectSize.height) ) for row in 0..<rows { let cellY = origin.y + (cellLength * Double(row)) let columnsForRow = row.isMultiple(of: 2) ? columns : columns - 1 for column in 0..<columnsForRow { var cellX = origin.x + (cellLength * Double(column)) if !row.isMultiple(of: 2) { cellX += cellLength * 0.5 } let index: Int = { var result = 0 if row > 0 { for completedRow in 0..<row { if completedRow.isMultiple(of: 2) { result += columns } else { // We have one less column in odd rows result += columns - 1 } } } return result + column }() guard index < subviews.count else { break } let cellRect = CGRect(x: cellX, y: cellY, width: cellLength, height: cellLength) .insetBy(dx: spacing * 0.5, dy: spacing * 0.5) subviews[index].place(at: cellRect.origin, proposal: ProposedViewSize(cellRect.size)) } } } } } struct TruckDonutsCard_Previews: PreviewProvider { static var previews: some View { TruckDonutsCard(donuts: Donut.all) } } ``` ## TruckOrdersCard.swift ```swift /* Abstract: The orders card showing in the Truck view. */ import SwiftUI import FoodTruckKit struct TruckOrdersCard: View { @ObservedObject var model: FoodTruckModel var orders: [Order] { model.orders } var navigation: TruckCardHeaderNavigation = .navigationLink @State private var pulseOrderText = false var body: some View { VStack(alignment: .leading) { CardNavigationHeader(panel: .orders, navigation: navigation) { Label("New Orders", systemImage: "shippingbox") } (HeroSquareTilingLayout()) { ForEach(orders.reversed().prefix(5)) { order in let iconShape = RoundedRectangle(cornerRadius: 10, style: .continuous) DonutStackView(donuts: order.donuts) .padding(6) #if canImport(UIKit) .background(Color(uiColor: .tertiarySystemFill), in: iconShape) #else .background(.quaternary.opacity(0.5), in: iconShape) #endif .overlay { iconShape.strokeBorder(.quaternary, lineWidth: 0.5) } .transition( .asymmetric( insertion: .offset(x: -100).combined(with: .opacity), removal: .scale.combined(with: .opacity) ) ) } .aspectRatio(1, contentMode: .fit) } .aspectRatio(2, contentMode: .fit) .frame(maxWidth: .infinity, maxHeight: 250) if let order = orders.last { HStack { Text(order.id) Image.donutSymbol Text(order.totalSales.formatted()) } .frame(maxWidth: .infinity) .foregroundStyle(pulseOrderText ? .primary : .secondary) .fontWeight(pulseOrderText ? .bold : .regular) .contentTransition(.interpolate) } } .padding(10) .clipShape(ContainerRelativeShape()) .background() .onChange(of: orders.last) { newValue in Task(priority: .background) { try await Task.sleep(nanoseconds: .secondsToNanoseconds(0.1)) Task { @MainActor in withAnimation(.spring(response: 0.25, dampingFraction: 1)) { pulseOrderText = true } } try await Task.sleep(nanoseconds: .secondsToNanoseconds(1)) Task { @MainActor in withAnimation(.spring(response: 0.25, dampingFraction: 1)) { pulseOrderText = false } } } } } } struct HeroSquareTilingLayout: Layout { var spacing: Double init() { self.spacing = 10 } init(spacing: Double = 10) { self.spacing = spacing } func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize { let size = proposal.replacingUnspecifiedDimensions(by: CGSize(width: 100, height: 100)) let heroLength = min((size.width - spacing) * 0.5, size.height) let boundsWidth = heroLength * 2 + spacing return CGSize(width: boundsWidth, height: heroLength) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) { let heroLength = min((bounds.width - spacing) * 0.5, bounds.height) let boundsWidth = heroLength * 2 + spacing let halfRectSize = CGSize(width: heroLength, height: heroLength) let heroOrigin = CGPoint( x: bounds.origin.x + ((bounds.width - boundsWidth) * 0.5), y: bounds.origin.y + ((bounds.height - heroLength) * 0.5) ) let tileLength = (heroLength - 10) * 0.5 let tilesOrigin = CGPoint(x: heroOrigin.x + heroLength + spacing, y: heroOrigin.y) let tilesRect = CGRect(origin: tilesOrigin, size: halfRectSize) for index in subviews.indices { if index == 0 { // hero cell subviews[index].place( at: heroOrigin, anchor: .topLeading, proposal: ProposedViewSize(halfRectSize) ) } else { // smaller tile let tileIndex = index - 1 let xPos: Double = tileIndex % 2 == 0 ? 0 : 1 let yPos: Double = tileIndex < 2 ? 0 : 1 let point = CGPoint( x: tilesRect.minX + (xPos * tilesRect.width), y: tilesRect.minY + (yPos * tilesRect.height) ) subviews[index].place( at: point, anchor: UnitPoint(x: xPos, y: yPos), proposal: ProposedViewSize(width: tileLength, height: tileLength) ) } } } } struct TruckOrdersCard_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() var body: some View { TruckOrdersCard(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## TruckSocialFeedCard.swift ```swift /* Abstract: The social feed card showing in the Truck view. */ import SwiftUI import FoodTruckKit struct TruckSocialFeedCard: View { var navigation: TruckCardHeaderNavigation = .navigationLink private let tags: [SocialFeedTag] = [ .donut(.powderedChocolate), .donut(.blueberryFrosted), .title("Warmed Up"), .title("Room Temperature"), .city(.sanFrancisco), .donut(.rainbow), .title("Rainbow Sprinkles"), .donut(.strawberrySprinkles), .title("Dairy Free"), .city(.cupertino), .city(.london), .title("Gluten Free"), .donut(.fireZest), .donut(.blackRaspberry), .title("Carrots"), .title("Donut vs Doughnut") ] var body: some View { VStack { CardNavigationHeader(panel: .socialFeed, navigation: navigation) { Label("Social Feed", systemImage: "text.bubble") } (FlowLayout(alignment: .center)) { ForEach(tags) { tag in tag.label } } .labelStyle(.socialFeedTag) #if canImport(UIKit) .backgroundStyle(Color(uiColor: .quaternarySystemFill)) #else .backgroundStyle(.quaternary.opacity(0.5)) #endif .frame(maxWidth: .infinity, minHeight: 180) .padding(.top, 15) Text("Trending Topics") .font(.footnote) .foregroundStyle(.secondary) Spacer() } .padding(10) .background() } } struct TruckSocialFeedCard_Previews: PreviewProvider { static var previews: some View { TruckSocialFeedCard() } } ``` ## TruckWeatherCard.swift ```swift /* Abstract: The weather card showing in the Truck view. */ import SwiftUI import Charts import FoodTruckKit @preconcurrency import CoreLocation @preconcurrency import WeatherKit struct TruckWeatherCard: View { var location: CLLocation var headerUsesNavigationLink: Bool = false var navigation: TruckCardHeaderNavigation = .navigationLink @State private var forecast: TruckWeatherForecast = placeholderForecast var body: some View { VStack { CardNavigationHeader(panel: .city(City.sanFrancisco.id), navigation: navigation) { Label("Forecast", systemImage: "cloud.sun") } chart .frame(minHeight: 180) } .padding(10) .background() .task { do { let weather = try await WeatherService.shared.weather(for: location, including: .hourly).forecast forecast = TruckWeatherForecast(entries: weather.map { .init( date: $0.date, degrees: $0.temperature.converted(to: .fahrenheit).value, isDaylight: $0.isDaylight ) }) } catch { print("Could not load weather", error.localizedDescription) } } } var chart: some View { Chart { areaMarks(seriesKey: "Temperature", value: 0) .foregroundStyle(.linearGradient(colors: [.teal, .yellow], startPoint: .bottom, endPoint: .top)) ForEach(forecast.nightTimeRanges, id: \.lowerBound) { range in RectangleMark( xStart: .value("Hour", range.lowerBound), xEnd: .value("Hour", range.upperBound) ) .opacity(0.5) .mask { areaMarks(seriesKey: "Mask", value: range.lowerBound.timeIntervalSince1970) } if range.lowerBound != forecast.entries.first!.date { let date = range.lowerBound RectangleMark( x: .value("Date", date), yStart: .value("Temperature", forecast.low - 0.5), yEnd: .value("Temperature", forecast.temperature(at: date) + 0.5), width: .fixed(4) ) .foregroundStyle(.indigo.shadow(.drop(color: .white.opacity(0.25), radius: 0, x: 1))) .cornerRadius(2) .annotation(position: .top, alignment: .bottom, spacing: 5) { Image(systemName: "moon.circle.fill") .imageScale(.large) .symbolRenderingMode(.palette) .foregroundStyle(.white, .indigo) } } if range.upperBound != forecast.entries.last!.date { let date = range.upperBound RectangleMark( x: .value("Date", date), yStart: .value("Temperature", forecast.low - 0.5), yEnd: .value("Temperature", forecast.temperature(at: date) + 0.5), width: .fixed(4) ) .foregroundStyle(.indigo.shadow(.drop(color: .white.opacity(0.25), radius: 0, x: -1))) .cornerRadius(2) .annotation(position: .top, alignment: .bottom, spacing: 5) { Image(systemName: "sun.max.circle.fill") .imageScale(.large) .symbolRenderingMode(.palette) .foregroundStyle(.white, .indigo) } } } } .chartXAxis { AxisMarks(values: DateBins(unit: .hour, by: 3, range: forecast.binRange).thresholds) { _ in AxisValueLabel(format: .dateTime.hour()) AxisTick() AxisGridLine() } } .chartYScale(domain: .automatic(includesZero: false)) .chartYAxis { AxisMarks(values: .automatic(minimumStride: 5, desiredCount: 6, roundLowerBound: false)) { value in AxisValueLabel("(value.as(Double.self)!.formatted())�F") AxisTick() AxisGridLine() } } } @ChartContentBuilder func areaMarks(seriesKey: String, value: Double) -> some ChartContent { ForEach(forecast.entries) { entry in AreaMark( x: .value("Hour", entry.date), yStart: .value("Temperature", forecast.low), yEnd: .value("Temperature", entry.degrees), series: .value(seriesKey, value) ) .interpolationMethod(.catmullRom) } } static var placeholderForecast: TruckWeatherForecast { func entry(hourOffset: Int, degrees: Double, isDaylight: Bool) -> TruckWeatherForecast.WeatherEntry { let startDate = Calendar.current.date(from: DateComponents(year: 2022, month: 5, day: 6, hour: 9))! let date = Calendar.current.date(byAdding: DateComponents(hour: hourOffset), to: startDate)! return TruckWeatherForecast.WeatherEntry(date: date, degrees: degrees, isDaylight: isDaylight) } return TruckWeatherForecast(entries: [ entry(hourOffset: 0, degrees: 63, isDaylight: true), entry(hourOffset: 1, degrees: 68, isDaylight: true), entry(hourOffset: 2, degrees: 72, isDaylight: true), entry(hourOffset: 3, degrees: 77, isDaylight: true), entry(hourOffset: 4, degrees: 80, isDaylight: true), entry(hourOffset: 5, degrees: 82, isDaylight: true), entry(hourOffset: 6, degrees: 83, isDaylight: true), entry(hourOffset: 7, degrees: 83, isDaylight: true), entry(hourOffset: 8, degrees: 81, isDaylight: true), entry(hourOffset: 9, degrees: 79, isDaylight: true), entry(hourOffset: 10, degrees: 75, isDaylight: true), entry(hourOffset: 11, degrees: 70, isDaylight: true), entry(hourOffset: 12, degrees: 66, isDaylight: false), entry(hourOffset: 13, degrees: 64, isDaylight: false), entry(hourOffset: 14, degrees: 63, isDaylight: false), entry(hourOffset: 15, degrees: 61, isDaylight: false), entry(hourOffset: 16, degrees: 60, isDaylight: false), entry(hourOffset: 17, degrees: 59, isDaylight: false), entry(hourOffset: 18, degrees: 57, isDaylight: false), entry(hourOffset: 19, degrees: 56, isDaylight: false), entry(hourOffset: 20, degrees: 55, isDaylight: false), entry(hourOffset: 21, degrees: 55, isDaylight: true), entry(hourOffset: 22, degrees: 56, isDaylight: true), entry(hourOffset: 23, degrees: 59, isDaylight: true), entry(hourOffset: 24, degrees: 62, isDaylight: true) ]) } } struct TruckWeatherForecast { struct WeatherEntry: Identifiable { var id: Date { date } var date: Date var degrees: Double var isDaylight: Bool } var entries: [WeatherEntry] var low: Double { return entries.map(\.degrees).min()! - 2 } var hottestEntry: WeatherEntry { return entries.sorted { $0.degrees > $1.degrees }.first! } var nightTimeRanges: [Range<Date>] { var currentLowerBound: Date? var results: [Range<Date>] = [] for entry in entries { if entry.isDaylight, let lowerBound = currentLowerBound { results.append(lowerBound..<entry.date) currentLowerBound = nil } else if !entry.isDaylight && currentLowerBound == nil { currentLowerBound = entry.date } } if let lowerBound = currentLowerBound { results.append(lowerBound..<entries.last!.date) } return results } var binRange: ClosedRange<Date> { let startDate: Date = entries.map(\.date).first(where: { Calendar.current.component(.hour, from: $0).isMultiple(of: 3) })! let endDate: Date = entries.map(\.date).reversed().first(where: { Calendar.current.component(.hour, from: $0).isMultiple(of: 3) })! return startDate ... endDate } func temperature(at date: Date) -> Double { entries.first(where: { $0.date == date })!.degrees } } struct TruckWeatherCard_Previews: PreviewProvider { static var previews: some View { TruckWeatherCard(location: City.sanFrancisco.parkingSpots[0].location) .aspectRatio(2, contentMode: .fit) .padding() .previewLayout(.sizeThatFits) } } ``` ## SalesHistoryChart.swift ```swift /* Abstract: The sales history chart view. */ import SwiftUI import Charts import FoodTruckKit struct SalesHistoryChart: View { var salesByCity: [SalesByCity] var hideChartContent: Bool = false var body: some View { Chart { ForEach(salesByCity) { citySales in ForEach(citySales.entries) { entry in LineMark( x: .value("Day", entry.date), y: .value("Sales", entry.sales) ) .foregroundStyle(by: .value("Location", citySales.city.name)) .interpolationMethod(.cardinal) .symbol(by: .value("Location", citySales.city.name)) .opacity(hideChartContent ? 0 : 1) } .lineStyle(StrokeStyle(lineWidth: 2)) } } .chartLegend(position: .top) .chartYScale(domain: .automatic(includesZero: false)) .chartXAxis { AxisMarks(values: .automatic(roundLowerBound: false, roundUpperBound: false)) { value in if value.index < value.count - 1 { AxisValueLabel() } AxisTick() AxisGridLine() } } } } struct SalesByCity: Identifiable { var id: String { city.id } var city: City var entries: [Entry] struct Entry: Identifiable { var id: Date { date } var date: Date var sales: Int } } struct SalesHistoryChart_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() var body: some View { SalesHistoryView(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## SalesHistoryView.swift ```swift /* Abstract: The sales history view. */ import SwiftUI import FoodTruckKit struct SalesHistoryView: View { @ObservedObject var model: FoodTruckModel @ObservedObject private var storeController = StoreActor.shared.productController @SceneStorage("historyTimeframe") private var timeframe: Timeframe = .week var annualHistoryIsUnlocked: Bool { storeController.isEntitled } var hideChartContent: Bool { timeframe != .week && !annualHistoryIsUnlocked } var body: some View { ScrollView { VStack { VStack(alignment: .leading) { Picker("Timeframe", selection: $timeframe) { Label("2 Weeks", systemImage: "calendar") .tag(Timeframe.week) Label("Month", systemImage: annualHistoryIsUnlocked ? "calendar" : "lock") .tag(Timeframe.month) Label("Year", systemImage: annualHistoryIsUnlocked ? "calendar" : "lock") .tag(Timeframe.year) } .pickerStyle(.segmented) .padding(.bottom, 10) Text("Total Sales") .font(.subheadline) .foregroundColor(.secondary) Text("(totalSales.formatted()) Donuts") .font(.headline) SalesHistoryChart(salesByCity: sales, hideChartContent: hideChartContent) .chartPlotStyle { content in content.chartOverlay { proxy in if hideChartContent { HStack { Image(systemName: "lock") Text("Premium Feature") } .foregroundColor(.secondary) .padding(20) .background(.background.shadow(.drop(color: .black.opacity(0.15), radius: 6, y: 2)), in: Capsule()) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.quaternary) } } } .frame(minHeight: 300) } .padding() UnlockFeatureView(controller: storeController) } } .navigationTitle("Sales History") .background() } var totalSales: Int { sales.flatMap(\.entries).reduce(into: 0) { (partialResult, entry) in partialResult += entry.sales } } var sales: [SalesByCity] { func dateComponents(_ offset: Int) -> DateComponents { switch timeframe { case .today: fatalError("Today timeframe is not supported.") case .week: return DateComponents(day: offset) case .month: return DateComponents(day: offset) case .year: return DateComponents(month: offset) } } return City.all.map { city in let summaries: [OrderSummary] switch timeframe { case .today: fatalError() case .week: summaries = Array(model.dailyOrderSummaries(cityID: city.id).prefix(14)) case .month: summaries = Array(model.dailyOrderSummaries(cityID: city.id).prefix(30)) case .year: summaries = model.monthlyOrderSummaries(cityID: city.id) } let entries = summaries .enumerated() .map { (offset, summary) in let startDate: Date if timeframe == .month || timeframe == .year { let components = Calendar.current.dateComponents([.year, .month], from: .now) startDate = Calendar.current.date(from: components)! } else { let components = Calendar.current.dateComponents([.year, .month, .day], from: .now) startDate = Calendar.current.date(from: components)! } let date = Calendar.current.date(byAdding: dateComponents(-offset), to: startDate)! return SalesByCity.Entry(date: date, sales: summary.totalSales) } return SalesByCity(city: city, entries: entries) } } } struct StatisticsView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() var body: some View { SalesHistoryView(model: model) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## SocialFeedContent.swift ```swift /* Abstract: Some content for the social feed view. */ import SwiftUI import FoodTruckKit struct SocialFeedPost: Identifiable { var id = UUID() var favoriteDonut: Donut var message: LocalizedStringKey var date: Date var tags: [SocialFeedTag] } enum SocialFeedTag: Identifiable { case title(LocalizedStringKey) case donut(Donut) case city(City) var id: String { switch self { case .title(let string): return "tag title: (string)" case .donut(let donut): return "tag donut: (donut.id)" case .city(let city): return "tag city: (city.id)" } } @ViewBuilder var icon: some View { switch self { case .title: Image(systemName: "tag") case .donut(let donut): DonutView(donut: donut) .padding(-3) case .city: Image(systemName: "building.2") } } var title: LocalizedStringKey { switch self { case .title(let string): return string case .donut(let donut): return .init(donut.name) case .city(let city): return .init(city.name) } } var label: some View { Label { Text(title) } icon: { icon } } } extension SocialFeedPost { static let standardContent: [SocialFeedPost] = { var date = Date.now func olderDate() -> Date { // minutes in the past date = date.addingTimeInterval(-60 * .random(in: 5...30)) return date } return [ SocialFeedPost( favoriteDonut: .classic, message: "I can't wait for the Food Truck to make its way to London!", date: olderDate(), tags: [.city(.london), .title("I'm waiting..."), .title("One of these days!")] ), SocialFeedPost( favoriteDonut: .blackRaspberry, message: "I'm really looking forward to trying the new chocolate donuts next time the truck is in town.", date: olderDate(), tags: [.donut(.lemonChocolate), .title("Chocolate!!!"), .donut(.powderedChocolate), .city(.sanFrancisco)] ), SocialFeedPost( favoriteDonut: .daytime, message: "Do you think there are any donuts in space?", date: olderDate(), tags: [.donut(.cosmos), .title("Space")] ), SocialFeedPost( favoriteDonut: .nighttime, message: "Thinking of checking out the Food Truck in its new location in SF today, anyone else down?", date: olderDate(), tags: [.city(.sanFrancisco), .title("Donuts for one"), .title("Unless...?")] ), SocialFeedPost( favoriteDonut: .custard, message: "I heard the Food Truck was in Cupertino today! Did anyone get a chance to visit?", date: olderDate(), tags: [.city(.cupertino), .title("Food Truck sighting")] ), SocialFeedPost( favoriteDonut: .figureSkater, message: "Okay, long day of work complete. Time to grab a bunch of donuts and get out of here!", date: olderDate(), tags: [.donut(.figureSkater), .donut(.blueberryFrosted), .donut(.powderedStrawberry), .title("Many more")] ), SocialFeedPost( favoriteDonut: .blueberryFrosted, message: "I think I just saw the Food Truck on its way to San Francisco! Taxi, follow that truck!", date: olderDate(), tags: [.donut(.classic), .city(.sanFrancisco), .title("And away we go!")] ) ] }() static let socialFeedPlusContent: [SocialFeedPost] = { var date = Date.now func olderDate() -> Date { // minutes in the past date = date.addingTimeInterval(-60 * .random(in: 5...30)) return date } return [ SocialFeedPost( favoriteDonut: .picnicBasket, message: "I'm going to place a huge order next time the Food Truck is in San Francisco!!", date: olderDate(), tags: [.city(.sanFrancisco), .donut(.classic), .title("Like two dozen!")] ), SocialFeedPost( favoriteDonut: .rainbow, message: "Just told my coworkers about the Food Truck and we are currently a group of 20 heading out.", date: olderDate(), tags: [.title("How many donuts are too many"), .title("Trick question"), .title("Please don't tell me")] ), SocialFeedPost( favoriteDonut: .fireZest, message: "Once the Food Truck adds carrot-flavored donuts; I'm going to order a million of them!", date: olderDate(), tags: [ .title("Carrot"), .title("Carrots of Social Feed"), .title("Bunnies of Social Feed"), .title("Carrots"), .title("Donuts for Bunnies") ] ) ] }() } extension LabelStyle where Self == SocialFeedTagLabelStyle { static var socialFeedTag: SocialFeedTagLabelStyle { SocialFeedTagLabelStyle() } } struct SocialFeedTagLabelStyle: LabelStyle { @ScaledMetric(relativeTo: .footnote) private var iconWidth = 14.0 func makeBody(configuration: Configuration) -> some View { HStack { configuration.icon .foregroundColor(.secondary) .frame(width: iconWidth) configuration.title } .padding(6) .background(in: RoundedRectangle(cornerRadius: 5, style: .continuous)) .font(.caption) } } ``` ## SocialFeedPostView.swift ```swift /* Abstract: The social post view. */ import SwiftUI import FoodTruckKit struct SocialFeedPostView: View { var post: SocialFeedPost @Environment(\.colorScheme) private var colorScheme var body: some View { VStack(alignment: .leading) { HStack(alignment: .top) { DonutView(donut: post.favoriteDonut) .shadow(color: .black.opacity(0.15), radius: 2, y: 1) .padding(.top, 5) .padding([.horizontal, .bottom], 6) .background(post.favoriteDonut.dough.backgroundColor.gradient, in: Circle()) .overlay { Circle() .strokeBorder(lineWidth: 0.5) .foregroundStyle(.tertiary) .blendMode(colorScheme == .light ? .plusDarker : .plusLighter) } .frame(width: 35, height: 35) VStack(alignment: .leading, spacing: 6) { Text(post.message) .font(.title3) (FlowLayout(alignment: .topLeading)) { ForEach(post.tags) { tag in tag.label .labelStyle(.socialFeedTag) } } .frame(maxWidth: .infinity, alignment: .leading) .backgroundStyle(tagBackgroundStyle) Text(dateString) .font(.caption) .foregroundStyle(.secondary) } } } .listRowInsets(EdgeInsets(top: 12, leading: 8, bottom: 12, trailing: 8)) } var dateString: String { let day: String = { if Calendar.current.isDateInToday(post.date) { return String(localized: "Today") } else if Calendar.current.isDateInYesterday(post.date) { return String(localized: "Yesterday") } else { return post.date.formatted(date: .abbreviated, time: .omitted) } }() return String(localized: "(day), (post.date.formatted(date: .omitted, time: .shortened))") } var tagBackgroundStyle: AnyShapeStyle { #if canImport(UIKit) return AnyShapeStyle(Color(uiColor: .quaternarySystemFill)) #else return AnyShapeStyle(.quaternary.opacity(0.5)) #endif } } struct SocialFeedPostView_Previews: PreviewProvider { static var previews: some View { let post = SocialFeedPost( favoriteDonut: .strawberrySprinkles, message: "Hello, this is a preview of a social-feed post!", date: .now, tags: [.title("A cool tag"), .donut(.blackRaspberry), .city(.london)] ) SocialFeedPostView(post: post) .padding() .previewLayout(.sizeThatFits) } } ``` ## SocialFeedView.swift ```swift /* Abstract: The social feed view. */ import SwiftUI import FoodTruckKit struct SocialFeedView: View { @ObservedObject var subscriptionController = StoreActor.shared.subscriptionController @State private var storeIsPresented = false @State private var manageSocialFeedPlusIsPresented = false var navigationTitle: LocalizedStringKey { if hasPlus { return "Social Feed+" } return "Social Feed" } var hasPlus: Bool { subscriptionController.entitledSubscriptionID != nil } var body: some View { WidthThresholdReader { proxy in List { if !hasPlus { SocialFeedPlusMarketingView(storeIsPresented: $storeIsPresented) } else { Section("Highlighted Posts") { ForEach(SocialFeedPost.socialFeedPlusContent) { post in SocialFeedPostView(post: post) } } } Section("Posts") { ForEach(SocialFeedPost.standardContent) { post in SocialFeedPostView(post: post) } } } .toolbar { if subscriptionController.entitledSubscriptionID != nil { Button { manageSocialFeedPlusIsPresented = true } label: { Label("Subscription Options", systemImage: "plus.bubble") } } } } .navigationTitle(navigationTitle) .sheet(isPresented: $storeIsPresented) { SubscriptionStoreView(controller: subscriptionController) #if os(macOS) .frame(minWidth: 400, minHeight: 400) #endif } .sheet(isPresented: $manageSocialFeedPlusIsPresented) { NavigationStack { SocialFeedPlusSettings(controller: subscriptionController) #if os(macOS) .frame(minWidth: 300, minHeight: 350) #endif } } } } struct SocialFeedPlusMarketingView: View { @Binding var storeIsPresented: Bool #if os(macOS) @Environment(\.colorScheme) private var colorScheme #endif var body: some View { Section { VStack(alignment: .center, spacing: 5) { Text("Get Social Feed+") .font(.title2) .bold() Text("The definitive social-feed experience") .font(.subheadline) Button { storeIsPresented = true } label: { Text("Get Started") .bold() .padding(.vertical, 2) #if os(macOS) .foregroundColor( colorScheme == .light ? .accentColor : .white ) #endif } #if os(iOS) .buttonStyle(.borderedProminent) .foregroundColor(.accentColor) #elseif os(macOS) .buttonStyle(.bordered) #endif .tint(.white) .padding(.top) } .foregroundColor(.white) .padding(10) .frame(maxWidth: .infinity) } #if os(iOS) .listRowBackground(Rectangle().fill(.indigo.gradient)) #elseif os(macOS) .background(.indigo.gradient) .cornerRadius(10) #endif } } struct SocialFeedView_Previews: PreviewProvider { static var previews: some View { NavigationStack { SocialFeedView() } } } ``` ## TruckView.swift ```swift /* Abstract: The app's landing page view. */ import SwiftUI import FoodTruckKit struct TruckView: View { @ObservedObject var model: FoodTruckModel @Binding var navigationSelection: Panel? #if os(iOS) @Environment(\.horizontalSizeClass) private var sizeClass #endif var body: some View { WidthThresholdReader(widthThreshold: 520) { proxy in ScrollView(.vertical) { VStack(spacing: 16) { BrandHeader() Grid(horizontalSpacing: 12, verticalSpacing: 12) { if proxy.isCompact { orders weather donuts socialFeed } else { GridRow { orders weather } GridRow { donuts socialFeed } } } .containerShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) .fixedSize(horizontal: false, vertical: true) .padding([.horizontal, .bottom], 16) .frame(maxWidth: 1200) } } } #if os(iOS) .background(Color(uiColor: .systemGroupedBackground)) #else .background(.quaternary.opacity(0.5)) #endif .background() .navigationTitle("Truck") .navigationDestination(for: Panel.self) { panel in switch panel { case .orders: OrdersView(model: model) case .donuts: DonutGallery(model: model) case .socialFeed: SocialFeedView() case .city(let id): CityView(city: City.identified(by: id)) default: DonutGallery(model: model) } } } // MARK: - Cards var orders: some View { TruckOrdersCard(model: model, navigation: cardNavigation) } var weather: some View { TruckWeatherCard(location: model.truck.location.location, navigation: cardNavigation) } var donuts: some View { TruckDonutsCard(donuts: model.donuts, navigation: cardNavigation) } var socialFeed: some View { TruckSocialFeedCard(navigation: cardNavigation) } var cardNavigation: TruckCardHeaderNavigation { let useNavigationLink: Bool = { #if os(iOS) return sizeClass == .compact #else return false #endif }() if useNavigationLink { return .navigationLink } else { return .selection($navigationSelection) } } } enum TruckCardHeaderNavigation { case navigationLink case selection(Binding<Panel?>) } // MARK: - Previews struct TruckView_Previews: PreviewProvider { struct Preview: View { @StateObject private var model = FoodTruckModel() @State private var navigationSelection: Panel? = Panel.truck var body: some View { TruckView(model: model, navigationSelection: $navigationSelection) } } static var previews: some View { NavigationStack { Preview() } } } ``` ## Package.swift ```swift // swift-tools-version: 5.7 /* Abstract: The FoodTruckKit package. */ import PackageDescription let package = Package( name: "FoodTruckKit", defaultLocalization: "en", platforms: [ .macOS("13.3"), .iOS("16.4"), .macCatalyst("16.4") ], products: [ .library( name: "FoodTruckKit", targets: ["FoodTruckKit"] ) ], dependencies: [], targets: [ .target( name: "FoodTruckKit", dependencies: [], path: "Sources" ) ] ) ``` ## AccountStore.swift ```swift /* Abstract: AccountStore manages account sign in and out. */ #if os(iOS) || os(macOS) import AuthenticationServices import SwiftUI import Combine import os public extension Logger { static let authorization = Logger(subsystem: "FoodTruck", category: "Food Truck accounts") } public enum AuthorizationHandlingError: Error { case unknownAuthorizationResult(ASAuthorizationResult) case otherError } extension AuthorizationHandlingError: LocalizedError { public var errorDescription: String? { switch self { case .unknownAuthorizationResult: return NSLocalizedString("Received an unknown authorization result.", comment: "Human readable description of receiving an unknown authorization result.") case .otherError: return NSLocalizedString("Encountered an error handling the authorization result.", comment: "Human readable description of an unknown error while handling the authorization result.") } } } @MainActor public final class AccountStore: NSObject, ObservableObject, ASAuthorizationControllerDelegate { @Published public private(set) var currentUser: User? = .default public weak var presentationContextProvider: ASAuthorizationControllerPresentationContextProviding? public var isSignedIn: Bool { currentUser != nil } public func signIntoPasskeyAccount(authorizationController: AuthorizationController, options: ASAuthorizationController.RequestOptions = []) async { do { let authorizationResult = try await authorizationController.performRequests( signInRequests(), options: options ) try await handleAuthorizationResult(authorizationResult) } catch let authorizationError as ASAuthorizationError where authorizationError.code == .canceled { // The user cancelled the authorization. Logger.authorization.log("The user cancelled passkey authorization.") } catch let authorizationError as ASAuthorizationError { // Some other error occurred occurred during authorization. Logger.authorization.error("Passkey authorization failed. Error: (authorizationError.localizedDescription)") } catch AuthorizationHandlingError.unknownAuthorizationResult(let authorizationResult) { // Received an unknown response. Logger.authorization.error(""" Passkey authorization handling failed. \ Received an unknown result: (String(describing: authorizationResult)) """) } catch { // Some other error occurred while handling the authorization. Logger.authorization.error(""" Passkey authorization handling failed. \ Caught an unknown error during passkey authorization or handling: (error.localizedDescription)" """) } } public func createPasskeyAccount(authorizationController: AuthorizationController, username: String, options: ASAuthorizationController.RequestOptions = []) async { do { let authorizationResult = try await authorizationController.performRequests( [passkeyRegistrationRequest(username: username)], options: options ) try await handleAuthorizationResult(authorizationResult, username: username) } catch let authorizationError as ASAuthorizationError where authorizationError.code == .canceled { // The user cancelled the registration. Logger.authorization.log("The user cancelled passkey registration.") } catch let authorizationError as ASAuthorizationError { // Some other error occurred occurred during registration. Logger.authorization.error("Passkey registration failed. Error: (authorizationError.localizedDescription)") } catch AuthorizationHandlingError.unknownAuthorizationResult(let authorizationResult) { // Received an unknown response. Logger.authorization.error(""" Passkey registration handling failed. \ Received an unknown result: (String(describing: authorizationResult)) """) } catch { // Some other error occurred while handling the registration. Logger.authorization.error(""" Passkey registration handling failed. \ Caught an unknown error during passkey registration or handling: (error.localizedDescription). """) } } public func createPasswordAccount(username: String, password: String) async { currentUser = .authenticated(username: username) } public func signOut() { currentUser = nil } // MARK: - Private private static let relyingPartyIdentifier = "example.com" private func passkeyChallenge() async -> Data { Data("passkey challenge".utf8) } private func passkeyAssertionRequest() async -> ASAuthorizationRequest { await ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: Self.relyingPartyIdentifier) .createCredentialAssertionRequest(challenge: passkeyChallenge()) } private func passkeyRegistrationRequest(username: String) async -> ASAuthorizationRequest { await ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: Self.relyingPartyIdentifier) .createCredentialRegistrationRequest(challenge: passkeyChallenge(), name: username, userID: Data(username.utf8)) } private func signInRequests() async -> [ASAuthorizationRequest] { await [passkeyAssertionRequest(), ASAuthorizationPasswordProvider().createRequest()] } // MARK: - Handle the results. private func handleAuthorizationResult(_ authorizationResult: ASAuthorizationResult, username: String? = nil) async throws { switch authorizationResult { case let .password(passwordCredential): Logger.authorization.log("Password authorization succeeded: (passwordCredential)") currentUser = .authenticated(username: passwordCredential.user) case let .passkeyAssertion(passkeyAssertion): // The login was successful. Logger.authorization.log("Passkey authorization succeeded: (passkeyAssertion)") guard let username = String(bytes: passkeyAssertion.userID, encoding: .utf8) else { fatalError("Invalid credential: (passkeyAssertion)") } currentUser = .authenticated(username: username) case let .passkeyRegistration(passkeyRegistration): // The registration was successful. Logger.authorization.log("Passkey registration succeeded: (passkeyRegistration)") if let username { currentUser = .authenticated(username: username) } default: Logger.authorization.error("Received an unknown authorization result.") // Throw an error and return to the caller. throw AuthorizationHandlingError.unknownAuthorizationResult(authorizationResult) } // In a real app, call the code at this location to obtain and save an authentication token to the keychain and sign in the user. } } #endif // os(iOS) || os(macOS) ``` ## User.swift ```swift /* Abstract: A model object to store user status. */ public enum User { case `default` case authenticated(username: String) public init(username: String) { self = .authenticated(username: username) } } ``` ## BrandHeader.swift ```swift /* Abstract: The branded header view. */ import SwiftUI public struct BrandHeader: View { public var animated: Bool public var headerSize: HeaderSize public enum HeaderSize: Double, RawRepresentable { case standard = 1.0 case reduced = 0.5 } public init(animated: Bool = true, size: HeaderSize = .standard) { self.animated = animated self.headerSize = size } var skyGradient: Gradient { Gradient(colors: [ Color("header/Sky Start", bundle: .module), Color("header/Sky End", bundle: .module) ]) } public var body: some View { TimelineView(.animation(paused: !animated)) { context in let director = AnimationDirector(timeInterval: context.date.timeIntervalSince1970) Canvas { context, size in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let centerX = size.width * 0.5 let scale = self.headerSize.rawValue // MARK: Background sky gradient context.fill( Rectangle().path(in: rect), with: .radialGradient( skyGradient, center: CGPoint(x: rect.midX, y: 400 * scale), startRadius: 0, endRadius: 600 ) ) // MARK: Background Layers for layer in director.backgroundLayers { context.drawLayer { context in context.translateBy(x: centerX, y: (750 + layer.yOffset) * scale) context.rotate(by: -layer.rotation) context.scaleBy(x: scale, y: scale) context.draw(layer.image, at: .zero) } } // MARK: Road & Truck Shadow context.drawLayer { context in context.translateBy(x: centerX, y: 350 * scale) context.scaleBy(x: scale, y: scale) context.draw(Image("header/layer/8 Road", bundle: .module), at: .zero) } // MARK: Truck context.drawLayer { context in context.translateBy(x: centerX, y: 307 * scale) context.scaleBy(x: scale, y: scale) context.draw(director.truckImage, at: .zero) } // MARK: Foreground for layer in director.foregroundLayers { context.drawLayer { context in context.translateBy(x: centerX, y: 770 * scale) context.rotate(by: -layer.rotation) context.scaleBy(x: scale, y: scale) context.draw(layer.image, at: .zero) } } } .padding(.top, -200 * headerSize.rawValue) // bleed into top safe area } .frame(height: 200 * headerSize.rawValue) // but only take up 200 height } } // MARK: - Animation Director extension BrandHeader { // A collection of computed values necessary for animating the BrandHeader based on the current time. struct AnimationDirector { // Derived values. var foregroundLayers: [RotatedLayer] var truckImage: Image var backgroundLayers: [RotatedLayer] init(timeInterval: TimeInterval) { func layerImage(_ name: String) -> Image { Image("header/layer/(name)", bundle: .module) } // Returns an `Angle` from 0 to 360 degrees based on the current time and how long it takes to rotate. func rotationPercent(duration: TimeInterval) -> Angle { Angle.radians(timeInterval.percent(truncation: duration) * .pi * 2) } // MARK: Background Layers backgroundLayers = [ RotatedLayer( image: layerImage("1 Small Clouds"), rotation: rotationPercent(duration: 760), yOffset: 0 ), RotatedLayer( image: layerImage("2 Medium Clouds"), rotation: rotationPercent(duration: 720), yOffset: -15 ), RotatedLayer( image: layerImage("3 Mountains"), rotation: rotationPercent(duration: 840), yOffset: -10 ), RotatedLayer( image: layerImage("4 Big Clouds"), rotation: rotationPercent(duration: 400) ), RotatedLayer( image: layerImage("5 Ocean"), rotation: rotationPercent(duration: 480) ), RotatedLayer( image: layerImage("6 Balloons"), rotation: rotationPercent(duration: 540) ), RotatedLayer( image: layerImage("7 Trees"), rotation: rotationPercent(duration: 180), yOffset: -10 ) ] // MARK: Foreground Layers foregroundLayers = [ RotatedLayer( image: layerImage("9 Foreground"), rotation: rotationPercent(duration: 96) ) ] // MARK: Truck let truckFrame: Int = { // Percent of frame changes per second from the first to last image in a twelve-frame-per-second animation. let framesPerSecond = 12.0 let totalFrames = 4.0 let percent = timeInterval.percent(truncation: (1 / framesPerSecond) * totalFrames) return Int(floor(percent * totalFrames)) }() truckImage = Image("header/truck/Frame (truckFrame + 1)", bundle: .module) } } } // MARK: - Rotated Layer extension BrandHeader { struct RotatedLayer { var image: Image var rotation: Angle var yOffset: Double = 0 } } // MARK: - Previews struct BrandHeader_Previews: PreviewProvider { static var previews: some View { ScrollView { BrandHeader() } .previewDisplayName("In Scroll View") BrandHeader() .border(.red.opacity(0.5)) .frame(height: 400, alignment: .bottom) .border(.green.opacity(0.5)) .frame(width: 1200, height: 1200, alignment: .top) .previewLayout(.sizeThatFits) .previewDisplayName("Full Size") } } ``` ## City.swift ```swift /* Abstract: The city model object. */ import Foundation import CoreLocation public struct City: Identifiable, Hashable { public var id: String { name } public var name: String public var parkingSpots: [ParkingSpot] } public extension City { static let sanFrancisco = City( name: String(localized: "San Francisco", bundle: .module, comment: "A city in California."), parkingSpots: [ ParkingSpot( name: String(localized: "Coit Tower", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.8024, longitude: -122.4058), cameraDistance: 300 ), ParkingSpot( name: String(localized: "Fisherman's Wharf", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.8099, longitude: -122.4103), cameraDistance: 700 ), ParkingSpot( name: String(localized: "Ferry Building", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.7956, longitude: -122.3935), cameraDistance: 450 ), ParkingSpot( name: String(localized: "Golden Gate Bridge", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.8199, longitude: -122.4783), cameraDistance: 2000 ), ParkingSpot( name: String(localized: "Oracle Park", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.7786, longitude: -122.3893), cameraDistance: 650 ), ParkingSpot( name: String(localized: "The Castro Theatre", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.7609, longitude: -122.4350), cameraDistance: 400 ), ParkingSpot( name: String(localized: "Sutro Tower", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.7552, longitude: -122.4528) ), ParkingSpot( name: String(localized: "Bay Bridge", bundle: .module, comment: "A landmark in San Francisco."), location: CLLocation(latitude: 37.7983, longitude: -122.3778) ) ] ) static let cupertino = City( name: String(localized: "Cupertino", bundle: .module, comment: "A city in California."), parkingSpots: [ ParkingSpot( name: String(localized: "Apple Park", bundle: .module, comment: "Apple's headquarters in California."), location: CLLocation(latitude: 37.3348, longitude: -122.0090), cameraDistance: 1100 ), ParkingSpot( name: String(localized: "Infinite Loop", comment: "One of Apple's buildings in California."), location: CLLocation(latitude: 37.3317, longitude: -122.0302) ) ] ) static let london = City( name: String(localized: "London", bundle: .module, comment: "A city in England."), parkingSpots: [ ParkingSpot( name: String(localized: "Big Ben", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.4994, longitude: -0.1245), cameraDistance: 850 ), ParkingSpot( name: String(localized: "Buckingham Palace", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.5014, longitude: -0.1419), cameraDistance: 750 ), ParkingSpot( name: String(localized: "Marble Arch", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.5131, longitude: -0.1589) ), ParkingSpot( name: String(localized: "Piccadilly Circus", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.510_067, longitude: -0.133_869) ), ParkingSpot( name: String(localized: "Shakespeare's Globe", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.5081, longitude: -0.0972) ), ParkingSpot( name: String(localized: "Tower Bridge", bundle: .module, comment: "A landmark in London."), location: CLLocation(latitude: 51.5055, longitude: -0.0754) ) ] ) static let all = [cupertino, sanFrancisco, london] static func identified(by id: City.ID) -> City { guard let result = all.first(where: { $0.id == id }) else { fatalError("Unknown City ID: (id)") } return result } } ``` ## ParkingSpot.swift ```swift /* Abstract: The parking spot model object. */ import Foundation import CoreLocation public struct ParkingSpot: Identifiable, Hashable { public var id: String { name } public var name: String public var location: CLLocation public var cameraDistance: Double = 1000 } ``` ## DiagonalDonutStackLayout.swift ```swift /* Abstract: A custom layout that places up to 3 views (tuned for `DonutView`) diagonally inside a square aspect ratio. */ import SwiftUI private let defaultSize = CGSize(width: 60, height: 60) public struct DiagonalDonutStackLayout: Layout { public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize { let proposal = proposal.replacingUnspecifiedDimensions(by: defaultSize) let minBound = min(proposal.width, proposal.height) return CGSize(width: minBound, height: minBound) } public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) { let proposal = proposal.replacingUnspecifiedDimensions(by: defaultSize) let minBound = min(proposal.width, proposal.height) let size = CGSize(width: minBound, height: minBound) let rect = CGRect( origin: CGPoint(x: bounds.minX + bounds.width - minBound, y: bounds.minY + bounds.height - minBound), size: size ) let center = CGPoint(x: rect.midX, y: rect.midY) let subviews = subviews.prefix(3) for index in subviews.indices { switch (index, subviews.count) { case (_, 1): subviews[index].place( at: center, anchor: .center, proposal: ProposedViewSize(size) ) case (_, 2): let direction = index == 0 ? -1.0 : 1.0 let offsetX = minBound * direction * 0.15 let offsetY = minBound * direction * 0.20 subviews[index].place( at: CGPoint(x: center.x + offsetX, y: center.y + offsetY), anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.7, height: size.height * 0.7)) ) case (1, 3): subviews[index].place( at: center, anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.65, height: size.height * 0.65)) ) case (_, 3): let direction = index == 0 ? -1.0 : 1.0 let offsetX = minBound * direction * 0.15 let offsetY = minBound * direction * 0.23 subviews[index].place( at: CGPoint(x: center.x + offsetX, y: center.y + offsetY), anchor: .center, proposal: ProposedViewSize(CGSize(width: size.width * 0.7, height: size.height * 0.65)) ) default: print("Ignore me!") } } } } ``` ## Donut.swift ```swift /* Abstract: The donut model object. */ import UniformTypeIdentifiers import SwiftUI public struct Donut: Identifiable, Hashable { public var id: Int public var name: String public var dough: Dough public var glaze: Glaze? public var topping: Topping? public init(id: Int, name: String, dough: Donut.Dough, glaze: Donut.Glaze? = nil, topping: Donut.Topping? = nil) { self.id = id self.name = name self.dough = dough self.glaze = glaze self.topping = topping } public var ingredients: [any Ingredient] { var result: [any Ingredient] = [] result.append(dough) if let glaze = glaze { result.append(glaze) } if let topping = topping { result.append(topping) } return result } public var flavors: FlavorProfile { ingredients .map(\.flavors) .reduce(into: FlavorProfile()) { partialResult, next in partialResult.formUnion(with: next) } } public func matches(searchText: String) -> Bool { if searchText.isEmpty { return true } if name.localizedCaseInsensitiveContains(searchText) { return true } return ingredients.contains { ingredient in ingredient.name.localizedCaseInsensitiveContains(searchText) } } } public extension Donut { static let classic = Donut( id: 0, name: String(localized: "The Classic", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .chocolate, topping: .sprinkles ) static let blueberryFrosted = Donut( id: 1, name: String(localized: "Blueberry Frosted", bundle: .module, comment: "A donut-flavor name."), dough: .blueberry, glaze: .blueberry, topping: .sugarLattice ) static let strawberryDrizzle = Donut( id: 2, name: String(localized: "Strawberry Drizzle", bundle: .module, comment: "A donut-flavor name."), dough: .strawberry, glaze: .strawberry, topping: .sugarDrizzle ) static let cosmos = Donut( id: 3, name: String(localized: "Cosmos", bundle: .module, comment: "A donut-flavor name."), dough: .chocolate, glaze: .chocolate, topping: .starSprinkles ) static let strawberrySprinkles = Donut( id: 4, name: String(localized: "Strawberry Sprinkles", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .strawberry, topping: .starSprinkles ) static let lemonChocolate = Donut( id: 5, name: String(localized: "Lemon Chocolate", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .chocolate, topping: .lemonLines ) static let rainbow = Donut( id: 6, name: String(localized: "Rainbow", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .rainbow ) static let picnicBasket = Donut( id: 7, name: String(localized: "Picnic Basket", bundle: .module, comment: "A donut-flavor name."), dough: .chocolate, glaze: .strawberry, topping: .blueberryLattice ) static let figureSkater = Donut( id: 8, name: String(localized: "Figure Skater", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .blueberry, topping: .sugarDrizzle ) static let powderedChocolate = Donut( id: 9, name: String(localized: "Powdered Chocolate", bundle: .module, comment: "A donut-flavor name."), dough: .chocolate, topping: .powderedSugar ) static let powderedStrawberry = Donut( id: 10, name: String(localized: "Powdered Strawberry", bundle: .module, comment: "A donut-flavor name."), dough: .strawberry, topping: .powderedSugar ) static let custard = Donut( id: 11, name: String(localized: "Custard", bundle: .module, comment: "A donut-flavor name."), dough: .lemonade, glaze: .spicy, topping: .lemonLines ) static let superLemon = Donut( id: 12, name: String(localized: "Super Lemon", bundle: .module, comment: "A donut-flavor name."), dough: .lemonade, glaze: .lemon, topping: .sprinkles ) static let fireZest = Donut( id: 13, name: String(localized: "Fire Zest", bundle: .module, comment: "A donut-flavor name."), dough: .lemonade, glaze: .spicy, topping: .spicySauceDrizzle ) static let blackRaspberry = Donut( id: 14, name: String(localized: "Black Raspberry", bundle: .module, comment: "A donut-flavor name."), dough: .plain, glaze: .chocolate, topping: .blueberryDrizzle ) static let daytime = Donut( id: 15, name: String(localized: "Daytime", bundle: .module, comment: "A donut-flavor name."), dough: .lemonade, glaze: .rainbow ) static let nighttime = Donut( id: 16, name: String(localized: "Nighttime", bundle: .module, comment: "A donut-flavor name."), dough: .chocolate, glaze: .chocolate, topping: .chocolateDrizzle ) static let all = [ classic, blueberryFrosted, strawberryDrizzle, cosmos, strawberrySprinkles, lemonChocolate, rainbow, picnicBasket, figureSkater, powderedChocolate, powderedStrawberry, custard, superLemon, fireZest, blackRaspberry, daytime, nighttime ] static var preview: Donut { .classic } } public extension UTType { static let donut = UTType(exportedAs: "com.example.apple-samplecode.donut") } ``` ## DonutBoxView.swift ```swift /* Abstract: A view showing donuts in a box. */ import SwiftUI public struct DonutBoxView<Content: View>: View { var isOpen: Bool var content: Content public init(isOpen: Bool, @ViewBuilder content: () -> Content) { self.isOpen = isOpen self.content = content() } public var body: some View { GeometryReader { proxy in let length = min(proxy.size.width, proxy.size.height) ZStack { Image("box/Inside", bundle: .module) .resizable() .scaledToFit() content .padding(floor(length * 0.15)) .frame(width: length, height: length) Image("box/Bottom", bundle: .module) .resizable() .scaledToFit() if isOpen { Image("box/Lid", bundle: .module) .resizable() .scaledToFit() .transition( .scale(scale: 0.75, anchor: .bottom) .combined(with: .offset(y: -length * 0.5)) .combined(with: .opacity) ) } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } } extension DonutBoxView where Content == EmptyView { public init(isOpen: Bool) { self.init(isOpen: isOpen) { EmptyView() } } } struct DonutBoxView_Previews: PreviewProvider { struct Preview: View { @State private var isOpen = true var body: some View { DonutBoxView(isOpen: isOpen) .onTapGesture { withAnimation(.spring(response: 0.25, dampingFraction: 1)) { isOpen.toggle() } } } } static var previews: some View { Preview() } } ``` ## DonutRenderer.swift ```swift /* Abstract: Renders donuts into images. */ import SwiftUI public struct DonutRenderer: View { static private var thumbnails = [Donut.ID: Image]() var donut: Donut public init(donut: Donut) { self.donut = donut } @State private var imageIsReady = false @Environment(\.displayScale) private var displayScale public var body: some View { ZStack { if imageIsReady { Self.thumbnails[donut.id]! .resizable() .interpolation(.medium) .antialiased(true) .scaledToFit() } else { ProgressView() .controlSize(.small) .frame(maxWidth: .infinity, maxHeight: .infinity) } } .onAppear { imageIsReady = Self.thumbnails.keys.contains(donut.id) guard !imageIsReady else { return } let renderer = ImageRenderer(content: DonutView(donut: donut)) renderer.proposedSize = ProposedViewSize(width: donutThumbnailSize, height: donutThumbnailSize) renderer.scale = displayScale if let cgImage = renderer.cgImage { let image = Image(cgImage, scale: displayScale, label: Text(donut.name)) Self.thumbnails[donut.id] = image imageIsReady = true } } } } struct DonutRenderer_Previews: PreviewProvider { static var previews: some View { DonutRenderer(donut: .preview) } } ``` ## DonutSales.swift ```swift /* Abstract: The donut sales model object. */ import Foundation public struct DonutSales: Identifiable, Comparable { public var id: Donut.ID { donut.id } public var donut: Donut public var sales: Int public init(donut: Donut, sales: Int) { self.donut = donut self.sales = sales } public static func <(lhs: DonutSales, rhs: DonutSales) -> Bool { if lhs.sales == rhs.sales { return lhs.donut.id < rhs.donut.id } else { return lhs.sales < rhs.sales } } } public extension DonutSales { static var previewArray: [DonutSales] = [ .init(donut: .classic, sales: 5), .init(donut: .picnicBasket, sales: 3), .init(donut: .strawberrySprinkles, sales: 10), .init(donut: .nighttime, sales: 4), .init(donut: .blackRaspberry, sales: 12) ] } ``` ## DonutStackView.swift ```swift /* Abstract: A donut stack view using a layout. */ import SwiftUI public struct DonutStackView: View { var donuts: [Donut] var includeOverflowCount: Bool public init(donuts: [Donut], includeOverflowCount: Bool = false) { self.donuts = donuts self.includeOverflowCount = includeOverflowCount } public var body: some View { DiagonalDonutStackLayout { ForEach(donuts.prefix(3)) { donut in DonutView(donut: donut) } } .overlay(alignment: .bottomTrailing) { let extra = donuts.count - 3 if extra > 0 && includeOverflowCount { Text("+(extra)") .foregroundStyle(.secondary) .font(.caption2) .padding(4) #if !os(watchOS) .background(.thinMaterial, in: Capsule()) #else .background(in: Capsule()) #endif .padding(4) } } } } struct DonutStackView_Previews: PreviewProvider { static var previews: some View { VStack { Group { DonutStackView(donuts: [.classic]) DonutStackView(donuts: [.classic, .cosmos]) DonutStackView(donuts: [.classic, .cosmos, .rainbow]) DonutStackView(donuts: [.classic, .cosmos, .rainbow, .classic, .classic, .classic], includeOverflowCount: true) } .frame(width: 120, height: 120) .border(.quaternary) } .padding() } } ``` ## DonutView.swift ```swift /* Abstract: A donut view. */ import SwiftUI public let donutThumbnailSize: Double = 128 public struct DonutView: View { var donut: Donut var visibleLayers: DonutLayer = .all public init(donut: Donut, visibleLayers: DonutLayer = .all) { self.donut = donut self.visibleLayers = visibleLayers } public var body: some View { GeometryReader { proxy in let useThumbnail = min(proxy.size.width, proxy.size.height) <= donutThumbnailSize ZStack { if visibleLayers.contains(.dough) { donut.dough.image(thumbnail: useThumbnail) .resizable() .interpolation(.medium) .scaledToFit() .id(donut.dough.id) } if let glaze = donut.glaze, visibleLayers.contains(.glaze) { glaze.image(thumbnail: useThumbnail) .resizable() .interpolation(.medium) .scaledToFit() .id(glaze.id) } if let topping = donut.topping, visibleLayers.contains(.topping) { topping.image(thumbnail: useThumbnail) .resizable() .interpolation(.medium) .scaledToFit() .id(topping.id) } } .aspectRatio(1, contentMode: .fit) .compositingGroup() .frame(maxWidth: .infinity, maxHeight: .infinity) } } } public struct DonutLayer: OptionSet { public var rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let dough = DonutLayer(rawValue: 1 << 1) public static let glaze = DonutLayer(rawValue: 1 << 2) public static let topping = DonutLayer(rawValue: 1 << 3) public static let all: DonutLayer = [dough, glaze, topping] } struct DonutCanvas_Previews: PreviewProvider { static var previews: some View { DonutView(donut: .preview) } } ``` ## FlavorProfile.swift ```swift /* Abstract: The flavor-profile model. */ import SwiftUI public struct FlavorProfile: Hashable, Codable { public var salty: Int public var sweet: Int public var bitter: Int public var sour: Int public var savory: Int public var spicy: Int public init(salty: Int = 0, sweet: Int = 0, bitter: Int = 0, sour: Int = 0, savory: Int = 0, spicy: Int = 0) { self.salty = salty self.sweet = sweet self.bitter = bitter self.sour = sour self.savory = savory self.spicy = spicy } public subscript(flavor: Flavor) -> Int { get { switch flavor { case .salty: return salty case .sweet: return sweet case .bitter: return bitter case .sour: return sour case .savory: return savory case .spicy: return spicy } } set(newValue) { switch flavor { case .salty: salty = newValue case .sweet: sweet = newValue case .bitter: bitter = newValue case .sour: sour = newValue case .savory: savory = newValue case .spicy: spicy = newValue } } } public func union(with other: FlavorProfile) -> FlavorProfile { var result = self for flavor in Flavor.allCases { result[flavor] += other[flavor] } return result } public mutating func formUnion(with other: FlavorProfile) { self = union(with: other) } public var mostPotent: (Flavor, Int) { var highestValue = 0 var mostPotent = Flavor.sweet for flavor in Flavor.allCases { let value = self[flavor] if value > highestValue { highestValue = value mostPotent = flavor } } return (mostPotent, highestValue) } public var mostPotentFlavor: Flavor { mostPotent.0 } public var mostPotentValue: Int { mostPotent.1 } } public enum Flavor: String, Identifiable, CaseIterable { case salty, sweet, bitter, sour, savory, spicy public var id: String { rawValue } public var name: String { switch self { case .salty: return String(localized: "Salty", bundle: .module, comment: "The main flavor-profile of a donut.") case .sweet: return String(localized: "Sweet", bundle: .module, comment: "The main flavor-profile of a donut.") case .bitter: return String(localized: "Bitter", bundle: .module, comment: "The main flavor-profile of a donut.") case .sour: return String(localized: "Sour", bundle: .module, comment: "The main flavor-profile of a donut.") case .savory: return String(localized: "Savory", bundle: .module, comment: "The main flavor-profile of a donut.") case .spicy: return String(localized: "Spicy", bundle: .module, comment: "The main flavor-profile of a donut.") } } public var image: Image { Image.flavorSymbol(self) } } ``` ## Dough.swift ```swift /* Abstract: An extension to donut to represent the dough. */ import SwiftUI public extension Donut { struct Dough: Ingredient { public var name: String public var imageAssetName: String public var flavors: FlavorProfile public var backgroundColor: Color { Color("(Self.imageAssetPrefix)/(imageAssetName)-bg", bundle: .module) } public static let imageAssetPrefix = "dough" } } public extension Donut.Dough { static let blueberry = Donut.Dough( name: String(localized: "Blueberry Dough", bundle: .module, comment: "Blueberry-flavored dough."), imageAssetName: "blue", flavors: FlavorProfile(salty: 1, sweet: 2, savory: 2) ) static let chocolate = Donut.Dough( name: String(localized: "Chocolate Dough", bundle: .module, comment: "Chocolate-flavored dough."), imageAssetName: "brown", flavors: FlavorProfile(salty: 1, sweet: 3, bitter: 1, sour: -1, savory: 1) ) static let sourCandy = Donut.Dough( name: String(localized: "Sour Candy", bundle: .module, comment: "Sour-candy-flavored dough."), imageAssetName: "green", flavors: FlavorProfile(salty: 1, sweet: 2, sour: 3, savory: -1) ) static let strawberry = Donut.Dough( name: String(localized: "Strawberry Dough", bundle: .module, comment: "Strawberry-flavored dough."), imageAssetName: "pink", flavors: FlavorProfile(sweet: 3, savory: 2) ) static let plain = Donut.Dough( name: String(localized: "Plain", bundle: .module, comment: "Plain donut dough."), imageAssetName: "plain", flavors: FlavorProfile(salty: 1, sweet: 1, bitter: 1, savory: 2) ) static let powdered = Donut.Dough( name: String(localized: "Powdered Dough", bundle: .module, comment: "Powdered donut dough."), imageAssetName: "white", flavors: FlavorProfile(salty: -1, sweet: 4, savory: 1) ) static let lemonade = Donut.Dough( name: String(localized: "Lemonade", bundle: .module, comment: "Lemonade-flavored dough."), imageAssetName: "yellow", flavors: FlavorProfile(salty: 1, sweet: 1, sour: 3) ) static let all = [blueberry, chocolate, sourCandy, strawberry, plain, powdered, lemonade] } ``` ## Glaze.swift ```swift /* Abstract: An extension to donut to represent the glaze. */ import SwiftUI public extension Donut { struct Glaze: Ingredient { public var name: String public var imageAssetName: String public var flavors: FlavorProfile public static let imageAssetPrefix = "glaze" } } public extension Donut.Glaze { static let blueberry = Donut.Glaze( name: String(localized: "Blueberry Spread", bundle: .module, comment: "Blueberry-flavored glaze."), imageAssetName: "blue", flavors: FlavorProfile(salty: 1, sweet: 3, sour: -1, savory: 2) ) static let chocolate = Donut.Glaze( name: String(localized: "Chocolate Glaze", bundle: .module, comment: "Chocolate-flavored glaze."), imageAssetName: "brown", flavors: FlavorProfile(salty: 1, sweet: 1, bitter: 1, savory: 2) ) static let sourCandy = Donut.Glaze( name: String(localized: "Sour Candy Glaze", bundle: .module, comment: "Sour-candy-flavored glaze."), imageAssetName: "green", flavors: FlavorProfile(bitter: 1, sour: 3, savory: -1, spicy: 2) ) static let spicy = Donut.Glaze( name: String(localized: "Spicy Spread", bundle: .module, comment: "Spicy glaze."), imageAssetName: "orange", flavors: FlavorProfile(salty: 1, sour: 1, spicy: 3) ) static let strawberry = Donut.Glaze( name: String(localized: "Strawberry Glaze", bundle: .module, comment: "Strawberry-flavored glaze."), imageAssetName: "pink", flavors: FlavorProfile(salty: 1, sweet: 2, savory: 2) ) static let lemon = Donut.Glaze( name: String(localized: "Lemon Spread", bundle: .module, comment: "Lemon-flavored glaze."), imageAssetName: "yellow", flavors: FlavorProfile(sweet: 1, sour: 3, spicy: 1) ) static let rainbow = Donut.Glaze( name: String(localized: "Rainbow Glaze", bundle: .module, comment: "Rainbow-colored glaze."), imageAssetName: "rainbow", flavors: FlavorProfile(salty: 2, sweet: 2, spicy: 1) ) static let all = [blueberry, chocolate, sourCandy, spicy, strawberry, lemon, rainbow] } ``` ## Ingredient.swift ```swift /* Abstract: The ingredient model object. */ import SwiftUI public protocol Ingredient: Identifiable, Hashable { var id: String { get } var name: String { get } var flavors: FlavorProfile { get } var imageAssetName: String { get } static var imageAssetPrefix: String { get } } public extension Ingredient { var id: String { "(Self.imageAssetPrefix)/(name)" } } public extension Ingredient { func image(thumbnail: Bool) -> Image { Image("(Self.imageAssetPrefix)/(imageAssetName)-(thumbnail ? "thumb" : "full")", bundle: .module) } } ``` ## Topping.swift ```swift /* Abstract: An extension to donut to represent the topping. */ import SwiftUI public extension Donut { struct Topping: Ingredient { public var name: String public var imageAssetName: String public var flavors: FlavorProfile public static let imageAssetPrefix = "topping" } } public extension Donut.Topping { static var all: [Donut.Topping] { other + lattices + lines + drizzles } static let other = [powderedSugar, sprinkles, starSprinkles] static let powderedSugar = Donut.Topping( name: String(localized: "Powdered Sugar", bundle: .module, comment: "Finely ground sugar to decorate or add texture."), imageAssetName: "powdersugar", flavors: FlavorProfile(salty: 1, sweet: 4) ) static let sprinkles = Donut.Topping( name: String(localized: "Sprinkles", bundle: .module, comment: "Small pieces of confectionery to decorate or add texture."), imageAssetName: "sprinkles", flavors: FlavorProfile(sweet: 3, savory: 2) ) static let starSprinkles = Donut.Topping( name: String(localized: "Star Sprinkles", bundle: .module, comment: "Star-shaped pieces of confectionery to decorate or add texture."), imageAssetName: "sprinkles-stars", flavors: FlavorProfile(sweet: 3, savory: 2) ) } // MARK: - Lattice public extension Donut.Topping { static let lattices = [blueberryLattice, chocolateLattice, sourAppleLattice, spicySauceLattice, strawberryLattice, sugarLattice, lemonLattice] static let blueberryLattice = Donut.Topping( name: String(localized: "Blueberry Lattice", bundle: .module, comment: "Blueberry-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-blue", flavors: FlavorProfile(salty: 1, sweet: 2, bitter: 1, sour: -1, savory: 2) ) static let chocolateLattice = Donut.Topping( name: String(localized: "Chocolate Lattice", bundle: .module, comment: "Chocolate-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-brown", flavors: FlavorProfile(salty: 2, sweet: 1, bitter: 2) ) static let sourAppleLattice = Donut.Topping( name: String(localized: "Sour Apple Lattice", bundle: .module, comment: "Sour-apple-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-green", flavors: FlavorProfile(sweet: 1, sour: 3, savory: -1, spicy: 2) ) static let spicySauceLattice = Donut.Topping( name: String(localized: "Spicy Sauce Lattice", bundle: .module, comment: "Spicy-sauce-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-orange", flavors: FlavorProfile(salty: 1, savory: 1, spicy: 3) ) static let strawberryLattice = Donut.Topping( name: String(localized: "Strawberry Lattice", bundle: .module, comment: "Strawberry-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-pink", flavors: FlavorProfile(salty: 1, sweet: 2, savory: 2) ) static let sugarLattice = Donut.Topping( name: String(localized: "Sugar Lattice", bundle: .module, comment: "Sugar-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-white", flavors: FlavorProfile(salty: 2, sweet: 3) ) static let lemonLattice = Donut.Topping( name: String(localized: "Lemon Lattice", bundle: .module, comment: "Lemon-flavored icing in a criss-cross pattern."), imageAssetName: "crisscross-yellow", flavors: FlavorProfile(bitter: 2, sour: 2, spicy: 1) ) } // MARK: - Lines public extension Donut.Topping { static let lines = [blueberryLines, chocolateLines, sourAppleLines, spicySauceLines, strawberryLines, sugarLines, lemonLines] static let blueberryLines = Donut.Topping( name: String(localized: "Blueberry Lines", bundle: .module, comment: "Blueberry-flavored icing in parallel lines."), imageAssetName: "crisscross-blue", flavors: FlavorProfile(salty: 1, sweet: 2, bitter: 1, sour: -1, savory: 2) ) static let chocolateLines = Donut.Topping( name: String(localized: "Chocolate Lines", bundle: .module, comment: "Chocolate-flavored icing in parallel lines."), imageAssetName: "straight-brown", flavors: FlavorProfile(salty: 2, sweet: 1, bitter: 2) ) static let sourAppleLines = Donut.Topping( name: String(localized: "Sour Apple Lines", bundle: .module, comment: "Sour-apple-flavored icing in parallel lines."), imageAssetName: "straight-green", flavors: FlavorProfile(sweet: 1, sour: 3, savory: -1, spicy: 2) ) static let spicySauceLines = Donut.Topping( name: String(localized: "Spicy Sauce Lines", bundle: .module, comment: "Spicy-sauce-flavored icing in parallel lines."), imageAssetName: "straight-orange", flavors: FlavorProfile(salty: 1, savory: 1, spicy: 3) ) static let strawberryLines = Donut.Topping( name: String(localized: "Strawberry Lines", bundle: .module, comment: "Strawberry-flavored icing in parallel lines."), imageAssetName: "straight-pink", flavors: FlavorProfile(salty: 1, sweet: 2, savory: 2) ) static let sugarLines = Donut.Topping( name: String(localized: "Sugar Lines", bundle: .module, comment: "Sugar-flavored icing in parallel lines."), imageAssetName: "straight-white", flavors: FlavorProfile(salty: 2, sweet: 3) ) static let lemonLines = Donut.Topping( name: String(localized: "Lemon Lines", bundle: .module, comment: "Lemon-flavored icing in parallel lines."), imageAssetName: "straight-yellow", flavors: FlavorProfile(bitter: 2, sour: 2, spicy: 1) ) } // MARK: - Drizzle public extension Donut.Topping { static let drizzles = [blueberryDrizzle, chocolateDrizzle, sourAppleDrizzle, spicySauceDrizzle, strawberryDrizzle, sugarDrizzle, lemonDrizzle] static let blueberryDrizzle = Donut.Topping( name: String(localized: "Blueberry Drizzle", bundle: .module, comment: "Blueberry-flavored icing drizzled over the donut."), imageAssetName: "zigzag-blue", flavors: FlavorProfile(salty: 1, sweet: 2, bitter: 1, sour: -1, savory: 2) ) static let chocolateDrizzle = Donut.Topping( name: String(localized: "Chocolate Drizzle", bundle: .module, comment: "Chocolate-flavored icing drizzled over the donut."), imageAssetName: "zigzag-brown", flavors: FlavorProfile(salty: 2, sweet: 1, bitter: 2) ) static let sourAppleDrizzle = Donut.Topping( name: String(localized: "Sour Apple Drizzle", bundle: .module, comment: "Sour-apple-flavored icing drizzled over the donut."), imageAssetName: "zigzag-green", flavors: FlavorProfile(sweet: 1, sour: 3, savory: -1, spicy: 2) ) static let spicySauceDrizzle = Donut.Topping( name: String(localized: "Spicy Sauce Drizzle", bundle: .module, comment: "Spicy-sauce-flavored icing drizzled over the donut."), imageAssetName: "zigzag-orange", flavors: FlavorProfile(salty: 1, savory: 1, spicy: 3) ) static let strawberryDrizzle = Donut.Topping( name: String(localized: "Strawberry Drizzle", bundle: .module, comment: "Strawberry-flavored icing drizzled over the donut."), imageAssetName: "zigzag-pink", flavors: FlavorProfile(salty: 1, sweet: 2, savory: 2) ) static let sugarDrizzle = Donut.Topping( name: String(localized: "Sugar Drizzle", bundle: .module, comment: "Sugar-flavored icing drizzled over the donut."), imageAssetName: "zigzag-white", flavors: FlavorProfile(salty: 2, sweet: 3) ) static let lemonDrizzle = Donut.Topping( name: String(localized: "Lemon Drizzle", bundle: .module, comment: "Lemon-flavored icing drizzled over the donut."), imageAssetName: "zigzag-yellow", flavors: FlavorProfile(bitter: 2, sour: 2, spicy: 1) ) } ``` ## Images.swift ```swift /* Abstract: Image extension to integrate the custom flavor symbols. */ import SwiftUI public extension Image { static var donutSymbol: Image { Image("donut", bundle: .module) } static func flavorSymbol(_ flavor: Flavor) -> Image { switch flavor { case .salty: return Image("salty", bundle: .module) case .sweet: return Image("sweet", bundle: .module) case .bitter: return Image("bitter", bundle: .module) case .sour: return Image("sour", bundle: .module) case .savory: return Image(systemName: "face.smiling") case .spicy: return Image("spicy", bundle: .module) } } } ``` ## Interpolation.swift ```swift /* Abstract: Helper extension to calculate animation progress and timing. */ import Foundation public extension ClosedRange where Bound: BinaryFloatingPoint { /// Returns a value between this range's lower and upper bounds, valued by a percentage between the two. /// - Parameters: /// - percent: The percentage between lower and upper bound. /// - clamped: Ignores values outside `0...1`, defaults to `true`. /// - Returns: A value between lower and upper bound. func value(percent: Bound, clamped: Bool = true) -> Bound { var percent = percent if clamped { percent = Swift.min(Swift.max(percent, 0), 1) } return (1 - percent) * lowerBound + percent * upperBound } /// Returns the percentage of `value` as it lays between this bound's lower and upper bounds. /// - Parameters: /// - value: A value between this range's lower and upper bounds. /// - clamped:Clamps the result between `0...1`, defaults to `true`. /// - Returns: A value between 0 and 1. func percent(for value: Bound, clamped: Bool = true) -> Bound { var result = (value - lowerBound) / (upperBound - value) if clamped { result = Swift.min(Swift.max(result, 0), 1) } return result } } public extension BinaryFloatingPoint { /// Returns a value that smoothly ramps from 0 to 1, useful for animation purposes. /// /// > Important: Only call this method on a finite number. /// - Parameter clamped: Ignores values outside `0...1`, defaults to `true`. /// - Returns: A value that is easing from 0 to 1. func easeInOut(clamped: Bool = true) -> Self { assert(self.isFinite) let timing = clamped ? min(max(self, 0), 1) : self return timing * timing * (3.0 - 2.0 * timing) } /// Takes a value from 0 to 1 and returns a value that starts at 0, eases into 1, and eases back into 0. /// /// For example, the following inputs generate these outputs: /// Input | Output /// --- | --- /// `0` | `0` /// `0.25` | `0.5` /// `0.5` | `1` /// `0.75` | `0.5` /// `1` | `0` /// /// > Important: Only call this method on a finite number. /// - Parameter clamped: Ignores values outside `0...1`, defaults to `true`. /// - Returns: A value that is easing from 0 to 1 and back to 0. func symmetricEaseInOut(clamped: Bool = true) -> Self { assert(self.isFinite) let timing = clamped ? min(max(self, 0), 1) : self if timing <= 0.5 { return (timing * 2).easeInOut(clamped: clamped) } else { return (2 - (timing * 2)).easeInOut(clamped: clamped) } } /// Truncates a value by `truncation` and returns the percentage between that value and `truncation` itself. /// /// If this value is 175 and you pass 50 for the `truncation` value, this would return 0.5 as it is 50% towards the next `truncation` value. /// /// > Important: Only call this method on a finite number. /// - Parameter truncation: A truncation value that also determines the percentage. /// - Returns: A value from 0 to 1. func percent(truncation: Self) -> Self { assert(self.isFinite) assert(!truncation.isZero && truncation.isFinite) return self.truncatingRemainder(dividingBy: truncation) / truncation } /// Maps this value, assumed to be a percentage from 0 to 1, to the corresponding value between the `range`'s lower and upper bounds. /// /// If this value is 0.5 and you pass a range from 0 to 10, the result would be 5 because it's 50% between 0 and 10. /// /// > Important: Only call this method on a finite number. /// - Parameters: /// - range: A closed range. /// - clamped: Ignores values outside `0...1`, defaults to `true`. /// - Returns: A value within the range that this value maps to as a percentage. func map(to range: ClosedRange<Self>, clamped: Bool = true) -> Self { assert(self.isFinite) return range.value(percent: self, clamped: clamped) } /// Maps a value from `originalRange` into a percentage that is used to return an equivalent value in `newRange`. /// /// > Important: The value this method is called on must be a finite number. /// - Parameters: /// - originalRange: A range from which this value will be converted into a percentage /// - newRange: A range that determines the possible resulting value /// - clamped: Ignores percentages in either range that are outside `0...1`, defaults to `true` /// - Returns: A value within `newRange` that this value maps to as a percentage in `originalRange`. func remap(from originalRange: ClosedRange<Self>, to newRange: ClosedRange<Self>, clamped: Bool = true) -> Self { assert(self.isFinite) return newRange.value(percent: originalRange.percent(for: self, clamped: clamped), clamped: clamped) } func interpolate(to destination: Self, percent: Self, clamped: Bool = true) -> Self { let percent = clamped ? min(max(percent, 0), 1) : percent return (1 - percent) * self + percent * destination } } ``` ## TaskSeconds.swift ```swift /* Abstract: Helper functions to calculate time. */ import Foundation public extension UInt64 { static func secondsToNanoseconds(_ seconds: Double) -> UInt64 { UInt64(seconds * 1_000_000_000) } } ``` ## FoodTruckModel.swift ```swift /* Abstract: The food truck model. */ import SwiftUI import Combine @MainActor public class FoodTruckModel: ObservableObject { @Published public var truck = Truck() @Published public var orders: [Order] = [] @Published public var donuts = Donut.all @Published public var newDonut: Donut var dailyOrderSummaries: [City.ID: [OrderSummary]] = [:] var monthlyOrderSummaries: [City.ID: [OrderSummary]] = [:] public init() { newDonut = Donut( id: Donut.all.count, name: String(localized: "New Donut", comment: "New donut-placeholder name."), dough: .plain, glaze: .chocolate, topping: .sprinkles ) let orderGenerator = OrderGenerator(knownDonuts: donuts) orders = orderGenerator.todaysOrders() dailyOrderSummaries = Dictionary(uniqueKeysWithValues: City.all.map { city in (key: city.id, value: orderGenerator.historicalDailyOrders(since: .now, cityID: city.id)) }) monthlyOrderSummaries = Dictionary(uniqueKeysWithValues: City.all.map { city in (key: city.id, orderGenerator.historicalMonthlyOrders(since: .now, cityID: city.id)) }) Task(priority: .background) { var generator = OrderGenerator.SeededRandomGenerator(seed: 5) for _ in 0..<20 { try? await Task.sleep(nanoseconds: .secondsToNanoseconds(.random(in: 3 ... 8, using: &generator))) Task { @MainActor in withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } } } } } public func dailyOrderSummaries(cityID: City.ID) -> [OrderSummary] { guard let result = dailyOrderSummaries[cityID] else { fatalError("Unknown City ID or daily order summaries were not found for: (cityID).") } return result } public func monthlyOrderSummaries(cityID: City.ID) -> [OrderSummary] { guard let result = monthlyOrderSummaries[cityID] else { fatalError("Unknown City ID or monthly order summaries were not found for: (cityID).") } return result } public func donuts<S: Sequence>(fromIDs ids: S) -> [Donut] where S.Element == Donut.ID { ids.map { donut(id: $0) } } public func donutSales(timeframe: Timeframe) -> [DonutSales] { combinedOrderSummary(timeframe: timeframe).sales.map { (id, count) in DonutSales(donut: donut(id: id), sales: count) } } public func donuts(sortedBy sort: DonutSortOrder = .popularity(.month)) -> [Donut] { switch sort { case .popularity(let timeframe): return donutsSortedByPopularity(timeframe: timeframe) case .name: return donuts.sorted { $0.name.localizedCompare($1.name) == .orderedAscending } case .flavor(let flavor): return donuts.sorted { $0.flavors[flavor] > $1.flavors[flavor] } } } public func orderBinding(for id: Order.ID) -> Binding<Order> { Binding<Order> { guard let index = self.orders.firstIndex(where: { $0.id == id }) else { fatalError() } return self.orders[index] } set: { newValue in guard let index = self.orders.firstIndex(where: { $0.id == id }) else { fatalError() } return self.orders[index] = newValue } } public func orderSummaries(for cityID: City.ID, timeframe: Timeframe) -> [OrderSummary] { switch timeframe { case .today: return orders.map { OrderSummary(sales: $0.sales) } case .week: return Array(dailyOrderSummaries(cityID: cityID).prefix(7)) case .month: return Array(dailyOrderSummaries(cityID: cityID).prefix(30)) case .year: return monthlyOrderSummaries(cityID: cityID) } } public func combinedOrderSummary(timeframe: Timeframe) -> OrderSummary { switch timeframe { case .today: return orders.reduce(into: .empty) { partialResult, order in partialResult.formUnion(order) } case .week: return dailyOrderSummaries.values.reduce(into: .empty) { partialResult, summaries in summaries.prefix(7).forEach { day in partialResult.formUnion(day) } } case .month: return dailyOrderSummaries.values.reduce(into: .empty) { partialResult, summaries in summaries.prefix(30).forEach { day in partialResult.formUnion(day) } } case .year: return monthlyOrderSummaries.values.reduce(into: .empty) { partialResult, summaries in summaries.forEach { month in partialResult.formUnion(month) } } } } func donutsSortedByPopularity(timeframe: Timeframe) -> [Donut] { let result = combinedOrderSummary(timeframe: timeframe).sales .sorted { if $0.value > $1.value { return true } else if $0.value == $1.value { return $0.key < $1.key } else { return false } } .map { donut(id: $0.key) } return result } public func donut(id: Donut.ID) -> Donut { donuts[id] } public func donutBinding(id: Donut.ID) -> Binding<Donut> { Binding<Donut> { self.donuts[id] } set: { newValue in self.donuts[id] = newValue } } public func updateDonut(id: Donut.ID, to newValue: Donut) { donutBinding(id: id).wrappedValue = newValue } public func markOrderAsCompleted(id: Order.ID) { guard let index = orders.firstIndex(where: { $0.id == id }) else { return } orders[index].status = .completed } public var incompleteOrders: [Order] { orders.filter { $0.status != .completed } } } public enum DonutSortOrder: Hashable { case popularity(Timeframe) case name case flavor(Flavor) } public enum Timeframe: String, Hashable, CaseIterable, Sendable { case today case week case month case year } public extension FoodTruckModel { static let preview = FoodTruckModel() } ``` ## Order.swift ```swift /* Abstract: The order model. */ import Foundation import SwiftUI public struct Order: Identifiable, Equatable { public var id: String // order public var status: OrderStatus public var donuts: [Donut] public var sales: [Donut.ID: Int] public var grandTotal: Decimal // location public var city: City.ID public var parkingSpot: ParkingSpot.ID // metadata public var creationDate: Date public var completionDate: Date? public var temperature: Measurement<UnitTemperature> public var wasRaining: Bool public init( id: String, status: OrderStatus, donuts: [Donut], sales: [Donut.ID: Int], grandTotal: Decimal, city: City.ID, parkingSpot: ParkingSpot.ID, creationDate: Date, completionDate: Date?, temperature: Measurement<UnitTemperature>, wasRaining: Bool ) { self.id = id self.status = status self.donuts = donuts self.sales = sales self.grandTotal = grandTotal self.city = city self.parkingSpot = parkingSpot self.creationDate = creationDate self.completionDate = completionDate self.temperature = temperature self.wasRaining = wasRaining } public var duration: TimeInterval? { guard let completionDate = completionDate else { return nil } return completionDate.timeIntervalSince(creationDate) } public var totalSales: Int { sales.map(\.value).reduce(0, +) } public mutating func markAsComplete() { if case .completed = status { return } self.completionDate = .now self.status = .completed } public mutating func markAsNextStep(completion: (_ newStatus: OrderStatus) -> Void) { switch status { case .placed: // Next step is to prepare. self.status = .preparing completion(self.status) case .preparing: // Next step is to complete the order. self.status = .completed completion(self.status) default: // completion(self.status) return } } public mutating func markAsPreparing() { if case .preparing = status { return } self.status = .preparing } public var isPreparing: Bool { if case .preparing = status { return true } return false } public var isComplete: Bool { if case .completed = status { return true } return false } public var formattedDate: String { let date: String = { if Calendar.current.isDateInToday(creationDate) { return String(localized: "Today") } else if Calendar.current.isDateInYesterday(creationDate) { return String(localized: "Yesterday") } else { return creationDate.formatted(date: .numeric, time: .omitted) } }() let time = creationDate.formatted(date: .omitted, time: .shortened) return "(date), (time)" } public func matches(searchText: String) -> Bool { if id.localizedCaseInsensitiveContains(searchText) { return true } // Search donuts... return false } } extension Order { public static let preview = Order( id: String(localized: "Order#(1203)"), status: .ready, donuts: [.classic], sales: [Donut.classic.id: 1], grandTotal: 4.78, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) public static let preview2 = Order( id: String(localized: "Order#(1204)"), status: .ready, donuts: [.picnicBasket, .blackRaspberry], sales: [Donut.picnicBasket.id: 2, Donut.blackRaspberry.id: 1], grandTotal: 4.78, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) public static let preview3 = Order( id: String(localized: "Order#(1205)"), status: .ready, donuts: [.classic], sales: [Donut.classic.id: 1], grandTotal: 4.78, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) public static let preview4 = Order( id: String(localized: "Order#(1206)"), status: .ready, donuts: [.fireZest, .superLemon, .daytime], sales: [Donut.fireZest.id: 1, Donut.superLemon.id: 1, Donut.daytime.id: 1], grandTotal: 4.78, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) public static let previewArray = [preview, preview2, preview3, preview4] } public enum OrderStatus: Int, Codable, Comparable { case placed case preparing case ready case completed public var title: String { switch self { case .placed: return String(localized: "Placed", bundle: .module, comment: "Order status.") case .preparing: return String(localized: "Preparing", bundle: .module, comment: "Order status.") case .ready: return String(localized: "Ready", bundle: .module, comment: "Order status.") case .completed: return String(localized: "Completed", bundle: .module, comment: "Order status.") } } public var buttonTitle: String { switch self { case .placed: return String(localized: "Prepare", bundle: .module, comment: "Order next step.") case .preparing: return String(localized: "Ready", bundle: .module, comment: "Order next step.") case .ready: return String(localized: "Complete", bundle: .module, comment: "Order next step.") case .completed: return String(localized: "Complete", bundle: .module, comment: "Order next step.") } } public var iconSystemName: String { switch self { case .placed: return "paperplane" case .preparing: return "timer" case .ready: return "checkmark.circle" case .completed: return "shippingbox" } } public var label: some View { Label(title, systemImage: iconSystemName) } public static func < (lhs: OrderStatus, rhs: OrderStatus) -> Bool { lhs.rawValue < rhs.rawValue } } ``` ## OrderGenerator.swift ```swift /* Abstract: The order generator that simulates order coming in. */ import Foundation // A value closer to 1.0 dramatically reduces how many sales the next donut sells when sorted by popularity. private let exponentialDonutCountFalloff: Double = 0.15 private let mostPopularDonutCountPerDayCount = 80.0 ... 120.0 struct OrderGenerator { var knownDonuts: [Donut] struct RandomInfo { var multiplier: Double var seed: Int } var seeds: [City.ID: RandomInfo] = [ City.cupertino.id: RandomInfo(multiplier: 0.5, seed: 1), City.sanFrancisco.id: RandomInfo(multiplier: 1, seed: 2), City.london.id: RandomInfo(multiplier: 0.75, seed: 3) ] func todaysOrders() -> [Order] { // Generate current orders for today let startingDate = Date.now var generator = SeededRandomGenerator(seed: 1) var previousOrderTime = startingDate.addingTimeInterval(-60 * 4) let totalOrders = 24 return (0 ..< totalOrders).map { index in previousOrderTime -= .random(in: 60 ..< 180, using: &generator) var order = generateOrder(number: totalOrders - index, date: previousOrderTime, generator: &generator) let isReady = index > 8 order.status = isReady ? .ready : .placed order.completionDate = isReady ? min(previousOrderTime + (14 * 60), Date.now) : nil return order } } func generateOrder(number: Int, date: Date) -> Order { var generator = SystemRandomNumberGenerator() return generateOrder(number: number, date: date, generator: &generator) } func generateOrder(number: Int, date: Date, generator: inout some RandomNumberGenerator) -> Order { let donuts = knownDonuts.shuffled(using: &generator).prefix(.random(in: 1 ... 5, using: &generator)) let sales: [Donut.ID: Int] = Dictionary(uniqueKeysWithValues: donuts.map { (key: $0.id, value: Int.random(in: 1 ... 5, using: &generator)) }) let totalSales = sales.map(\.value).reduce(0, +) return Order( id: String(localized: "Order") + String(localized: ("#(12)(number, specifier: "%02d")")), status: .placed, donuts: Array(donuts), sales: sales, grandTotal: Decimal(totalSales) * 5.78, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: date, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) } func historicalDailyOrders(since date: Date, cityID: City.ID) -> [OrderSummary] { guard let randomInfo = seeds[cityID] else { fatalError("No random info found for City ID (cityID)") } var generator = SeededRandomGenerator(seed: randomInfo.seed) var previousSales: [Donut.ID: Int]? let donuts = knownDonuts.shuffled(using: &generator) return Array((1...60).reversed().map { (daysAgo: Int) in let startDate = Calendar.current.startOfDay(for: .now) let day = Calendar.current.date(byAdding: DateComponents(day: -daysAgo), to: startDate)! let dayMultiplier = Calendar.current.isDateInWeekend(day) ? 1.25 : 1 let orderCount = Double.random(in: mostPopularDonutCountPerDayCount, using: &generator) let maxDonutCount = orderCount * .random(in: 0.75 ... 1.1, using: &generator) var sales: [Donut.ID: Int] = Dictionary(uniqueKeysWithValues: donuts.enumerated().map { offset, donut in // This value starts at 1 for the most popular donut and dramatically decreases towards 0 by the time // we reach the least popular donut. let percent: Double = 1 - pow(Double(offset) / Double(knownDonuts.count), exponentialDonutCountFalloff) // To make the data more interesting, we throw in a bit of randomness to make it not perfectly match an // exponential falloff. let variance: Double = .random(in: 0.9...1.0, using: &generator) let result = Int(maxDonutCount * percent * variance * randomInfo.multiplier * dayMultiplier) return (key: donut.id, value: max(result, 0)) }) if let previousSales = previousSales { for (donutID, count) in sales { if let previousSaleCount = previousSales[donutID] { sales[donutID] = Int(Double(count).interpolate(to: Double(previousSaleCount), percent: 0.5)) } } } previousSales = sales return OrderSummary(sales: sales) }) } func historicalMonthlyOrders(since date: Date, cityID: City.ID) -> [OrderSummary] { guard let randomInfo = seeds[cityID] else { fatalError("No random info found for City ID (cityID)") } var generator = SeededRandomGenerator(seed: randomInfo.seed) var previousSales: [Donut.ID: Int]? let donuts = knownDonuts.shuffled(using: &generator) return Array((0...12).reversed().map { monthsAgo in let orderCount = Double.random(in: mostPopularDonutCountPerDayCount, using: &generator) * 30 let maxDonutCount = orderCount * .random(in: 0.75 ... 1.1, using: &generator) var sales: [Donut.ID: Int] = Dictionary(uniqueKeysWithValues: donuts.enumerated().map { offset, donut in // This value starts at 1 for the most popular donut and quickly decreases towards 0 by the time we reach the least popular donut. let percent: Double = 1 - pow(Double(offset) / Double(knownDonuts.count), exponentialDonutCountFalloff) // To make the data more interesting, we throw in a bit of randomness to make it not perfectly match an exponential falloff. let variance: Double = .random(in: 0.9...1.0, using: &generator) let result = Int(maxDonutCount * percent * variance * randomInfo.multiplier) return (key: donut.id, value: max(result, 0)) }) if let previousSales = previousSales { for (donutID, count) in sales { if let previousSaleCount = previousSales[donutID] { sales[donutID] = Int(Double(count).interpolate(to: Double(previousSaleCount), percent: 0.25)) } } } previousSales = sales return OrderSummary(sales: sales) }) } struct SeededRandomGenerator: RandomNumberGenerator { init(seed: Int) { srand48(seed) } func next() -> UInt64 { UInt64(drand48() * Double(UInt64.max)) } } } ``` ## OrderSummary.swift ```swift /* Abstract: The order summary model. */ import Foundation public struct OrderSummary { public var sales: [Donut.ID: Int] public var totalSales: Int public init(sales: [Donut.ID: Int]) { self.sales = sales self.totalSales = sales.map(\.value).reduce(0, +) } public func union(_ other: OrderSummary) -> Self { var copy = self for donutID in Set(copy.sales.keys).union(Set(other.sales.keys)) { copy.sales[donutID, default: 0] += other.sales[donutID, default: 0] } copy.totalSales += other.totalSales return copy } public mutating func formUnion(_ other: OrderSummary) { self = union(other) } public func union(_ order: Order) -> Self { var copy = self for donutID in Set(copy.sales.keys).union(Set(order.sales.keys)) { copy.sales[donutID, default: 0] += order.sales[donutID, default: 0] } copy.totalSales += order.totalSales return copy } public mutating func formUnion(_ order: Order) { self = union(order) } public static let empty = OrderSummary(sales: [:]) } ``` ## StoreActor.swift ```swift /* Abstract: A concurrent interface to StoreKit. */ import Foundation import StoreKit @globalActor public actor StoreActor { public static let socialFeedMonthlyID = "socialfeedplus.monthly" public static let socialFeedYearlyID = "socialfeedplus.yearly" public static let annualHistoryID = "feature.annualhistory" static let subscriptionIDs: Set<String> = [ socialFeedMonthlyID, socialFeedYearlyID ] static let allProductIDs: Set<String> = { var ids = subscriptionIDs ids.insert(annualHistoryID) return ids }() public static let shared = StoreActor() private var loadedProducts: [String: Product] = [:] private var lastLoadError: Error? private var productLoadingTask: Task<Void, Never>? private var transactionUpdatesTask: Task<Void, Never>? private var statusUpdatesTask: Task<Void, Never>? private var storefrontUpdatesTask: Task<Void, Never>? public nonisolated let productController: StoreProductController public nonisolated let subscriptionController: StoreSubscriptionController init() { self.productController = StoreProductController(identifiedBy: Self.annualHistoryID) self.subscriptionController = StoreSubscriptionController(productIDs: Array(Self.subscriptionIDs)) Task(priority: .background) { await self.setupListenerTasksIfNecessary() await self.loadProducts() } } public func product(identifiedBy productID: String) async -> Product? { await waitUntilProductsLoaded() return loadedProducts[productID] } private func setupListenerTasksIfNecessary() { if transactionUpdatesTask == nil { transactionUpdatesTask = Task(priority: .background) { for await update in StoreKit.Transaction.updates { await self.handle(transaction: update) } } } if statusUpdatesTask == nil { statusUpdatesTask = Task(priority: .background) { for await update in Product.SubscriptionInfo.Status.updates { await subscriptionController.handle(update: update) } } } if storefrontUpdatesTask == nil { storefrontUpdatesTask = Task(priority: .background) { for await update in Storefront.updates { self.handle(storefrontUpdate: update) } } } } private func waitUntilProductsLoaded() async { if let task = productLoadingTask { await task.value } // You load all the products at once, so you can skip this if the // dictionary is empty. else if loadedProducts.isEmpty { let newTask = Task { await loadProducts() } productLoadingTask = newTask await newTask.value } } private func loadProducts() async { do { let products = try await Product.products(for: Self.allProductIDs) try Task.checkCancellation() print("Loaded (products.count) products") loadedProducts = products.reduce(into: [:]) { $0[$1.id] = $1 } let premiumProduct = loadedProducts[Self.annualHistoryID] Task(priority: .utility) { @MainActor in self.productController.product = premiumProduct self.subscriptionController.subscriptions = products .compactMap { Subscription(subscription: $0) } // Now that you have loaded the products, have the subscription // controller update the entitlement based on the group ID. await self.subscriptionController.updateEntitlement() } } catch { print("Failed to get in-app products: (error)") lastLoadError = error } productLoadingTask = nil } private func handle(transaction: VerificationResult<StoreKit.Transaction>) async { guard case .verified(let transaction) = transaction else { print("Received unverified transaction: (transaction)") return } // If you have a subscription, call checkEntitlement() which gets the // full status instead. if transaction.productType == .autoRenewable { await subscriptionController.updateEntitlement() } else if transaction.productID == Self.annualHistoryID { await productController.set(isEntitled: !transaction.isRevoked) } await transaction.finish() } private func handle(storefrontUpdate newStorefront: Storefront) { print("Storefront changed to (newStorefront)") // Cancel existing loading task if necessary. if let task = productLoadingTask { task.cancel() } // Load products again. productLoadingTask = Task(priority: .utility) { await self.loadProducts() } } } public extension StoreKit.Transaction { var isRevoked: Bool { // The revocation date is never in the future. revocationDate != nil } } ``` ## StoreMessagesManager.swift ```swift /* Abstract: A class that manages and displays StoreKit messages. */ #if os(iOS) import Foundation import StoreKit import SwiftUI @MainActor public final class StoreMessagesManager { private var pendingMessages: [Message] = [] private var updatesTask: Task<Void, Never>? public static let shared = StoreMessagesManager() public var sensitiveViewIsPresented = false { didSet { handlePendingMessages() } } public var displayAction: DisplayMessageAction? { didSet { handlePendingMessages() } } private init() { self.updatesTask = Task.detached(priority: .background) { await self.updatesLoop() } } deinit { updatesTask?.cancel() } private func updatesLoop() async { for await message in Message.messages { if sensitiveViewIsPresented == false, let action = displayAction { display(message: message, with: action) } else { pendingMessages.append(message) } } } private func handlePendingMessages() { if sensitiveViewIsPresented == false, let action = displayAction { let pendingMessages = self.pendingMessages self.pendingMessages = [] for message in pendingMessages { display(message: message, with: action) } } } private func display(message: Message, with display: DisplayMessageAction) { do { try display(message) } catch { print("Failed to display message: (error)") } } } public struct StoreMessagesDeferredPreferenceKey: PreferenceKey { public static let defaultValue = false public static func reduce(value: inout Bool, nextValue: () -> Bool) { value = value || nextValue() } } private struct StoreMessagesDeferredModifier: ViewModifier { let areDeferred: Bool func body(content: Content) -> some View { content.preference(key: StoreMessagesDeferredPreferenceKey.self, value: areDeferred) } } public extension View { func storeMessagesDeferred(_ storeMessagesDeferred: Bool) -> some View { self.modifier(StoreMessagesDeferredModifier(areDeferred: storeMessagesDeferred)) } } #endif // os(iOS) ``` ## StoreProductController.swift ```swift /* Abstract: A class that interacts with StoreKit products. */ import Foundation import StoreKit import Combine @MainActor public final class StoreProductController: ObservableObject { @Published public internal(set) var product: Product? @Published public private(set) var isEntitled: Bool = false @Published public private(set) var purchaseError: Error? private let productID: String internal nonisolated init(identifiedBy productID: String) { self.productID = productID Task(priority: .background) { await self.updateEntitlement() } } public func purchase() async { guard let product = product else { print("Product has not loaded yet") return } do { let result = try await product.purchase() switch result { case .success(let verificationResult): let transaction = try verificationResult.payloadValue self.isEntitled = true await transaction.finish() case .pending: print("Purchase pending user action") case .userCancelled: print("User cancelled purchase") @unknown default: print("Unknown result: (result)") } } catch { purchaseError = error } } internal func set(isEntitled: Bool) { self.isEntitled = isEntitled } private func updateEntitlement() async { switch await StoreKit.Transaction.currentEntitlement(for: productID) { case .verified: isEntitled = true case .unverified(_, let error): print("Unverified entitlement for (productID): (error)") fallthrough case .none: isEntitled = false } } } ``` ## StoreSubscriptionController.swift ```swift /* Abstract: A class that manages StoreKit subscriptions. */ import Foundation import StoreKit import Combine @MainActor public final class StoreSubscriptionController: ObservableObject { @Published public internal(set) var subscriptions: [Subscription] = [] @Published public private(set) var entitledSubscriptionID: String? @Published public private(set) var autoRenewPreference: String? @Published public private(set) var purchaseError: (any LocalizedError)? @Published public private(set) var expirationDate: Date? private let productIDs: [String] private var groupID: String? { subscriptions.first?.subscriptionGroupID } public var entitledSubscription: Subscription? { subscriptions.first { $0.id == entitledSubscriptionID } } public var nextSubscription: Subscription? { subscriptions.first { $0.id == autoRenewPreference } } internal nonisolated init(productIDs: [String]) { self.productIDs = productIDs Task { @MainActor in await self.updateEntitlement() } } public enum PurchaseFinishedAction { case dismissStore case noAction case displayError } public func purchase(option subscription: Subscription) async -> PurchaseFinishedAction { let action: PurchaseFinishedAction do { let result = try await subscription.product.purchase() switch result { case .success(let verificationResult): let transaction = try verificationResult.payloadValue entitledSubscriptionID = transaction.productID autoRenewPreference = transaction.productID expirationDate = transaction.expirationDate await transaction.finish() action = .dismissStore case .pending: print("Purchase pending user action") action = .noAction case .userCancelled: print("User cancelled purchase") action = .noAction @unknown default: print("Unknown result: (result)") action = .noAction } } catch let error as LocalizedError { purchaseError = error action = .displayError } catch { print("Purchase failed: (error)") action = .noAction } // Check status again. await updateEntitlement() return action } internal func handle(update status: Product.SubscriptionInfo.Status) { guard case .verified(let transaction) = status.transaction, case .verified(let renewalInfo) = status.renewalInfo else { print(""" Unverified entitlement for \ (status.transaction.unsafePayloadValue.productID) """) return } if status.state == .subscribed || status.state == .inGracePeriod { entitledSubscriptionID = renewalInfo.currentProductID autoRenewPreference = renewalInfo.autoRenewPreference expirationDate = transaction.expirationDate } else { entitledSubscriptionID = nil autoRenewPreference = renewalInfo.autoRenewPreference } } internal func updateEntitlement() async { // Start with nil. entitledSubscriptionID = nil if let groupID = groupID { await updateEntitlement(groupID: groupID) } else { await updateEntitlementWithProductIDs() } } /// Update the entitlement state based on the status API. /// - Parameter groupID: The groupID to check status for. func updateEntitlement(groupID: String) async { guard let statuses = try? await Product.SubscriptionInfo.status(for: groupID) else { return } for status in statuses { guard case .verified(let transaction) = status.transaction, case .verified(let renewalInfo) = status.renewalInfo else { print(""" Unverified entitlement for \ (status.transaction.unsafePayloadValue.productID) """) continue } if status.state == .subscribed || status.state == .inGracePeriod { entitledSubscriptionID = renewalInfo.currentProductID autoRenewPreference = renewalInfo.autoRenewPreference expirationDate = transaction.expirationDate } } } /// Update the entitlement based on the current entitlement API. Use this if there is no network /// connection and the subscription group ID is not accessible. private func updateEntitlementWithProductIDs() async { for productID in productIDs { guard let entitlement = await StoreKit.Transaction.currentEntitlement(for: productID) else { continue } guard case .verified(let transaction) = entitlement else { print(""" Unverified entitlement for \ (entitlement.unsafePayloadValue.productID) """) continue } entitledSubscriptionID = transaction.productID break } } } ``` ## Subscription.swift ```swift /* Abstract: A StoreKit subscription model. */ import Foundation import StoreKit @dynamicMemberLookup public struct Subscription: Identifiable, Equatable { public let product: Product public var subscriptionInfo: Product.SubscriptionInfo { product.subscription.unsafelyUnwrapped } public var id: String { product.id } init?(subscription: Product) { guard subscription.subscription != nil else { return nil } self.product = subscription } public subscript<T>(dynamicMember keyPath: KeyPath<Product, T>) -> T { product[keyPath: keyPath] } public subscript<T>(dynamicMember keyPath: KeyPath<Product.SubscriptionInfo, T>) -> T { subscriptionInfo[keyPath: keyPath] } public var priceText: String { "(self.displayPrice)/(self.subscriptionPeriod.unit.localizedDescription.lowercased())" } } public struct SubscriptionSavings { public let percentSavings: Decimal public let granularPrice: Decimal public let granularPricePeriod: Product.SubscriptionPeriod.Unit public init(percentSavings: Decimal, granularPrice: Decimal, granularPricePeriod: Product.SubscriptionPeriod.Unit) { self.percentSavings = percentSavings self.granularPrice = granularPrice self.granularPricePeriod = granularPricePeriod } public var formattedPercent: String { return percentSavings.formatted(.percent.precision(.significantDigits(3))) } public func formattedPrice(for subscription: Subscription) -> String { let currency = granularPrice.formatted(subscription.priceFormatStyle) let period = granularPricePeriod.formatted(subscription.subscriptionPeriodUnitFormatStyle) return "(currency)/(period)" } } ``` ## Truck.swift ```swift /* Abstract: The Truck model. */ import Foundation public struct Truck { public var city: City = .cupertino public var location: ParkingSpot = City.cupertino.parkingSpots[0] } public extension Truck { static var preview = Truck() } ``` ## DailyDonutWidget.swift ```swift /* Abstract: The Daily Donut Widget. */ import WidgetKit import SwiftUI import FoodTruckKit struct DailyDonutWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "Daily Donut", provider: Provider()) { entry in DailyDonutWidgetView(entry: entry) } #if os(iOS) .supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge]) #elseif os(macOS) .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) #endif .configurationDisplayName("Daily Donut") .description("Showcasing the latest trending donuts.") } struct Provider: TimelineProvider { func placeholder(in context: Context) -> Entry { Entry.preview } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { completion(.preview) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { var entries: [Entry] = [] // Generate a timeline consisting of five entries an hour apart, starting from the current date. let currentDate = Date() for hourOffset in 0 ..< 5 { let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! let entry = Entry(date: entryDate, donut: Donut.all[hourOffset % Donut.all.count]) entries.append(entry) } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } } struct Entry: TimelineEntry { var date: Date var donut: Donut static let preview = Entry(date: .now, donut: .preview) } } struct DailyDonutWidgetView: View { var entry: DailyDonutWidget.Entry @Environment(\.widgetFamily) private var family var body: some View { switch family { case .systemSmall: VStack { DonutView(donut: entry.donut) Text(entry.donut.name) } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.indigo.gradient) case .systemMedium: HStack { VStack { DonutView(donut: entry.donut) Text(entry.donut.name) } Text("Trend Data...") } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.indigo.gradient) case .systemLarge: HStack { VStack { DonutView(donut: entry.donut) Text(entry.donut.name) } Text("Trend Data...") } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.indigo.gradient) case .systemExtraLarge: HStack { VStack { DonutView(donut: entry.donut) Text(entry.donut.name) } Text("Trend Data...") } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.indigo.gradient) default: Text("Unsupported!") } } } #if os(iOS) || os(macOS) struct DailyDonutWidget_Previews: PreviewProvider { static var previews: some View { DailyDonutWidgetView(entry: .preview) .previewContext(WidgetPreviewContext(family: .systemMedium)) } } #endif ``` ## OrdersWidget.swift ```swift /* Abstract: The Orders Widget. */ import WidgetKit import SwiftUI import FoodTruckKit struct OrdersWidget: Widget { static var supportedFamilies: [WidgetFamily] { var families: [WidgetFamily] = [] #if os(iOS) || os(watchOS) // Common families between iOS and watchOS families += [.accessoryRectangular, .accessoryCircular, .accessoryInline] #endif #if os(iOS) // Families specific to iOS families += [.systemSmall] #endif return families } var body: some WidgetConfiguration { StaticConfiguration(kind: "Orders", provider: Provider()) { entry in OrdersWidgetView(entry: entry) } .supportedFamilies(OrdersWidget.supportedFamilies) .configurationDisplayName("Orders") .description("Information about Food Truck's orders and daily quotas.") } struct Provider: TimelineProvider { func placeholder(in context: Context) -> Entry { Entry.preview } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { completion(.preview) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { var entries: [Entry] = [] // Generate a timeline consisting of five entries an hour apart, starting from the current date. let currentDate = Date() for hourOffset in 0 ..< 5 { let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! let entry = Entry(date: entryDate, orders: 7 + hourOffset, quota: 25) entries.append(entry) } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } } struct Entry: TimelineEntry { var date: Date var orders: Int var quota: Int static let preview = Entry(date: .now, orders: 7, quota: 13) } } struct OrdersWidgetView: View { var entry: OrdersWidget.Entry @Environment(\.widgetFamily) private var family @Environment(\.widgetRenderingMode) private var widgetRenderingMode var body: some View { switch family { #if os(iOS) case .systemSmall: ZStack { LinearGradient(gradient: Gradient.widgetAccent, startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 1, y: 1)) VStack(alignment: .leading) { Text("Orders") .font(.title) Text("(entry.orders.formatted()) out of (entry.quota.formatted())") Gauge(value: Double(entry.orders), in: 0...Double(entry.quota)) { EmptyView() } currentValueLabel: { DonutView(donut: Donut.classic) } .tint(Color.white) } .frame(maxWidth: .infinity, alignment: .leading) .foregroundColor(.white) .padding() } #endif #if os(iOS) || os(watchOS) case .accessoryCircular: Gauge(value: Double(entry.orders), in: 0...Double(entry.quota)) { Image.donutSymbol } currentValueLabel: { Text(entry.orders.formatted()) } .gaugeStyle(.accessoryCircular ) .tint(Gradient.widgetAccent) case .accessoryRectangular: VStack(alignment: .leading) { HStack(alignment: .firstTextBaseline) { Image.donutSymbol Text("Orders") } .font(.headline) .foregroundColor(.widgetAccent) .widgetAccentable() .padding(.top, 4) SegmentedGauge(value: entry.orders, total: entry.quota) { Text("(entry.orders.formatted()) out of (entry.quota.formatted())") } .tint(Color.widgetAccent) } .frame(maxWidth: .infinity, alignment: .leading) case .accessoryInline: Label { Text("(entry.orders) of (entry.quota) Orders") } icon: { Image.donutSymbol } #endif default: Text("Unsupported!") } } } struct OrdersAccessory_Previews: PreviewProvider { static var previews: some View { ForEach(OrdersWidget.supportedFamilies, id: \.rawValue) { family in OrdersWidgetView(entry: .preview) .previewContext(WidgetPreviewContext(family: family)) .previewDisplayName("Orders: (family)") } } } ``` ## ParkingSpotAccessory.swift ```swift /* Abstract: The Parking Spot Accessory View. */ import WidgetKit import SwiftUI import FoodTruckKit struct ParkingSpotAccessory: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "Parking Spot", provider: Provider()) { entry in ParkingSpotAccessoryView(entry: entry) } #if os(iOS) || os(watchOS) .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular]) #endif .configurationDisplayName("Parking Spot") .description("Information about your Food Truck's parking spot.") } struct Provider: TimelineProvider { func placeholder(in context: Context) -> Entry { Entry.preview } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { completion(.preview) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { let timeline = Timeline(entries: [Entry.preview], policy: .never) completion(timeline) } } struct Entry: TimelineEntry { var date: Date var city: City var parkingSpot: ParkingSpot static let preview = Entry(date: .now, city: .cupertino, parkingSpot: City.cupertino.parkingSpots[0]) } } struct ParkingSpotAccessoryView: View { var entry: ParkingSpotAccessory.Entry @Environment(\.widgetFamily) private var family var body: some View { switch family { #if os(iOS) || os(watchOS) case .accessoryInline: Label(entry.parkingSpot.name, systemImage: "box.truck") case .accessoryCircular: VStack { Image(systemName: "box.truck") Text("CUP") } case .accessoryRectangular: Label { Text("Parking Spot") Text(entry.parkingSpot.name) Text(entry.city.name) } icon: { Image(systemName: "box.truck") } #endif default: Text("Unsupported!") } } } struct ParkingSpotAccessory_Previews: PreviewProvider { static var previews: some View { ParkingSpotAccessoryView(entry: .preview) #if os(iOS) || os(watchOS) .previewContext(WidgetPreviewContext(family: .accessoryCircular)) #endif } } ``` ## SegmentedGauge.swift ```swift /* Abstract: A Segmented Gauge View. */ import SwiftUI public struct SegmentedGauge<Label: View>: View { public var value: Int public var total: Int @ViewBuilder public var label: () -> Label public init(value: Int, total: Int, label: @escaping () -> Label) { // Value can't go beyond total. self.value = min(value, total) // Always show at least one segment. // This is second to have it always at least show a segment. self.total = max(total, 1) self.label = label } public var body: some View { Gauge(value: Double(value), in: 0.0...Double(total), label: label) .gaugeStyle(SegmentedGaugeStyle(total: total)) } } struct SegmentedGaugeStyle: GaugeStyle { var total: Int private var metrics = Metrics() init(total: Int) { self.total = total } func makeBody(configuration: Configuration) -> some View { let value = Int(configuration.value * Double(total)) VStack(alignment: .leading, spacing: 4) { configuration.label HStack(spacing: metrics.gap) { ForEach(0..<total, id: \.self) { index in Segment(metrics, position: position(for: index, with: value, in: total)) .opacity(opacity(for: index, with: value)) } } .frame(height: metrics.height) } } func position(for index: Int, with value: Int, in total: Int) -> Segment.Position { if total <= 1 { return .single } else { switch index { case 0: return .leading case total - 1: return .trailing default: return .middle } } } func opacity(for index: Int, with value: Int) -> Double { index < value ? 1.0 : metrics.unfilledOpacity } struct Metrics { var height: CGFloat { 11.0 } var gap: CGFloat { 3.0 } var cornerRadius: CGFloat { 2.0 } var unfilledOpacity: Double { 0.35 } } struct Segment: View { enum Position { case leading case trailing case middle case single } var metrics: Metrics var position: Position @Environment(\.layoutDirection) var layoutDirection init(_ metrics: Metrics, position: Position) { self.metrics = metrics self.position = position } var body: some View { Segment(cornerRadius: metrics.cornerRadius, position: position, layoutDirection: layoutDirection) .fill(.tint) } struct Segment: Shape { var cornerRadius: CGFloat var position: Position var layoutDirection: LayoutDirection func path(in rect: CGRect) -> Path { var path = Path() let corners = corners(for: rect) // Start at middle of top edge, go clockwise, according to the wall clock. // But because positive y is down, we have to flip the argument. var point = CGPoint(x: rect.midX, y: rect.minY) path.move(to: point) // Just before start of top right corner. var radius = corners.topRight point.x = rect.maxX - radius path.addLine(to: point) // Top right corner. point.y = (rect.minY + radius) path.addArc(center: point, radius: radius, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false) // Just before bottom right corner. radius = corners.bottomRight point.x = rect.maxX point.y = rect.maxY - radius path.addLine(to: point) // Bottom right corner. point.x = rect.maxX - radius path.addArc(center: point, radius: radius, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false) // Just before bottom left corner. radius = corners.bottomLeft point.x = rect.minX + radius point.y = rect.maxY path.addLine(to: point) // Bottom left corner. point.y = rect.maxY - radius path.addArc(center: point, radius: radius, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false) // Just before top left corner. radius = corners.topLeft point.x = rect.minX point.y = rect.minY + radius path.addLine(to: point) // Top left corner. point.x = rect.minX + radius path.addArc(center: point, radius: radius, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false) // Back to top middle. point.x = rect.midX point.y = rect.minY path.addLine(to: point) return path } func corners(for rect: CGRect) -> (topRight: CGFloat, bottomRight: CGFloat, bottomLeft: CGFloat, topLeft: CGFloat) { let rectCorner = cornerRadius let capsuleCorner = rect.height / 2.0 let position: Position = { var position = self.position if layoutDirection == .rightToLeft { if position == .leading { position = .trailing } else if position == .trailing { position = .leading } } return position }() switch position { case .leading: return (rectCorner, rectCorner, capsuleCorner, capsuleCorner) case .trailing: return (capsuleCorner, capsuleCorner, rectCorner, rectCorner) case .middle: return (rectCorner, rectCorner, rectCorner, rectCorner) case .single: return (capsuleCorner, capsuleCorner, capsuleCorner, capsuleCorner) } } } } } struct SegmentedGauge_Previews: PreviewProvider { static var previews: some View { SegmentedGauge(value: 8, total: 10) { Text("8 out of 10 cats!") } .tint(.mint) .padding() // .environment(\.layoutDirection, .rightToLeft) } } ``` ## TruckActivityAttributes.swift ```swift /* Abstract: Defines the live activity attributes. */ #if canImport(ActivityKit) import Foundation import ActivityKit import FoodTruckKit struct TruckActivityAttributes: ActivityAttributes { public typealias MyActivityStatus = ContentState public struct ContentState: Codable, Hashable { var timerRange: ClosedRange<Date> } var orderID: String var order: [Donut.ID] var sales: [Donut.ID: Int] var activityName: String } #endif ``` ## TruckActivityWidget.swift ```swift /* Abstract: Defines the live activity and dynamic island. */ #if canImport(ActivityKit) import SwiftUI import WidgetKit import FoodTruckKit struct TruckActivityWidget: Widget { var body: some WidgetConfiguration { ActivityConfiguration(for: TruckActivityAttributes.self) { context in LiveActivityView(orderNumber: context.attributes.orderID, timerRange: context.state.timerRange) .widgetURL(URL(string: "foodtruck://order/(context.attributes.orderID)")) } dynamicIsland: { context in DynamicIsland { DynamicIslandExpandedRegion(.leading) { ExpandedLeadingView() } DynamicIslandExpandedRegion(.trailing, priority: 1) { ExpandedTrailingView(orderNumber: context.attributes.orderID, timerInterval: context.state.timerRange) .dynamicIsland(verticalPlacement: .belowIfTooWide) } } compactLeading: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape()) } compactTrailing: { Text(timerInterval: context.state.timerRange, countsDown: true) .monospacedDigit() .foregroundColor(Color("LightIndigo")) .frame(width: 40) } minimal: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape()) } .contentMargins(.trailing, 32, for: .expanded) .contentMargins([.leading, .top, .bottom], 6, for: .compactLeading) .contentMargins(.all, 6, for: .minimal) .widgetURL(URL(string: "foodtruck://order/(context.attributes.orderID)")) } } } struct LiveActivityView: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.isLuminanceReduced) var isLuminanceReduced var orderNumber: String var timerRange: ClosedRange<Date> var body: some View { HStack { Image("IslandExpandedIcon") .clipShape(ContainerRelativeShape()) .opacity(isLuminanceReduced ? 0.5 : 1.0) OrderInfoView(orderNumber: orderNumber) Spacer() OrderTimerView(timerRange: timerRange) } .tint(.primary) .padding([.leading, .top, .bottom]) .padding(.trailing, 32) .activityBackgroundTint(colorScheme == .light ? Color("LiveActivityBackground") : Color("AccentColorDimmed")) .activitySystemActionForegroundColor(.primary) } } struct ExpandedLeadingView: View { var body: some View { Image("IslandExpandedIcon") .clipShape(ContainerRelativeShape()) } } struct OrderInfoView: View { @Environment(\.isLuminanceReduced) var isLuminanceReduced var orderNumber: String var body: some View { VStack(alignment: .leading, spacing: 0) { Text("Order (orderNumber)") .font(.title3) .fontWeight(.semibold) .foregroundStyle(.tint) Text("6 donuts") .font(.subheadline) .fontWeight(.medium) .foregroundStyle(.secondary) .opacity(isLuminanceReduced ? 0.5 : 1.0) } } } struct OrderTimerView: View { @Environment(\.isLuminanceReduced) var isLuminanceReduced var timerRange: ClosedRange<Date> var body: some View { VStack(alignment: .trailing) { Text(timerInterval: timerRange, countsDown: true) .monospacedDigit() .multilineTextAlignment(.trailing) .frame(width: 80) .font(.title3) .fontWeight(.semibold) .foregroundStyle(.tint) Text("Remaining") .font(.subheadline) .fontWeight(.medium) .foregroundStyle(.secondary) .opacity(isLuminanceReduced ? 0.5 : 1.0) } } } struct ExpandedTrailingView: View { var orderNumber: String var timerInterval: ClosedRange<Date> var body: some View { HStack(alignment: .lastTextBaseline) { OrderInfoView(orderNumber: orderNumber) Spacer() OrderTimerView(timerRange: timerInterval) } .tint(Color("LightIndigo")) } } struct TruckActivityPreviewProvider: PreviewProvider { static let activityAttributes = TruckActivityAttributes( orderID: "1234", order: [Donut.preview.id], sales: [Donut.preview.id: 4], activityName: "activity name" ) static let state = TruckActivityAttributes.ContentState( timerRange: Date.now...Date(timeIntervalSinceNow: 30)) static var previews: some View { activityAttributes .previewContext(state, viewKind: .dynamicIsland(.compact)) .previewDisplayName("Compact") activityAttributes .previewContext(state, viewKind: .dynamicIsland(.expanded)) .previewDisplayName("Expanded") activityAttributes .previewContext(state, viewKind: .content) .previewDisplayName("Notification") activityAttributes .previewContext(state, viewKind: .dynamicIsland(.minimal)) .previewDisplayName("Minimal") } } #endif ``` ## WidgetColors.swift ```swift /* Abstract: The accents in the Widget. */ import SwiftUI extension Color { static let widgetAccent = Color("AccentColor") static let widgetAccentDimmed = Color("AccentColorDimmed") } extension Gradient { static let widgetAccent = Gradient(colors: [.widgetAccentDimmed, .widgetAccent]) } ``` ## Widgets.swift ```swift /* Abstract: The Widget entry point. */ import WidgetKit import SwiftUI @main struct Widgets: WidgetBundle { var body: some Widget { // MARK: - Live Activity Widgets #if canImport(ActivityKit) TruckActivityWidget() #endif // MARK: - Accessory Widgets #if os(iOS) || os(watchOS) OrdersWidget() ParkingSpotAccessory() #endif // MARK: - Widgets #if os(iOS) || os(macOS) DailyDonutWidget() #endif } } ``` ## AnimatableFontModifier.swift ```swift /* Abstract: A modifier that can animate a font's size changing over time. */ import SwiftUI struct AnimatableFontModifier: AnimatableModifier { var size: Double var weight: Font.Weight = .regular var design: Font.Design = .default var animatableData: Double { get { size } set { size = newValue } } func body(content: Content) -> some View { content .font(.system(size: size, weight: weight, design: design)) } } extension View { func animatableFont(size: Double, weight: Font.Weight = .regular, design: Font.Design = .default) -> some View { self.modifier(AnimatableFontModifier(size: size, weight: weight, design: design)) } } ``` ## BubbleBackground.swift ```swift /* Abstract: The bubbly background for use behind the RewardsCard and Fruta widgets. */ import SwiftUI struct BubbleBackground: View { var body: some View { ZStack { Color("bubbles-background") ZStack(alignment: .topTrailing) { BubbleView(size: 300, xOffset: 80, yOffset: -150, opacity: 0.05) BubbleView(size: 100, xOffset: 60, yOffset: 200, opacity: 0.1) BubbleView(size: 35, xOffset: -220, yOffset: 80, opacity: 0.15) BubbleView(size: 10, xOffset: -320, yOffset: 50, opacity: 0.1) BubbleView(size: 12, xOffset: -250, yOffset: 8, opacity: 0.1) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing) ZStack(alignment: .bottomLeading) { BubbleView(size: 320, xOffset: -190, yOffset: 150, opacity: 0.05) BubbleView(size: 60, xOffset: -40, yOffset: -210, opacity: 0.1) BubbleView(size: 10, xOffset: 320, yOffset: -50, opacity: 0.1) BubbleView(size: 12, xOffset: 250, yOffset: -20, opacity: 0.1) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) LinearGradient(colors: [.primary.opacity(0.25), .primary.opacity(0)], startPoint: .top, endPoint: .bottom) .blendMode(.overlay) } .frame(maxWidth: .infinity, maxHeight: .infinity) .ignoresSafeArea() .drawingGroup() } } struct RewardsBubbleBackground_Previews: PreviewProvider { static var previews: some View { Group { BubbleBackground() .frame(width: 350, height: 700) BubbleBackground() .frame(width: 800, height: 400) BubbleBackground() .frame(width: 200, height: 200) } } } ``` ## BubbleView.swift ```swift /* Abstract: A graphical bubble-like view, used behind the RewardsCard. */ import SwiftUI struct BubbleView: View { var size: Double = 30 var xOffset: Double = 0 var yOffset: Double = 0 var opacity: Double = 0.1 @State private var shimmer: Bool = .random() @State private var shimmerDelay: Double = .random(in: 0.15...0.55) @State private var float: Bool = .random() @State private var floatDelay: Double = .random(in: 0.15...0.55) var body: some View { Circle() .blendMode(.overlay) .opacity(shimmer ? opacity * 2 : opacity) .frame(width: size, height: size) .scaleEffect(shimmer ? 1.1 : 1) .offset(x: xOffset, y: yOffset) .offset(y: float ? 4 : 0) .onAppear { #if !os(macOS) withAnimation(Animation.easeInOut(duration: 4 - shimmerDelay).repeatForever().delay(shimmerDelay)) { shimmer.toggle() } withAnimation(Animation.easeInOut(duration: 8 - floatDelay).repeatForever().delay(floatDelay)) { float.toggle() } #endif } } } struct BubbleView_Previews: PreviewProvider { static var previews: some View { ZStack { ZStack { BubbleView(opacity: 0.9) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .foregroundStyle(.red) ZStack { BubbleView(opacity: 0.9) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing) .foregroundStyle(.blue) ZStack { BubbleView(size: 300, yOffset: -150) BubbleView(size: 260, xOffset: 40, yOffset: -60) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) BubbleView(size: 100, xOffset: -40, yOffset: 50) } .frame(maxWidth: .infinity, maxHeight: .infinity) } } ``` ## CardActionButton.swift ```swift /* Abstract: A squishable button that has a consistent look for use on a card */ import SwiftUI struct CardActionButton: View { var label: LocalizedStringKey var systemImage: String var action: () -> Void var body: some View { Button(action: action) { Image(systemName: systemImage) .font(Font.title.bold()) .imageScale(.large) .frame(width: 44, height: 44) .padding() .contentShape(Rectangle()) } .buttonStyle(SquishableButtonStyle(fadeOnPress: false)) .accessibility(label: Text(label)) } } struct CardActionButton_Previews: PreviewProvider { static var previews: some View { CardActionButton(label: "Close", systemImage: "xmark", action: {}) .previewLayout(.sizeThatFits) } } ``` ## CountButton.swift ```swift /* Abstract: A button for either incrementing or decrementing a binding. */ import SwiftUI // MARK: - CountButton struct CountButton: View { var mode: Mode var action: () -> Void @Environment(\.isEnabled) var isEnabled public var body: some View { Button(action: action) { Image(systemName: mode.imageName) .symbolVariant(isEnabled ? .circle.fill : .circle) .imageScale(.large) .padding() .contentShape(Rectangle()) .opacity(0.5) } .buttonStyle(.plain) } } // MARK: - CountButton.Mode extension CountButton { enum Mode { case increment case decrement var imageName: String { switch self { case .increment: return "plus" case .decrement: return "minus" } } } } // MARK: - Previews struct CountButton_Previews: PreviewProvider { static var previews: some View { Group { CountButton(mode: .increment, action: {}) CountButton(mode: .decrement, action: {}) CountButton(mode: .increment, action: {}).disabled(true) CountButton(mode: .decrement, action: {}).disabled(true) } .padding() .previewLayout(.sizeThatFits) } } ``` ## FlipView.swift ```swift /* Abstract: A view that can flip between a front and back side. */ import SwiftUI import StoreKit struct FlipView<Front: View, Back: View>: View { var visibleSide: FlipViewSide @ViewBuilder var front: Front @ViewBuilder var back: Back var body: some View { ZStack { front .modifier(FlipModifier(side: .front, visibleSide: visibleSide)) back .modifier(FlipModifier(side: .back, visibleSide: visibleSide)) } } } enum FlipViewSide { case front case back mutating func toggle() { self = self == .front ? .back : .front } } struct FlipModifier: AnimatableModifier { var side: FlipViewSide var flipProgress: Double init(side: FlipViewSide, visibleSide: FlipViewSide) { self.side = side self.flipProgress = visibleSide == .front ? 0 : 1 } public var animatableData: Double { get { flipProgress } set { flipProgress = newValue } } var visible: Bool { switch side { case .front: return flipProgress <= 0.5 case .back: return flipProgress > 0.5 } } public func body(content: Content) -> some View { ZStack { content .opacity(visible ? 1 : 0) .accessibility(hidden: !visible) } .scaleEffect(x: scale, y: 1.0) .rotation3DEffect(.degrees(flipProgress * -180), axis: (x: 0.0, y: 1.0, z: 0.0), perspective: 0.5) } var scale: CGFloat { switch side { case .front: return 1.0 case .back: return -1.0 } } } struct FlipView_Previews: PreviewProvider { static var previews: some View { FlipView(visibleSide: .front) { Text(verbatim: "Front Side") } back: { Text(verbatim: "Back Side") } } } ``` ## StepperView.swift ```swift /* Abstract: A view that offers controls that tilt the view when incrementing or decrementing a value */ import SwiftUI // MARK: - StepperView struct StepperView: View { @Binding var value: Int { didSet { tilt = value > oldValue ? 1 : -1 withAnimation(.interactiveSpring(response: 1, dampingFraction: 1)) { tilt = 0 } } } var label: LocalizedStringKey var configuration: Configuration @State private var tilt = 0.0 var body: some View { HStack { CountButton(mode: .decrement, action: decrement) .disabled(value <= configuration.minValue) Text(label) .frame(width: 150) .padding(.vertical) CountButton(mode: .increment, action: increment) .disabled(configuration.maxValue <= value) } .accessibilityRepresentation { Stepper("Smoothie Count", value: $value, in: configuration.minValue...configuration.maxValue, step: configuration.increment) } .font(Font.title2.bold()) .foregroundStyle(.primary) .background(.thinMaterial, in: Capsule()) .contentShape(Capsule()) .rotation3DEffect(.degrees(3 * tilt), axis: (x: 0, y: 1, z: 0)) } func increment() { value = min(max(value + configuration.increment, configuration.minValue), configuration.maxValue) } func decrement() { value = min(max(value - configuration.increment, configuration.minValue), configuration.maxValue) } } // MARK: - StepperView.Configuration extension StepperView { struct Configuration { var increment: Int var minValue: Int var maxValue: Int } } // MARK: - Previews struct StepperView_Previews: PreviewProvider { static var previews: some View { StepperView( value: .constant(5), label: "Stepper", configuration: StepperView.Configuration(increment: 1, minValue: 1, maxValue: 10) ) .padding() } } ``` ## FrutaApp.swift ```swift /* Abstract: The single entry point for the Fruta app on iOS and macOS. */ import SwiftUI /// - Tag: SingleAppDefinitionTag @main struct FrutaApp: App { @StateObject private var model = Model() var body: some Scene { WindowGroup { ContentView() .environmentObject(model) } .commands { SidebarCommands() SmoothieCommands(model: model) } } } ``` ## Ingredient+NutritionFacts.swift ```swift /* Abstract: An extension that allows Ingredients to look up nutrition facts for a cup's worth of its volume. */ extension Ingredient { var nutritionFact: NutritionFact? { NutritionFact.lookupFoodItem(id, forVolume: .cups(1)) } } ``` ## Ingredient+SwiftUI.swift ```swift /* Abstract: Definition of how the ingredients should appear in their thumbnail and card appearances. */ import SwiftUI // MARK: - SwiftUI extension Ingredient { /// Defines how the `Ingredient`'s title should be displayed in card mode struct CardTitle { var color = Color.black var rotation = Angle.degrees(0) var offset = CGSize.zero var blendMode = BlendMode.normal var opacity: Double = 1 var fontSize: Double = 1 } /// Defines a state for the `Ingredient` to transition from when changing between card and thumbnail struct Crop { var xOffset: Double = 0 var yOffset: Double = 0 var scale: Double = 1 var offset: CGSize { CGSize(width: xOffset, height: yOffset) } } /// The `Ingredient`'s image, useful for backgrounds or thumbnails var image: Image { Image("ingredient/(id)", label: Text(name)) .renderingMode(.original) } } // MARK: - All Recipes extension Ingredient { static let avocado = Ingredient( id: "avocado", name: String(localized: "Avocado", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .brown, offset: CGSize(width: 0, height: 20), blendMode: .plusDarker, opacity: 0.4, fontSize: 60 ) ) static let almondMilk = Ingredient( id: "almond-milk", name: String(localized: "Almond Milk", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( offset: CGSize(width: 0, height: -140), blendMode: .overlay, fontSize: 40 ), thumbnailCrop: Crop(yOffset: 0, scale: 1) ) static let banana = Ingredient( id: "banana", name: String(localized: "Banana", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( rotation: Angle.degrees(-30), offset: CGSize(width: 0, height: 0), blendMode: .overlay, fontSize: 70 ), thumbnailCrop: Crop(yOffset: 0, scale: 1) ) static let blueberry = Ingredient( id: "blueberry", name: String(localized: "Blueberry", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .white, offset: CGSize(width: 0, height: 100), opacity: 0.5, fontSize: 45 ), thumbnailCrop: Crop(yOffset: 0, scale: 2) ) static let carrot = Ingredient( id: "carrot", name: String(localized: "Carrot", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( rotation: Angle.degrees(-90), offset: CGSize(width: -120, height: 100), blendMode: .plusDarker, opacity: 0.3, fontSize: 70 ), thumbnailCrop: Crop(yOffset: 0, scale: 1.2) ) static let chocolate = Ingredient( id: "chocolate", name: String(localized: "Chocolate", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .brown, rotation: Angle.degrees(-11), offset: CGSize(width: 0, height: 10), blendMode: .plusDarker, opacity: 0.8, fontSize: 45 ), thumbnailCrop: Crop(yOffset: 0, scale: 1) ) static let coconut = Ingredient( id: "coconut", name: String(localized: "Coconut", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .brown, offset: CGSize(width: 40, height: 110), blendMode: .plusDarker, opacity: 0.8, fontSize: 36 ), thumbnailCrop: Crop(scale: 1.5) ) static let kiwi = Ingredient( id: "kiwi", name: String(localized: "Kiwi", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( offset: CGSize(width: 0, height: 0), blendMode: .overlay, fontSize: 140 ), thumbnailCrop: Crop(scale: 1.1) ) static let lemon = Ingredient( id: "lemon", name: String(localized: "Lemon", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( rotation: Angle.degrees(-9), offset: CGSize(width: 15, height: 90), blendMode: .overlay, fontSize: 80 ), thumbnailCrop: Crop(scale: 1.1) ) static let mango = Ingredient( id: "mango", name: String(localized: "Mango", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .orange, offset: CGSize(width: 0, height: 20), blendMode: .plusLighter, fontSize: 70 ) ) static let orange = Ingredient( id: "orange", name: String(localized: "Orange", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( rotation: Angle.degrees(-90), offset: CGSize(width: -130, height: -60), blendMode: .overlay, fontSize: 80 ), thumbnailCrop: Crop(yOffset: -15, scale: 2) ) static let papaya = Ingredient( id: "papaya", name: String(localized: "Papaya", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( offset: CGSize(width: -20, height: 20), blendMode: .overlay, fontSize: 70 ), thumbnailCrop: Crop(scale: 1) ) static let peanutButter = Ingredient( id: "peanut-butter", name: String(localized: "Peanut Butter", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( offset: CGSize(width: 0, height: 190), blendMode: .overlay, fontSize: 35 ), thumbnailCrop: Crop(yOffset: -20, scale: 1.2) ) static let pineapple = Ingredient( id: "pineapple", name: String(localized: "Pineapple", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .yellow, offset: CGSize(width: 0, height: 90), blendMode: .plusLighter, opacity: 0.5, fontSize: 55 ) ) static let raspberry = Ingredient( id: "raspberry", name: String(localized: "Raspberry", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .pink, blendMode: .plusLighter, fontSize: 50 ), thumbnailCrop: Crop(yOffset: 0, scale: 1.5) ) static let spinach = Ingredient( id: "spinach", name: String(localized: "Spinach", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( offset: CGSize(width: 0, height: -150), blendMode: .overlay, fontSize: 70 ), thumbnailCrop: Crop(yOffset: 0, scale: 1) ) static let strawberry = Ingredient( id: "strawberry", name: String(localized: "Strawberry", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .white, offset: CGSize(width: 35, height: -5), blendMode: .softLight, opacity: 0.7, fontSize: 30 ), thumbnailCrop: Crop(scale: 2.5), cardCrop: Crop(xOffset: -110, scale: 1.35) ) static let water = Ingredient( id: "water", name: String(localized: "Water", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( color: .blue, offset: CGSize(width: 0, height: 150), opacity: 0.2, fontSize: 50 ), thumbnailCrop: Crop(yOffset: -10, scale: 1.2) ) static let watermelon = Ingredient( id: "watermelon", name: String(localized: "Watermelon", table: "Ingredients", comment: "Ingredient name"), title: CardTitle( rotation: Angle.degrees(-50), offset: CGSize(width: -80, height: -50), blendMode: .overlay, fontSize: 25 ), thumbnailCrop: Crop(yOffset: -10, scale: 1.2) ) } ``` ## Ingredient.swift ```swift /* Abstract: A model that represents a smoothie ingredient and its appearance as a thumbnail and card. */ // MARK: - Ingredient struct Ingredient: Identifiable, Codable { var id: String var name: String var title = CardTitle() var thumbnailCrop = Crop() var cardCrop = Crop() enum CodingKeys: String, CodingKey { case id case name } } // MARK: - All Ingredients extension Ingredient { static let all: [Ingredient] = [ .avocado, .almondMilk, .banana, .blueberry, .carrot, .chocolate, .coconut, .kiwi, .lemon, .mango, .orange, .papaya, .peanutButter, .pineapple, .raspberry, .spinach, .strawberry, .watermelon ] init?(for id: Ingredient.ID) { guard let result = Ingredient.all.first(where: { $0.id == id }) else { return nil } self = result } } ``` ## IngredientCard.swift ```swift /* Abstract: A card that presents an IngredientGraphic and allows it to flip over to reveal its nutritional information */ import SwiftUI // MARK: - Ingredient View struct IngredientCard: View { var ingredient: Ingredient var presenting: Bool var closeAction: () -> Void = {} @State private var visibleSide = FlipViewSide.front var body: some View { FlipView(visibleSide: visibleSide) { IngredientGraphic(ingredient: ingredient, style: presenting ? .cardFront : .thumbnail, closeAction: closeAction, flipAction: flipCard) } back: { IngredientGraphic(ingredient: ingredient, style: .cardBack, closeAction: closeAction, flipAction: flipCard) } .contentShape(Rectangle()) .animation(.flipCard, value: visibleSide) } func flipCard() { visibleSide.toggle() } } ``` ## IngredientGraphic.swift ```swift /* Abstract: A graphic that displays an Ingredient as a thumbnail, a card highlighting its image, or the back of a card highlighting its nutrition facts. */ import SwiftUI struct IngredientGraphic: View { var ingredient: Ingredient var style: Style var closeAction: () -> Void = {} var flipAction: () -> Void = {} enum Style { case cardFront case cardBack case thumbnail } var displayingAsCard: Bool { style == .cardFront || style == .cardBack } var shape = RoundedRectangle(cornerRadius: 16, style: .continuous) var body: some View { ZStack { image if style != .cardBack { title } if style == .cardFront { cardControls(for: .front) .foregroundStyle(ingredient.title.color) .opacity(ingredient.title.opacity) .blendMode(ingredient.title.blendMode) } if style == .cardBack { ZStack { if let nutritionFact = ingredient.nutritionFact { NutritionFactView(nutritionFact: nutritionFact) .padding(.bottom, 70) } cardControls(for: .back) } .background(.thinMaterial) } } .frame(minWidth: 130, maxWidth: 400, maxHeight: 500) .compositingGroup() .clipShape(shape) .overlay { shape .inset(by: 0.5) .stroke(.quaternary, lineWidth: 0.5) } .contentShape(shape) .accessibilityElement(children: .contain) } var image: some View { GeometryReader { geo in ingredient.image .resizable() .aspectRatio(contentMode: .fill) .frame(width: geo.size.width, height: geo.size.height) .scaleEffect(displayingAsCard ? ingredient.cardCrop.scale : ingredient.thumbnailCrop.scale) .offset(displayingAsCard ? ingredient.cardCrop.offset : ingredient.thumbnailCrop.offset) .frame(width: geo.size.width, height: geo.size.height) .scaleEffect(x: style == .cardBack ? -1 : 1) } .accessibility(hidden: true) } var title: some View { Text(ingredient.name.uppercased()) .padding(.horizontal, 8) .frame(maxWidth: .infinity, maxHeight: .infinity) .lineLimit(2) .multilineTextAlignment(.center) .foregroundStyle(ingredient.title.color) .rotationEffect(displayingAsCard ? ingredient.title.rotation: .degrees(0)) .opacity(ingredient.title.opacity) .blendMode(ingredient.title.blendMode) .animatableFont(size: displayingAsCard ? ingredient.title.fontSize : 40, weight: .bold) .minimumScaleFactor(0.25) .offset(displayingAsCard ? ingredient.title.offset : .zero) } func cardControls(for side: FlipViewSide) -> some View { VStack { if side == .front { CardActionButton(label: "Close", systemImage: "xmark.circle.fill", action: closeAction) .scaleEffect(displayingAsCard ? 1 : 0.5) .opacity(displayingAsCard ? 1 : 0) } Spacer() CardActionButton( label: side == .front ? "Open Nutrition Facts" : "Close Nutrition Facts", systemImage: side == .front ? "info.circle.fill" : "arrow.left.circle.fill", action: flipAction ) .scaleEffect(displayingAsCard ? 1 : 0.5) .opacity(displayingAsCard ? 1 : 0) } .frame(maxWidth: .infinity, alignment: .trailing) } } // MARK: - Previews struct IngredientGraphic_Previews: PreviewProvider { static let ingredient = Ingredient.orange static var previews: some View { Group { IngredientGraphic(ingredient: ingredient, style: .thumbnail) .frame(width: 180, height: 180) .previewDisplayName("Thumbnail") IngredientGraphic(ingredient: ingredient, style: .cardFront) .aspectRatio(0.75, contentMode: .fit) .frame(width: 500, height: 600) .previewDisplayName("Card Front") IngredientGraphic(ingredient: ingredient, style: .cardBack) .aspectRatio(0.75, contentMode: .fit) .frame(width: 500, height: 600) .previewDisplayName("Card Back") } .previewLayout(.sizeThatFits) } } ``` ## Account.swift ```swift /* Abstract: A representation of a customer's account. Used for calculating free smoothie redemption. */ struct Account { var orderHistory = [Order]() var pointsSpent = 0 var unstampedPoints = 0 var pointsEarned: Int { orderHistory.reduce(0) { $0 + $1.points } } var unspentPoints: Int { pointsEarned - pointsSpent } var canRedeemFreeSmoothie: Bool { unspentPoints >= 10 } mutating func clearUnstampedPoints() { unstampedPoints = 0 } mutating func appendOrder(_ order: Order) { orderHistory.append(order) unstampedPoints += order.points } } ``` ## Model.swift ```swift /* Abstract: A model representing all of the data the app needs to display in its interface. */ import Foundation import AuthenticationServices import StoreKit class Model: ObservableObject { @Published var order: Order? @Published var account: Account? var hasAccount: Bool { #if targetEnvironment(simulator) return true #else return userCredential != nil && account != nil #endif } @Published var favoriteSmoothieIDs = Set<Smoothie.ID>() @Published var selectedSmoothieID: Smoothie.ID? @Published var searchString = "" @Published var isApplePayEnabled = true @Published var allRecipesUnlocked = false @Published var unlockAllRecipesProduct: Product? let defaults = UserDefaults(suiteName: "group.example.fruta") private var userCredential: String? { get { defaults?.string(forKey: "UserCredential") } set { defaults?.setValue(newValue, forKey: "UserCredential") } } private let allProductIdentifiers = Set([Model.unlockAllRecipesIdentifier]) private var fetchedProducts: [Product] = [] private var updatesHandler: Task<Void, Error>? = nil init() { // Start listening for transaction info updates, like if the user // refunds the purchase or if a parent approves a child's request to // buy. updatesHandler = Task { await listenForStoreUpdates() } fetchProducts() guard let user = userCredential else { return } let provider = ASAuthorizationAppleIDProvider() provider.getCredentialState(forUserID: user) { state, error in if state == .authorized || state == .transferred { DispatchQueue.main.async { self.createAccount() } } } } deinit { updatesHandler?.cancel() } func authorizeUser(_ result: Result<ASAuthorization, Error>) { guard case .success(let authorization) = result, let credential = authorization.credential as? ASAuthorizationAppleIDCredential else { if case .failure(let error) = result { print("Authentication error: (error.localizedDescription)") } return } DispatchQueue.main.async { self.userCredential = credential.user self.createAccount() } } } // MARK: - Smoothies�& Account extension Model { func orderSmoothie(_ smoothie: Smoothie) { order = Order(smoothie: smoothie, points: 1, isReady: false) addOrderToAccount() } func redeemSmoothie(_ smoothie: Smoothie) { guard var account = account, account.canRedeemFreeSmoothie else { return } account.pointsSpent += 10 self.account = account orderSmoothie(smoothie) } func orderReadyForPickup() { order?.isReady = true } func toggleFavorite(smoothieID: Smoothie.ID) { if favoriteSmoothieIDs.contains(smoothieID) { favoriteSmoothieIDs.remove(smoothieID) } else { favoriteSmoothieIDs.insert(smoothieID) } } func isFavorite(smoothie: Smoothie) -> Bool { favoriteSmoothieIDs.contains(smoothie.id) } func createAccount() { guard account == nil else { return } account = Account() addOrderToAccount() } func addOrderToAccount() { guard let order = order else { return } account?.appendOrder(order) } func clearUnstampedPoints() { account?.clearUnstampedPoints() } var searchSuggestions: [Ingredient] { Ingredient.all.filter { $0.name.localizedCaseInsensitiveContains(searchString) && $0.name.localizedCaseInsensitiveCompare(searchString) != .orderedSame } } } // MARK: - Store API extension Model { static let unlockAllRecipesIdentifier = "com.example.apple-samplecode.fruta.unlock-recipes" func product(for identifier: String) -> Product? { return fetchedProducts.first(where: { $0.id == identifier }) } func purchase(product: Product) { Task { @MainActor in do { let result = try await product.purchase() guard case .success(.verified(let transaction)) = result, transaction.productID == Model.unlockAllRecipesIdentifier else { return } self.allRecipesUnlocked = true } catch { print("Failed to purchase (product.id): (error)") } } } } // MARK: - Private Logic extension Model { private func fetchProducts() { Task { @MainActor in self.fetchedProducts = try await Product.products(for: allProductIdentifiers) self.unlockAllRecipesProduct = self.fetchedProducts .first { $0.id == Model.unlockAllRecipesIdentifier } // Check if the user owns all recipes at app launch. await self.updateAllRecipesOwned() } } @MainActor private func updateAllRecipesOwned() async { guard let product = self.unlockAllRecipesProduct else { self.allRecipesUnlocked = false return } guard let entitlement = await product.currentEntitlement, case .verified(_) = entitlement else { self.allRecipesUnlocked = false return } self.allRecipesUnlocked = true } /// - Important: This method never returns, it will only suspend. @MainActor private func listenForStoreUpdates() async { for await update in Transaction.updates { guard case .verified(let transaction) = update else { print("Unverified transaction update: (update)") continue } guard transaction.productID == Model.unlockAllRecipesIdentifier else { continue } // If this transaction was revoked, make sure the user no longer // has access to it. if transaction.revocationReason != nil { print("Revoking access to (transaction.productID)") self.allRecipesUnlocked = false } else { self.allRecipesUnlocked = true await transaction.finish() } } } } ``` ## Order.swift ```swift /* Abstract: A representation of an order � how many points it is worth and whether it is ready to be picked up. */ struct Order { private(set) var smoothie: Smoothie private(set) var points: Int var isReady: Bool } ``` ## AppSidebarNavigation.swift ```swift /* Abstract: The app's navigation with a configuration that offers a sidebar, content list, and detail pane. */ import SwiftUI struct AppSidebarNavigation: View { enum NavigationItem { case menu case favorites case recipes } @EnvironmentObject private var model: Model @State private var presentingRewards: Bool = false @State private var selection: NavigationItem? = .menu var body: some View { NavigationView { List { NavigationLink(tag: NavigationItem.menu, selection: $selection) { SmoothieMenu() } label: { Label("Menu", systemImage: "list.bullet") } NavigationLink(tag: NavigationItem.favorites, selection: $selection) { FavoriteSmoothies() } label: { Label("Favorites", systemImage: "heart") } #if EXTENDED_ALL NavigationLink(tag: NavigationItem.recipes, selection: $selection) { RecipeList() } label: { Label("Recipes", systemImage: "book.closed") } #endif } .navigationTitle("Fruta") #if EXTENDED_ALL .safeAreaInset(edge: .bottom, spacing: 0) { Pocket() } #endif Text("Select a category") .foregroundStyle(.secondary) .frame(maxWidth: .infinity, maxHeight: .infinity) .background() .ignoresSafeArea() Text("Select a smoothie") .foregroundStyle(.secondary) .frame(maxWidth: .infinity, maxHeight: .infinity) .background() .ignoresSafeArea() .toolbar { SmoothieFavoriteButton() .environmentObject(model) .disabled(true) } } } struct Pocket: View { @State private var presentingRewards: Bool = false @EnvironmentObject private var model: Model var body: some View { Button(action: { presentingRewards = true }) { Label("Rewards", systemImage: "seal") } .controlSize(.large) .buttonStyle(.capsule) .padding(.vertical, 8) .padding(.horizontal, 16) .sheet(isPresented: $presentingRewards) { RewardsView() #if os(iOS) .overlay(alignment: .topTrailing) { Button(action: { presentingRewards = false }) { Text("Done", comment: "Button title to dismiss rewards sheet") } .font(.body.bold()) .keyboardShortcut(.defaultAction) .buttonStyle(.capsule) .padding() } #else .frame(minWidth: 400, maxWidth: 600, minHeight: 400, maxHeight: 600) .toolbar { ToolbarItem(placement: .confirmationAction) { Button(action: { presentingRewards = false }) { Text("Done", comment: "Button title to dismiss rewards sheet") } } } #endif } } } } struct AppSidebarNavigation_Previews: PreviewProvider { static var previews: some View { AppSidebarNavigation() .environmentObject(Model()) } } struct AppSidebarNavigationPocket_Previews: PreviewProvider { static var previews: some View { AppSidebarNavigation.Pocket() .environmentObject(Model()) .frame(width: 300) } } ``` ## ContentView.swift ```swift /* Abstract: The primary entry point for the app's user interface. Can change between tab-based and sidebar-based navigation. */ import SwiftUI struct ContentView: View { #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass #endif var body: some View { #if os(iOS) if horizontalSizeClass == .compact { AppTabNavigation() } else { AppSidebarNavigation() } #else AppSidebarNavigation() #endif } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ``` ## DisplayableMeasurement.swift ```swift /* Abstract: A measurement that can be displayed with a title and image. */ import Foundation import SwiftUI public protocol DisplayableMeasurement { var unitImage: Image { get } func localizedSummary(unitStyle: MeasurementFormatter.UnitStyle, unitOptions: MeasurementFormatter.UnitOptions) -> String } extension DisplayableMeasurement { public func localizedSummary() -> String { localizedSummary(unitStyle: .long, unitOptions: [.providedUnit]) } } extension Measurement: DisplayableMeasurement { public func localizedSummary(unitStyle: MeasurementFormatter.UnitStyle = .long, unitOptions: MeasurementFormatter.UnitOptions = [.providedUnit]) -> String { let formatter = MeasurementFormatter() formatter.unitStyle = unitStyle formatter.unitOptions = unitOptions return formatter.string(from: self) } public var unitImage: Image { unit.unitIcon } } ``` ## NutritionFact+Decodable.swift ```swift /* Abstract: Loading nutrition facts from JSON */ import Foundation //let nutritionFacts: [String: NutritionFact] = { // let jsonURL = Bundle.main.url(forResource: "NutritionalItems", withExtension: "json")! // let jsonData = try! Data(contentsOf: jsonURL) // // // return try! JSONDecoder().decode(Dictionary<String, NutritionFact>.self, from: jsonData) //}() let nutritionFacts: [String: NutritionFact] = { if let jsonURL = Bundle.main.url(forResource: "NutritionalItems", withExtension: "json"), let jsonData = try? Data(contentsOf: jsonURL), let facts = try? JSONDecoder().decode(Dictionary<String, NutritionFact>.self, from: jsonData) { return facts } else { return [String: NutritionFact]() } }() extension NutritionFact: Decodable { enum CodingKeys: String, CodingKey { case identifier case localizedFoodItemName case referenceMass case density case totalSaturatedFat case totalMonounsaturatedFat case totalPolyunsaturatedFat case cholesterol case sodium case totalCarbohydrates case dietaryFiber case sugar case protein case calcium case potassium case vitaminA case vitaminC case iron } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) identifier = try values.decode(String.self, forKey: .identifier) localizedFoodItemName = try values.decode(String.self, forKey: .localizedFoodItemName) let densityString = try values.decode(String.self, forKey: .density) density = Density.fromString(densityString) referenceMass = try values.decode(Measurement<UnitMass>.self, forKey: .referenceMass) totalSaturatedFat = try values.decode(Measurement<UnitMass>.self, forKey: .totalSaturatedFat) totalMonounsaturatedFat = try values.decode(Measurement<UnitMass>.self, forKey: .totalMonounsaturatedFat) totalPolyunsaturatedFat = try values.decode(Measurement<UnitMass>.self, forKey: .totalPolyunsaturatedFat) cholesterol = try values.decode(Measurement<UnitMass>.self, forKey: .cholesterol) sodium = try values.decode(Measurement<UnitMass>.self, forKey: .sodium) totalCarbohydrates = try values.decode(Measurement<UnitMass>.self, forKey: .totalCarbohydrates) dietaryFiber = try values.decode(Measurement<UnitMass>.self, forKey: .dietaryFiber) sugar = try values.decode(Measurement<UnitMass>.self, forKey: .sugar) protein = try values.decode(Measurement<UnitMass>.self, forKey: .protein) calcium = try values.decode(Measurement<UnitMass>.self, forKey: .calcium) potassium = try values.decode(Measurement<UnitMass>.self, forKey: .potassium) vitaminA = try values.decode(Measurement<UnitMass>.self, forKey: .vitaminA) vitaminC = try values.decode(Measurement<UnitMass>.self, forKey: .vitaminC) iron = try values.decode(Measurement<UnitMass>.self, forKey: .iron) } } extension KeyedDecodingContainer { public func decode(_ type: Measurement<UnitMass>.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Measurement<UnitMass> { let valueString = try decode(String.self, forKey: key) return Measurement(string: valueString) } public func decode(_ type: Measurement<UnitVolume>.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Measurement<UnitVolume> { let valueString = try decode(String.self, forKey: key) return Measurement(string: valueString) } } extension Measurement where UnitType == UnitMass { init(string: String) { let components = string.split(separator: " ") let valueString = String(components[0]) let unitSymbolString = String(components[1]) self.init( value: Double(valueString)!, unit: UnitMass.fromSymbol(unitSymbolString) ) } } extension Measurement where UnitType == UnitVolume { init(string: String) { let components = string.split(separator: " ") let valueString = String(components[0]) let unitSymbolString = String(components[1]) self.init( value: Double(valueString)!, unit: UnitVolume.fromSymbol(unitSymbolString) ) } } // These methods return Units with an associated converter, whereas units // initialized from a string using the `Unit(symbol:)` initializer // do not have a converter associated and thereby don't support conversion. extension UnitVolume { static func fromSymbol(_ symbol: String) -> UnitVolume { switch symbol { case "gal": return .gallons case "cup": return .cups default: return UnitVolume(symbol: symbol) } } } extension UnitMass { static func fromSymbol(_ symbol: String) -> UnitMass { switch symbol { case "kg": return .kilograms case "g": return .grams case "mg": return .milligrams default: return UnitMass(symbol: symbol) } } } extension UnitEnergy { static func fromSymbol(_ symbol: String) -> UnitEnergy { switch symbol { case "kCal": return .kilocalories default: return UnitEnergy(symbol: symbol) } } } extension Density { fileprivate static func fromString(_ string: String) -> Density { // Example: 5 g per 1 cup let components = string.split(separator: " ") let massValue = Double(components[0])! let massUnit: UnitMass = .fromSymbol(String(components[1])) let volumeValue = Double(components[3])! let volumeUnit: UnitVolume = .fromSymbol(String(components[4])) return Density(massValue, massUnit, per: volumeValue, volumeUnit) } } ``` ## NutritionFact+Energy.swift ```swift /* Abstract: Break down of calories in fat, carbohydrates, and protein */ import Foundation private let kilocaloriesInFat: Double = 9 private let kilocaloriesInCarb: Double = 4 private let kilocaloriesInProtein: Double = 4 public struct CalorieBreakdown { public let percentFat: Double public let percentCarbohydrate: Double public let percentProtein: Double public var labeledValues: [(String, Double)] { return [ ("Protein", percentProtein), ("Fat", percentFat), ("Carbohydrates", percentCarbohydrate) ] } } extension NutritionFact { public var kilocaloriesFromFat: Double { totalFat.converted(to: .grams).value * kilocaloriesInFat } public var kilocaloriesFromCarbohydrates: Double { (totalCarbohydrates - dietaryFiber).converted(to: .grams).value * kilocaloriesInCarb } public var kilocaloriesFromProtein: Double { protein.converted(to: .grams).value * kilocaloriesInProtein } public var kilocalories: Double { kilocaloriesFromFat + kilocaloriesFromCarbohydrates + kilocaloriesFromProtein } public var energy: Measurement<UnitEnergy> { return Measurement<UnitEnergy>(value: kilocalories, unit: .kilocalories) } public var calorieBreakdown: CalorieBreakdown { let totalKilocalories = kilocalories let percentFat = kilocaloriesFromFat / totalKilocalories * 100 let percentCarbohydrate = kilocaloriesFromCarbohydrates / totalKilocalories * 100 let percentProtein = kilocaloriesFromProtein / totalKilocalories * 100 return CalorieBreakdown( percentFat: percentFat, percentCarbohydrate: percentCarbohydrate, percentProtein: percentProtein ) } } ``` ## NutritionFact.swift ```swift /* Abstract: Nutritional facts for food items. */ import Foundation public struct Density { public var mass: Measurement<UnitMass> public var volume: Measurement<UnitVolume> public init(_ massAmount: Double, _ massUnit: UnitMass, per volumeAmount: Double, _ volumeUnit: UnitVolume) { self.mass = Measurement(value: massAmount, unit: massUnit) self.volume = Measurement(value: volumeAmount, unit: volumeUnit) } public init(mass: Measurement<UnitMass>, volume: Measurement<UnitVolume>) { self.mass = mass self.volume = volume } } public struct NutritionFact { public var identifier: String public var localizedFoodItemName: String public var referenceMass: Measurement<UnitMass> public var density: Density public var totalSaturatedFat: Measurement<UnitMass> public var totalMonounsaturatedFat: Measurement<UnitMass> public var totalPolyunsaturatedFat: Measurement<UnitMass> public var totalFat: Measurement<UnitMass> { return totalSaturatedFat + totalMonounsaturatedFat + totalPolyunsaturatedFat } public var cholesterol: Measurement<UnitMass> public var sodium: Measurement<UnitMass> public var totalCarbohydrates: Measurement<UnitMass> public var dietaryFiber: Measurement<UnitMass> public var sugar: Measurement<UnitMass> public var protein: Measurement<UnitMass> public var calcium: Measurement<UnitMass> public var potassium: Measurement<UnitMass> public var vitaminA: Measurement<UnitMass> public var vitaminC: Measurement<UnitMass> public var iron: Measurement<UnitMass> } extension NutritionFact { public func converted(toVolume newReferenceVolume: Measurement<UnitVolume>) -> NutritionFact { let newRefMassInCups = newReferenceVolume.converted(to: .cups).value let oldRefMassInCups = referenceMass.convertedToVolume(usingDensity: self.density).value let scaleFactor = newRefMassInCups / oldRefMassInCups return NutritionFact( identifier: identifier, localizedFoodItemName: localizedFoodItemName, referenceMass: referenceMass * scaleFactor, density: density, totalSaturatedFat: totalSaturatedFat * scaleFactor, totalMonounsaturatedFat: totalMonounsaturatedFat * scaleFactor, totalPolyunsaturatedFat: totalPolyunsaturatedFat * scaleFactor, cholesterol: cholesterol * scaleFactor, sodium: sodium * scaleFactor, totalCarbohydrates: totalCarbohydrates * scaleFactor, dietaryFiber: dietaryFiber * scaleFactor, sugar: sugar * scaleFactor, protein: protein * scaleFactor, calcium: calcium * scaleFactor, potassium: potassium * scaleFactor, vitaminA: vitaminA * scaleFactor, vitaminC: vitaminC * scaleFactor, iron: iron * scaleFactor ) } public func converted(toMass newReferenceMass: Measurement<UnitMass>) -> NutritionFact { let newRefMassInGrams = newReferenceMass.converted(to: .grams).value let oldRefMassInGrams = referenceMass.converted(to: .grams).value let scaleFactor = newRefMassInGrams / oldRefMassInGrams return NutritionFact( identifier: identifier, localizedFoodItemName: localizedFoodItemName, referenceMass: newReferenceMass, density: density, totalSaturatedFat: totalSaturatedFat * scaleFactor, totalMonounsaturatedFat: totalMonounsaturatedFat * scaleFactor, totalPolyunsaturatedFat: totalPolyunsaturatedFat * scaleFactor, cholesterol: cholesterol * scaleFactor, sodium: sodium * scaleFactor, totalCarbohydrates: totalCarbohydrates * scaleFactor, dietaryFiber: dietaryFiber * scaleFactor, sugar: sugar * scaleFactor, protein: protein * scaleFactor, calcium: calcium * scaleFactor, potassium: potassium * scaleFactor, vitaminA: vitaminA * scaleFactor, vitaminC: vitaminC * scaleFactor, iron: iron * scaleFactor ) } public func amount(_ mass: Measurement<UnitMass>) -> NutritionFact { return converted(toMass: mass) } public func amount(_ volume: Measurement<UnitVolume>) -> NutritionFact { let mass = volume.convertedToMass(usingDensity: density) return converted(toMass: mass) } } extension NutritionFact { /// Nutritional information is for 100 grams, unless a `mass` is specified. public static func lookupFoodItem(_ foodItemIdentifier: String, forMass mass: Measurement<UnitMass> = Measurement(value: 100, unit: .grams)) -> NutritionFact? { return nutritionFacts[foodItemIdentifier]?.converted(toMass: mass) } /// Nutritional information is for 1 cup, unless a `volume` is specified. public static func lookupFoodItem(_ foodItemIdentifier: String, forVolume volume: Measurement<UnitVolume> = Measurement(value: 1, unit: .cups)) -> NutritionFact? { guard let nutritionFact = nutritionFacts[foodItemIdentifier] else { return nil } // Convert volume to mass via density let mass = volume.convertedToMass(usingDensity: nutritionFact.density) return nutritionFact.converted(toMass: mass) } // MARK: - Examples public static var banana: NutritionFact { nutritionFacts["banana"]! } public static var blueberry: NutritionFact { nutritionFacts["blueberry"]! } public static var peanutButter: NutritionFact { nutritionFacts["peanut-butter"]! } public static var almondMilk: NutritionFact { nutritionFacts["almond-milk"]! } public static var zero: NutritionFact { NutritionFact( identifier: "", localizedFoodItemName: "", referenceMass: .grams(0), density: Density(mass: .grams(1), volume: .cups(1)), totalSaturatedFat: .grams(0), totalMonounsaturatedFat: .grams(0), totalPolyunsaturatedFat: .grams(0), cholesterol: .grams(0), sodium: .grams(0), totalCarbohydrates: .grams(0), dietaryFiber: .grams(0), sugar: .grams(0), protein: .grams(0), calcium: .grams(0), potassium: .grams(0), vitaminA: .grams(0), vitaminC: .grams(0), iron: .grams(0) ) } } extension NutritionFact { // Support adding up nutritional facts public static func + (lhs: NutritionFact, rhs: NutritionFact) -> NutritionFact { // Calculate combined mass, volume and density let totalMass = lhs.referenceMass + rhs.referenceMass let lhsVolume = lhs.referenceMass.convertedToVolume(usingDensity: lhs.density) let rhsVolume = lhs.referenceMass.convertedToVolume(usingDensity: lhs.density) let totalVolume = lhsVolume + rhsVolume return NutritionFact( identifier: "", localizedFoodItemName: "", referenceMass: totalMass, density: Density(mass: totalMass, volume: totalVolume), totalSaturatedFat: lhs.totalSaturatedFat + rhs.totalSaturatedFat, totalMonounsaturatedFat: lhs.totalMonounsaturatedFat + rhs.totalMonounsaturatedFat, totalPolyunsaturatedFat: lhs.totalPolyunsaturatedFat + rhs.totalPolyunsaturatedFat, cholesterol: lhs.cholesterol + rhs.cholesterol, sodium: lhs.sodium + rhs.sodium, totalCarbohydrates: lhs.totalCarbohydrates + rhs.totalCarbohydrates, dietaryFiber: lhs.dietaryFiber + rhs.dietaryFiber, sugar: lhs.sugar + rhs.sugar, protein: lhs.protein + rhs.protein, calcium: lhs.calcium + rhs.calcium, potassium: lhs.potassium + rhs.potassium, vitaminA: lhs.vitaminA + rhs.vitaminA, vitaminC: lhs.vitaminC + rhs.vitaminC, iron: lhs.iron + rhs.iron ) } } // MARK: - CustomStringConvertible extension NutritionFact: CustomStringConvertible { public var description: String { let suffix = identifier.isEmpty ? "" : " of (identifier)" return "(referenceMass.converted(to: .grams).localizedSummary(unitStyle: .medium))" + suffix } } // MARK: - Volume <-> Mass Conversion extension Measurement where UnitType == UnitVolume { public func convertedToMass(usingDensity density: Density) -> Measurement<UnitMass> { let densityLiters = density.volume.converted(to: .liters).value let liters = converted(to: .liters).value let scale = liters / densityLiters return density.mass * scale } } extension Measurement where UnitType == UnitMass { public func convertedToVolume(usingDensity density: Density) -> Measurement<UnitVolume> { let densityKilograms = density.mass.converted(to: .kilograms).value let kilograms = converted(to: .kilograms).value let scale = kilograms / densityKilograms return density.volume * scale } } // MARK: - Convenience Accessors extension Measurement where UnitType == UnitVolume { public static func cups(_ cups: Double) -> Measurement<UnitVolume> { return Measurement(value: cups, unit: .cups) } public static func tablespoons(_ tablespoons: Double) -> Measurement<UnitVolume> { return Measurement(value: tablespoons, unit: .tablespoons) } } extension Measurement where UnitType == UnitMass { public static func grams(_ grams: Double) -> Measurement<UnitMass> { return Measurement(value: grams, unit: .grams) } } ``` ## NutritionFactView.swift ```swift /* Abstract: A view that represents nutritional facts */ import SwiftUI public struct NutritionFactView: View { public var nutritionFact: NutritionFact public init(nutritionFact: NutritionFact) { self.nutritionFact = nutritionFact.converted(toVolume: .cups(1)) } public var body: some View { VStack(alignment: .leading, spacing: 0) { VStack(alignment: .leading) { Text("Nutrition Facts") .font(.title2) .bold() Text("Serving Size 1 Cup") .font(.footnote) Text(nutritionFact.energy.formatted(.measurement(width: .wide, usage: .food))) .fontWeight(.semibold) .padding(.top, 10) } .padding(20) Divider() .padding(.horizontal, 20) ScrollView { VStack(spacing: 0) { ForEach(nutritionFact.nutritions) { nutrition in NutritionRow(nutrition: nutrition) .padding(.vertical, 4) .padding(.leading, nutrition.indented ? 10 : 0) Divider() } } .padding([.bottom, .horizontal], 20) } } } } struct NutritionFactView_Previews: PreviewProvider { static var previews: some View { Group { ForEach(["en", "de", "pt"], id: \.self) { lang in NutritionFactView(nutritionFact: .banana) .previewLayout(.fixed(width: 300, height: 500)) .environment(\.locale, .init(identifier: lang)) } } } } ``` ## NutritionRow.swift ```swift /* Abstract: An individual row of a larger nutritional facts list */ import SwiftUI public struct NutritionRow: View { public var nutrition: Nutrition public init(nutrition: Nutrition) { self.nutrition = nutrition } var nutritionValue: String { nutrition.measurement.localizedSummary( unitStyle: .short, unitOptions: .providedUnit ) } public var body: some View { HStack { Text(nutrition.name) .fontWeight(.medium) Spacer() Text(nutritionValue) .fontWeight(.semibold) .foregroundStyle(.secondary) } .font(.footnote) } } struct NutritionRow_Previews: PreviewProvider { static var previews: some View { let nutrition = Nutrition( id: "iron", name: "Iron", measurement: Measurement( value: 25, unit: UnitMass.milligrams ) ) return NutritionRow(nutrition: nutrition) .frame(maxWidth: 300) } } ``` ## Nutritions.swift ```swift /* Abstract: Names of nutritional information and their measurements */ import SwiftUI public struct Nutrition: Identifiable { public var id: String public var name: LocalizedStringKey public var measurement: DisplayableMeasurement public var indented: Bool = false } extension NutritionFact { public var nutritions: [Nutrition] { [ Nutrition( id: "totalFat", name: "Total Fat", measurement: totalFat ), Nutrition( id: "totalSaturatedFat", name: "Saturated Fat", measurement: totalSaturatedFat, indented: true ), Nutrition( id: "totalMonounsaturatedFat", name: "Monounsaturated Fat", measurement: totalMonounsaturatedFat, indented: true ), Nutrition( id: "totalPolyunsaturatedFat", name: "Polyunsaturated Fat", measurement: totalPolyunsaturatedFat, indented: true ), Nutrition( id: "cholesterol", name: "Cholesterol", measurement: cholesterol ), Nutrition( id: "sodium", name: "Sodium", measurement: sodium ), Nutrition( id: "totalCarbohydrates", name: "Total Carbohydrates", measurement: totalCarbohydrates ), Nutrition( id: "dietaryFiber", name: "Dietary Fiber", measurement: dietaryFiber, indented: true ), Nutrition( id: "sugar", name: "Sugar", measurement: sugar, indented: true ), Nutrition( id: "protein", name: "Protein", measurement: protein ), Nutrition( id: "calcium", name: "Calcium", measurement: calcium ), Nutrition( id: "potassium", name: "Potassium", measurement: potassium ), Nutrition( id: "vitaminA", name: "Vitamin A", measurement: vitaminA ), Nutrition( id: "vitaminC", name: "Vitamin C", measurement: vitaminC ), Nutrition( id: "iron", name: "Iron", measurement: iron ) ] } } ``` ## UnitIcons.swift ```swift /* Abstract: Iconography for different units for mass and volume. */ import Foundation import SwiftUI extension Unit { public var unitIcon: Image { if let iconProvider = self as? UnitIconProvider { return iconProvider.customUnitIcon } // Fallback to 'gauge' where no icon is specified return Image(systemName: "gauge") } } // Allow Unit subclasses to provide icon overrides private protocol UnitIconProvider { var customUnitIcon: Image { get } } extension UnitMass: UnitIconProvider { var customUnitIcon: Image { Image(systemName: "scalemass.fill") } } extension UnitVolume: UnitIconProvider { var customUnitIcon: Image { switch symbol { // Icons included in the asset catalog case "cup", "qt", "tbsp", "tsp", "gal": return Image(symbol) default: return Image(systemName: "drop.fill") } } } ``` ## OrderPlacedView.swift ```swift /* Abstract: A view presented to the user once they order a smoothie, and when it's ready to be picked up. */ import SwiftUI import AuthenticationServices import StoreKit struct OrderPlacedView: View { @EnvironmentObject private var model: Model #if APPCLIP @State private var presentingAppStoreOverlay = false #endif var orderReady: Bool { guard let order = model.order else { return false } return order.isReady } var presentingBottomBanner: Bool { #if APPCLIP if presentingAppStoreOverlay { return true } #endif return !model.hasAccount } /// - Tag: ActiveCompilationConditionTag var body: some View { VStack(spacing: 0) { Spacer() orderStatusCard Spacer() #if EXTENDED_ALL if presentingBottomBanner { bottomBanner } #endif #if APPCLIP Text(verbatim: "App Store Overlay") .hidden() .appStoreOverlay(isPresented: $presentingAppStoreOverlay) { SKOverlay.AppClipConfiguration(position: .bottom) } #endif } .onChange(of: model.hasAccount) { _ in #if APPCLIP if model.hasAccount { presentingAppStoreOverlay = true } #endif } .frame(maxWidth: .infinity, maxHeight: .infinity) .background { ZStack { if let order = model.order { order.smoothie.image .resizable() .aspectRatio(contentMode: .fill) } else { Color("order-placed-background") } if model.order?.isReady == false { Rectangle() .fill(.ultraThinMaterial) } } .ignoresSafeArea() } .animation(.spring(response: 0.25, dampingFraction: 1), value: orderReady) .animation(.spring(response: 0.25, dampingFraction: 1), value: model.hasAccount) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 4) { self.model.orderReadyForPickup() } #if APPCLIP if model.hasAccount { presentingAppStoreOverlay = true } #endif } } var orderStatusCard: some View { FlipView(visibleSide: orderReady ? .back : .front) { Card( title: "Thank you for your order!", subtitle: "We will notify you when your order is ready." ) } back: { let smoothieName = model.order?.smoothie.title ?? String(localized: "Smoothie", comment: "Fallback name for smoothie") Card( title: "Your smoothie is ready!", subtitle: "(smoothieName) is ready to be picked up." ) } .animation(.flipCard, value: orderReady) .padding() } var bottomBanner: some View { VStack { if !model.hasAccount { Text("Sign up to get rewards!") .font(Font.headline.bold()) SignInWithAppleButton(.signUp, onRequest: { _ in }, onCompletion: model.authorizeUser) .frame(minWidth: 100, maxWidth: 400) .padding(.horizontal, 20) #if os(iOS) .frame(height: 45) #endif } else { #if APPCLIP if presentingAppStoreOverlay { Text("Get the full smoothie experience!") .font(Font.title2.bold()) .padding(.top, 15) .padding(.bottom, 150) } #endif } } .padding() .frame(maxWidth: .infinity) .background(.bar) } struct Card: View { var title: LocalizedStringKey var subtitle: LocalizedStringKey var body: some View { VStack(spacing: 16) { Text(title) .font(Font.title.bold()) .textCase(.uppercase) .layoutPriority(1) Text(subtitle) .font(.system(.headline, design: .rounded)) .foregroundStyle(.secondary) } .multilineTextAlignment(.center) .padding(.horizontal, 36) .frame(width: 300, height: 300) .background(in: Circle()) } } } struct OrderPlacedView_Previews: PreviewProvider { static let orderReady: Model = { let model = Model() model.orderSmoothie(Smoothie.berryBlue) model.orderReadyForPickup() return model }() static let orderNotReady: Model = { let model = Model() model.orderSmoothie(Smoothie.berryBlue) return model }() static var previews: some View { Group { #if !APPCLIP OrderPlacedView() .environmentObject(orderNotReady) OrderPlacedView() .environmentObject(orderReady) #endif } } } ``` ## PaymentButton.swift ```swift /* Abstract: A button that hosts PKPaymentButton for simulating smoothie purchases with Apple Pay. */ import SwiftUI import PassKit struct PaymentButton: View { var action: () -> Void var height: Double { #if os(macOS) return 30 #else return 45 #endif } var body: some View { Representable(action: action) .frame(minWidth: 100, maxWidth: 400) .frame(height: height) .frame(maxWidth: .infinity) .accessibility(label: Text("Buy with Apple Pay", comment: "Accessibility label for Buy with Apple Pay button")) } } extension PaymentButton { #if os(iOS) typealias ViewRepresentable = UIViewRepresentable #else typealias ViewRepresentable = NSViewRepresentable #endif struct Representable: ViewRepresentable { var action: () -> Void func makeCoordinator() -> Coordinator { Coordinator(action: action) } #if os(iOS) func makeUIView(context: Context) -> UIView { context.coordinator.button } func updateUIView(_ rootView: UIView, context: Context) { context.coordinator.action = action } #else func makeNSView(context: Context) -> NSView { context.coordinator.button } func updateNSView(_ rootView: NSView, context: Context) { context.coordinator.action = action } #endif } class Coordinator: NSObject { var action: () -> Void var button = PKPaymentButton(paymentButtonType: .buy, paymentButtonStyle: .automatic) init(action: @escaping () -> Void) { self.action = action super.init() #if os(iOS) button.addTarget(self, action: #selector(callback(_:)), for: .touchUpInside) #else button.action = #selector(callback(_:)) button.target = self #endif } @objc func callback(_ sender: Any) { action() } } } struct PaymentButton_Previews: PreviewProvider { static var previews: some View { Group { PaymentButton(action: {}) .padding() .preferredColorScheme(.light) PaymentButton(action: {}) .padding() .preferredColorScheme(.dark) } .previewLayout(.sizeThatFits) } } ``` ## RewardsCard.swift ```swift /* Abstract: Animates newly aquired points as stamps on a card representing progress towards the next free smoothie. */ import SwiftUI struct RewardsCard: View { var totalStamps: Int var animatedStamps = 0 var hasAccount: Bool var compact = false var spacing: Double { compact ? 10 : 20 } var columns: [GridItem] { [GridItem](repeating: GridItem(.flexible(minimum: 20), spacing: 10), count: 5) } var body: some View { VStack { VStack(spacing: 0) { Text("Rewards Card", comment: "Header for rewards card") .font(compact ? Font.subheadline.bold() : Font.title2.bold()) .padding(.top, spacing) LazyVGrid(columns: columns, spacing: 10) { ForEach(1...10, id: \.self) { index in let status: StampSlot.Status = { guard index <= totalStamps else { return .unstamped } let firstAnimatedIndex = totalStamps - animatedStamps if index >= firstAnimatedIndex { return .stampedAnimated(delayIndex: index - firstAnimatedIndex) } else { return .stamped } }() StampSlot(status: status, compact: compact) } } .frame(maxWidth: compact ? 250 : 300) .opacity(hasAccount ? 1 : 0.5) .padding(spacing) } .background() .clipShape(RoundedRectangle(cornerRadius: spacing, style: .continuous)) .accessibility(label: Text("(totalStamps) of 10 points earned", comment: "Accessibility label for number of points earned")) if !compact { Group { if hasAccount { Text("You are (10 - totalStamps) points away from a free smoothie!", comment: "Label showing the number of points needed to get a free smoothie in rewards card view") } else { #if EXTENDED_ALL Text("Sign up to get rewards!", comment: "Label shown in rewards card view when no account has been created yet") #endif } } .font(Font.system(.headline, design: .rounded).bold()) .multilineTextAlignment(.center) .foregroundStyle(Color("rewards-foreground")) .padding([.horizontal], 20) } } .padding(20) } } extension RewardsCard { struct StampSlot: View { enum Status { case unstamped case stampedAnimated(delayIndex: Int) case stamped } var status: Status var compact = false @State private var stamped = false var body: some View { ZStack { Circle().fill(Color("bubbles-background").opacity(0.5)) switch status { case .stamped, .stampedAnimated: Image(systemName: "seal.fill") .font(.system(size: compact ? 24 : 30)) .scaleEffect(stamped ? 1 : 2) .opacity(stamped ? 1 : 0) .foregroundStyle(Color("rewards-foreground")) default: EmptyView() } } .aspectRatio(1, contentMode: .fit) .onAppear { switch status { case .stamped: stamped = true case .stampedAnimated(let delayIndex): let delay = Double(delayIndex + 1) * 0.15 #if !os(macOS) withAnimation(Animation.spring(response: 0.5, dampingFraction: 0.8).delay(delay)) { stamped = true } #else stamped = true #endif default: stamped = false } } } } } struct RewardsCard_Previews: PreviewProvider { static var previews: some View { RewardsCard(totalStamps: 8, animatedStamps: 4, hasAccount: true) .padding() .previewLayout(.sizeThatFits) } } ``` ## RewardsView.swift ```swift /* Abstract: Displays progress towards the next free smoothie, as well as offers a way for users to create an account. */ import SwiftUI import AuthenticationServices struct RewardsView: View { @EnvironmentObject private var model: Model var body: some View { ZStack { RewardsCard( totalStamps: model.account?.unspentPoints ?? 0, animatedStamps: model.account?.unstampedPoints ?? 0, hasAccount: model.hasAccount ) .onDisappear { model.clearUnstampedPoints() } } .frame(maxWidth: .infinity, maxHeight: .infinity) #if os(iOS) .navigationBarTitleDisplayMode(.inline) #endif #if EXTENDED_ALL .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { Divider() if !model.hasAccount { SignInWithAppleButton(.signUp, onRequest: { _ in }, onCompletion: model.authorizeUser) .frame(minWidth: 100, maxWidth: 400) .padding(.horizontal, 20) #if os(iOS) .frame(height: 45) #endif .padding(.horizontal, 20) .padding() .frame(maxWidth: .infinity) } } .background(.bar) } #endif .frame(maxWidth: .infinity, maxHeight: .infinity) .background(BubbleBackground().ignoresSafeArea()) } } struct SmoothieRewards_Previews: PreviewProvider { static let dataStore: Model = { var dataStore = Model() dataStore.createAccount() dataStore.orderSmoothie(.thatsBerryBananas) dataStore.orderSmoothie(.thatsBerryBananas) dataStore.orderSmoothie(.thatsBerryBananas) dataStore.orderSmoothie(.thatsBerryBananas) return dataStore }() static var previews: some View { Group { RewardsView() .preferredColorScheme(.light) RewardsView() .preferredColorScheme(.dark) RewardsView() .environmentObject(Model()) } .environmentObject(dataStore) } } ``` ## MeasuredIngredient.swift ```swift /* Abstract: An ingredient with a measurement that informs its nutrition facts */ import SwiftUI struct MeasuredIngredient: Identifiable, Codable { var ingredient: Ingredient var measurement: Measurement<UnitVolume> init(_ ingredient: Ingredient, measurement: Measurement<UnitVolume>) { self.ingredient = ingredient self.measurement = measurement } // Identifiable var id: Ingredient.ID { ingredient.id } } extension MeasuredIngredient { var kilocalories: Int { guard let nutritionFact = nutritionFact else { return 0 } return Int(nutritionFact.kilocalories) } // Nutritional information according to the quantity of this measurement. var nutritionFact: NutritionFact? { guard let nutritionFact = ingredient.nutritionFact else { return nil } let mass = measurement.convertedToMass(usingDensity: nutritionFact.density) return nutritionFact.converted(toMass: mass) } } extension Ingredient { func measured(with unit: UnitVolume) -> MeasuredIngredient { MeasuredIngredient(self, measurement: Measurement(value: 1, unit: unit)) } } extension MeasuredIngredient { func scaled(by scale: Double) -> MeasuredIngredient { return MeasuredIngredient(ingredient, measurement: measurement * scale) } } ``` ## MeasurementView.swift ```swift /* Abstract: A view that can display an arbritrary DisplayableMeasurement */ import SwiftUI struct MeasurementView: View { var measurement: DisplayableMeasurement var body: some View { HStack { measurement.unitImage .foregroundStyle(.secondary) Text(measurement.localizedSummary()) } } } struct MeasurementView_Previews: PreviewProvider { static var previews: some View { MeasurementView( measurement: Measurement(value: 1.5, unit: UnitVolume.cups) ) .padding() .previewLayout(.sizeThatFits) } } ``` ## RecipeList.swift ```swift /* Abstract: A list of unlocked smoothies' recipes, and a call to action to purchase all recipes. */ import SwiftUI struct RecipeList: View { @EnvironmentObject private var model: Model var smoothies: [Smoothie] { Smoothie.all(includingPaid: model.allRecipesUnlocked) .filter { $0.matches(model.searchString) } .sorted { $0.title.localizedCompare($1.title) == .orderedAscending } } var body: some View { List { #if os(iOS) if !model.allRecipesUnlocked { Section { unlockButton .listRowInsets(EdgeInsets()) .listRowBackground(EmptyView()) .listSectionSeparator(.hidden) .listRowSeparator(.hidden) } .listSectionSeparator(.hidden) } #endif ForEach(smoothies) { smoothie in NavigationLink(tag: smoothie.id, selection: $model.selectedSmoothieID) { RecipeView(smoothie: smoothie) .environmentObject(model) } label: { SmoothieRow(smoothie: smoothie) .padding(.vertical, 5) } } } #if os(iOS) .listStyle(.insetGrouped) #elseif os(macOS) .safeAreaInset(edge: .bottom, spacing: 0) { if !model.allRecipesUnlocked { unlockButton .padding(8) } } #endif .navigationTitle(Text("Recipes", comment: "Title of the 'recipes' app section showing the list of smoothie recipes.")) .animation(.spring(response: 1, dampingFraction: 1), value: model.allRecipesUnlocked) .accessibilityRotor("Favorite Smoothies", entries: smoothies.filter { model.isFavorite(smoothie: $0) }, entryLabel: \.title) .accessibilityRotor("Smoothies", entries: smoothies, entryLabel: \.title) .searchable(text: $model.searchString) { ForEach(model.searchSuggestions) { suggestion in Text(suggestion.name).searchCompletion(suggestion.name) } } } @ViewBuilder var unlockButton: some View { Group { if let product = model.unlockAllRecipesProduct { RecipeUnlockButton( product: RecipeUnlockButton.Product(for: product), purchaseAction: { model.purchase(product: product) } ) } else { RecipeUnlockButton( product: RecipeUnlockButton.Product( title: "Unlock All Recipes", description: "Loading�", availability: .unavailable ), purchaseAction: {} ) } } .transition(.scale.combined(with: .opacity)) } } struct RecipeList_Previews: PreviewProvider { static let unlocked: Model = { let store = Model() store.allRecipesUnlocked = true return store }() static var previews: some View { Group { NavigationView { RecipeList() } .environmentObject(Model()) .previewDisplayName("Locked") NavigationView { RecipeList() } .environmentObject(unlocked) .previewDisplayName("Unlocked") } } } ``` ## RecipeUnlockButton.swift ```swift /* Abstract: A button that unlocks all recipes. */ import SwiftUI import StoreKit struct RecipeUnlockButton: View { var product: Product var purchaseAction: () -> Void @Environment(\.colorScheme) private var colorScheme var body: some View { ZStack(alignment: .bottom) { Image("smoothie/recipes-background").resizable() .aspectRatio(contentMode: .fill) #if os(iOS) .frame(height: 225) #else .frame(height: 150) #endif .accessibility(hidden: true) bottomBar } .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) .overlay { RoundedRectangle(cornerRadius: 10, style: .continuous) .strokeBorder(.quaternary, lineWidth: 0.5) } .accessibilityElement(children: .contain) } var bottomBar: some View { HStack { VStack(alignment: .leading) { Text(product.title) .font(.headline) .bold() Text(product.description) .foregroundStyle(.secondary) .font(.subheadline) } Spacer() if case let .available(displayPrice) = product.availability { Button(action: purchaseAction) { Text(displayPrice) } .buttonStyle(.purchase) .accessibility(label: Text("Buy recipe for (displayPrice)", comment: "Accessibility label for button to buy recipe for a certain price.")) } } .padding() .frame(maxWidth: .infinity) .background(.regularMaterial) .accessibilityElement(children: .combine) } } extension RecipeUnlockButton { struct Product { var title: LocalizedStringKey var description: LocalizedStringKey var availability: Availability } enum Availability { case available(displayPrice: String) case unavailable } } extension RecipeUnlockButton.Product { init(for product: StoreKit.Product) { title = LocalizedStringKey(product.displayName) description = LocalizedStringKey(product.description) availability = .available(displayPrice: product.displayPrice) } } // MARK: - Previews struct RecipeUnlockButton_Previews: PreviewProvider { static let availableProduct = RecipeUnlockButton.Product( title: "Unlock All Recipes", description: "Make smoothies at home!", availability: .available(displayPrice: "$4.99") ) static let unavailableProduct = RecipeUnlockButton.Product( title: "Unlock All Recipes", description: "Loading�", availability: .unavailable ) static var previews: some View { Group { RecipeUnlockButton(product: availableProduct, purchaseAction: {}) RecipeUnlockButton(product: unavailableProduct, purchaseAction: {}) } .frame(width: 300) .previewLayout(.sizeThatFits) } } ``` ## RecipeView.swift ```swift /* Abstract: A view that displays the recipe for a smoothie. */ import SwiftUI struct RecipeView: View { var smoothie: Smoothie @EnvironmentObject private var model: Model @State private var smoothieCount = 1 var backgroundColor: Color { #if os(iOS) return Color(uiColor: .secondarySystemBackground) #else return Color(nsColor: .textBackgroundColor) #endif } let shape = RoundedRectangle(cornerRadius: 24, style: .continuous) var recipeToolbar: some View { StepperView( value: $smoothieCount, label: "(smoothieCount) Smoothies", configuration: StepperView.Configuration(increment: 1, minValue: 1, maxValue: 9) ) .frame(maxWidth: .infinity) .padding(20) } var body: some View { ScrollView { VStack(alignment: .leading) { smoothie.image .resizable() .aspectRatio(contentMode: .fill) .frame(maxHeight: 300) .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous)) .overlay { RoundedRectangle(cornerRadius: 24, style: .continuous) .strokeBorder(.quaternary, lineWidth: 0.5) } .overlay(alignment: .bottom) { recipeToolbar } VStack(alignment: .leading) { Text("Ingredients.recipe", tableName: "Ingredients", comment: "Ingredients in a recipe. For languages that have different words for \"Ingredient\" based on semantic context.") .font(Font.title).bold() .foregroundStyle(.secondary) VStack { ForEach(0 ..< smoothie.measuredIngredients.count, id: \.self) { index in RecipeIngredientRow(measuredIngredient: smoothie.measuredIngredients[index].scaled(by: Double(smoothieCount))) .padding(.horizontal) if index < smoothie.measuredIngredients.count - 1 { Divider() } } } .padding(.vertical) .background() .clipShape(shape) .overlay { shape.strokeBorder(.quaternary, lineWidth: 0.5) } } } .padding() .frame(minWidth: 200, idealWidth: 400, maxWidth: 400) .frame(maxWidth: .infinity) } .background { backgroundColor.ignoresSafeArea() } .navigationTitle(smoothie.title) .toolbar { SmoothieFavoriteButton().environmentObject(model) } } } struct RecipeIngredientRow: View { var measuredIngredient: MeasuredIngredient @State private var checked = false var body: some View { Button(action: { checked.toggle() }) { HStack { measuredIngredient.ingredient.image .resizable() .aspectRatio(contentMode: .fill) .scaleEffect(measuredIngredient.ingredient.thumbnailCrop.scale * 1.25) .frame(width: 60, height: 60) .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) VStack(alignment: .leading, spacing: 4) { Text(measuredIngredient.ingredient.name).font(.headline) MeasurementView(measurement: measuredIngredient.measurement) } Spacer() Toggle(isOn: $checked) { Text("Complete", comment: "Label for toggle showing whether you have completed adding an ingredient that's part of a smoothie recipe") } } .contentShape(Rectangle()) } .buttonStyle(.plain) .toggleStyle(.circle) } } struct RecipeView_Previews: PreviewProvider { static var previews: some View { RecipeView(smoothie: .thatsBerryBananas) .environmentObject(Model()) } } ``` ## FavoriteSmoothies.swift ```swift /* Abstract: The favorites tab or content list that includes smoothies marked as favorites. */ import SwiftUI struct FavoriteSmoothies: View { @EnvironmentObject private var model: Model var favoriteSmoothies: [Smoothie] { model.favoriteSmoothieIDs.map { Smoothie(for: $0)! } } var body: some View { SmoothieList(smoothies: favoriteSmoothies) .overlay { if model.favoriteSmoothieIDs.isEmpty { Text("Add some smoothies to your favorites!", comment: "Placeholder text shown in list of smoothies when no favorite smoothies have been added yet") .foregroundStyle(.secondary) .frame(maxWidth: .infinity, maxHeight: .infinity) .background() .ignoresSafeArea() } } .navigationTitle(Text("Favorites", comment: "Title of the 'favorites' app section showing the list of favorite smoothies")) .environmentObject(model) } } struct FavoriteSmoothies_Previews: PreviewProvider { static var previews: some View { FavoriteSmoothies() .environmentObject(Model()) } } ``` ## RedeemSmoothieButton.swift ```swift /* Abstract: A button for redeeming free smoothies. */ import SwiftUI struct RedeemSmoothieButton: View { var action: () -> Void var height: Double { #if os(macOS) return 30 #else return 45 #endif } var body: some View { Button(action: action) { Text("Redeem Free Smoothie!", comment: "Button to redeem a free smoothie") .font(Font.headline.bold()) .frame(height: height) .frame(minWidth: 100, maxWidth: 400) .foregroundStyle(.white) .background { Color.accentColor } .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) .contentShape(Rectangle()) } .buttonStyle(.squishable) } } struct RedeemSmoothieButton_Previews: PreviewProvider { static var previews: some View { RedeemSmoothieButton(action: {}) .frame(width: 300) .padding() .previewLayout(.sizeThatFits) } } ``` ## Smoothie+SwiftUI.swift ```swift /* Abstract: An extension for the smoothie model that offers an image property for ease of use. */ import SwiftUI // MARK: - SwiftUI.Image extension Smoothie { var image: Image { Image("smoothie/(id)", label: Text(title)) .renderingMode(.original) } } ``` ## Smoothie.swift ```swift /* Abstract: A model that represents a smoothie � including its descriptive information and ingredients (and nutrition facts). */ import Foundation struct Smoothie: Identifiable, Codable { var id: String var title: String var description: AttributedString var measuredIngredients: [MeasuredIngredient] } extension Smoothie { init?(for id: Smoothie.ID) { guard let smoothie = Smoothie.all().first(where: { $0.id == id }) else { return nil } self = smoothie } var kilocalories: Int { let value = measuredIngredients.reduce(0) { total, ingredient in total + ingredient.kilocalories } return Int(round(Double(value) / 10.0) * 10) } var energy: Measurement<UnitEnergy> { return Measurement<UnitEnergy>(value: Double(kilocalories), unit: .kilocalories) } // The nutritional information for the combined ingredients var nutritionFact: NutritionFact { let facts = measuredIngredients.compactMap { $0.nutritionFact } guard let firstFact = facts.first else { print("Could not find nutrition facts for (title) � using `banana`'s nutrition facts.") return .banana } return facts.dropFirst().reduce(firstFact, +) } var menuIngredients: [MeasuredIngredient] { measuredIngredients.filter { $0.id != Ingredient.water.id } } func matches(_ string: String) -> Bool { string.isEmpty || title.localizedCaseInsensitiveContains(string) || menuIngredients.contains { $0.ingredient.name.localizedCaseInsensitiveContains(string) } } } extension Smoothie: Hashable { static func == (lhs: Smoothie, rhs: Smoothie) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } } // MARK: - Smoothie List extension Smoothie { @SmoothieArrayBuilder static func all(includingPaid: Bool = true) -> [Smoothie] { Smoothie(id: "berry-blue", title: String(localized: "Berry Blue", comment: "Smoothie name")) { AttributedString(localized: "*Filling* and *refreshing*, this smoothie will fill you with joy!", comment: "Berry Blue smoothie description") Ingredient.orange.measured(with: .cups).scaled(by: 1.5) Ingredient.blueberry.measured(with: .cups) Ingredient.avocado.measured(with: .cups).scaled(by: 0.2) } Smoothie(id: "carrot-chops", title: String(localized: "Carrot Chops", comment: "Smoothie name")) { AttributedString(localized: "*Packed* with vitamin A and C, Carrot Chops is a great way to start your day!", comment: "Carrot Chops smoothie description") Ingredient.orange.measured(with: .cups).scaled(by: 1.5) Ingredient.carrot.measured(with: .cups).scaled(by: 0.5) Ingredient.mango.measured(with: .cups).scaled(by: 0.5) } if includingPaid { Smoothie(id: "pina-y-coco", title: String(localized: "Pi�a y Coco", comment: "Smoothie name")) { AttributedString(localized: "Enjoy the *tropical* flavors of coconut and pineapple!", comment: "Pi�a y Coco smoothie description") Ingredient.pineapple.measured(with: .cups).scaled(by: 1.5) Ingredient.almondMilk.measured(with: .cups) Ingredient.coconut.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "hulking-lemonade", title: String(localized: "Hulking Lemonade", comment: "Smoothie name")) { AttributedString(localized: "This is not just *any* lemonade. It will give you *powers* you'll struggle to control!", comment: "Hulking Lemonade smoothie description") Ingredient.lemon.measured(with: .cups).scaled(by: 1.5) Ingredient.spinach.measured(with: .cups) Ingredient.avocado.measured(with: .cups).scaled(by: 0.2) Ingredient.water.measured(with: .cups).scaled(by: 0.2) } Smoothie(id: "kiwi-cutie", title: String(localized: "Kiwi Cutie", comment: "Smoothie name")) { AttributedString(localized: "Kiwi Cutie is beautiful *inside* ***and*** *out*! Packed with nutrients to start your day!", comment: "Kiwi Cutie smoothie description") Ingredient.kiwi.measured(with: .cups) Ingredient.orange.measured(with: .cups) Ingredient.spinach.measured(with: .cups) } Smoothie( id: "lemonberry", title: String(localized: "Lemonberry", comment: "Smoothie name")) { AttributedString(localized: "A refreshing blend that's a *real kick*!", comment: "Lemonberry smoothie description") Ingredient.raspberry.measured(with: .cups) Ingredient.strawberry.measured(with: .cups) Ingredient.lemon.measured(with: .cups).scaled(by: 0.5) Ingredient.water.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "love-you-berry-much", title: String(localized: "Love You Berry Much", comment: "Smoothie name")) { AttributedString(localized: "If you *love* berries berry berry much, you will love this one!", comment: "Love You Berry Much smoothie description") Ingredient.strawberry.measured(with: .cups).scaled(by: 0.75) Ingredient.blueberry.measured(with: .cups).scaled(by: 0.5) Ingredient.raspberry.measured(with: .cups).scaled(by: 0.5) Ingredient.water.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "mango-jambo", title: String(localized: "Mango Jambo", comment: "Smoothie name")) { AttributedString(localized: "Dance around with this *delicious* tropical blend!", comment: "Mango Jambo smoothie description") Ingredient.mango.measured(with: .cups) Ingredient.pineapple.measured(with: .cups).scaled(by: 0.5) Ingredient.water.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "one-in-a-melon", title: String(localized: "One in a Melon", comment: "Smoothie name")) { AttributedString(localized: "Feel special this summer with the *coolest* drink in our menu!", comment: "One in a Melon smoothie description") Ingredient.watermelon.measured(with: .cups).scaled(by: 2) Ingredient.raspberry.measured(with: .cups) Ingredient.water.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "papas-papaya", title: String(localized: "Papa's Papaya", comment: "Smoothie name")) { AttributedString(localized: "Papa would be proud of you if he saw you drinking this!", comment: "Papa's Papaya smoothie description") Ingredient.orange.measured(with: .cups) Ingredient.mango.measured(with: .cups).scaled(by: 0.5) Ingredient.papaya.measured(with: .cups).scaled(by: 0.5) } Smoothie(id: "peanut-butter-cup", title: String(localized: "Peanut Butter Cup", comment: "Smoothie name")) { AttributedString(localized: "Ever wondered what it was like to *drink a peanut butter cup*? Wonder no more!", comment: "Peanut Butter Cup smoothie description") Ingredient.almondMilk.measured(with: .cups) Ingredient.banana.measured(with: .cups).scaled(by: 0.5) Ingredient.chocolate.measured(with: .tablespoons).scaled(by: 2) Ingredient.peanutButter.measured(with: .tablespoons) } Smoothie(id: "sailor-man", title: String(localized: "Sailor Man", comment: "Smoothie name")) { AttributedString(localized: "*Get strong* with this delicious spinach smoothie!", comment: "Sailor Man smoothie description") Ingredient.orange.measured(with: .cups).scaled(by: 1.5) Ingredient.spinach.measured(with: .cups) } Smoothie(id: "thats-a-smore", title: String(localized: "That's a Smore!", comment: "Smoothie name")) { AttributedString(localized: "When the world seems to rock like you've had too much choc, that's *a smore*!", comment: "That's a Smore! smoothie description") Ingredient.almondMilk.measured(with: .cups) Ingredient.coconut.measured(with: .cups).scaled(by: 0.5) Ingredient.chocolate.measured(with: .tablespoons) } } Smoothie(id: "thats-berry-bananas", title: String(localized: "That's Berry Bananas!", comment: "Smoothie name")) { AttributedString(localized: "You'll go *crazy* with this classic!", comment: "That's Berry Bananas! smoothie description") Ingredient.almondMilk.measured(with: .cups) Ingredient.banana.measured(with: .cups) Ingredient.strawberry.measured(with: .cups) } if includingPaid { Smoothie(id: "tropical-blue", title: String(localized: "Tropical Blue", comment: "Smoothie name")) { AttributedString( localized: "A delicious blend of *tropical fruits and blueberries* will have you sambaing around like you never knew you could!", comment: "Tropical Blue smoothie description") Ingredient.almondMilk.measured(with: .cups) Ingredient.banana.measured(with: .cups).scaled(by: 0.5) Ingredient.blueberry.measured(with: .cups).scaled(by: 0.5) Ingredient.mango.measured(with: .cups).scaled(by: 0.5) } } } // Used in previews. static var berryBlue: Smoothie { Smoothie(for: "berry-blue")! } static var kiwiCutie: Smoothie { Smoothie(for: "kiwi-cutie")! } static var hulkingLemonade: Smoothie { Smoothie(for: "hulking-lemonade")! } static var mangoJambo: Smoothie { Smoothie(for: "mango-jambo")! } static var tropicalBlue: Smoothie { Smoothie(for: "tropical-blue")! } static var lemonberry: Smoothie { Smoothie(for: "lemonberry")! } static var oneInAMelon: Smoothie { Smoothie(for: "one-in-a-melon")! } static var thatsASmore: Smoothie { Smoothie(for: "thats-a-smore")! } static var thatsBerryBananas: Smoothie { Smoothie(for: "thats-berry-bananas")! } } extension Smoothie { init(id: Smoothie.ID, title: String, @SmoothieBuilder _ makeIngredients: () -> (AttributedString, [MeasuredIngredient])) { let (description, ingredients) = makeIngredients() self.init(id: id, title: title, description: description, measuredIngredients: ingredients) } } @resultBuilder enum SmoothieBuilder { static func buildBlock(_ description: AttributedString, _ ingredients: MeasuredIngredient...) -> (AttributedString, [MeasuredIngredient]) { return (description, ingredients) } @available(*, unavailable, message: "first statement of SmoothieBuilder must be its description String") static func buildBlock(_ ingredients: MeasuredIngredient...) -> (String, [MeasuredIngredient]) { fatalError() } } @resultBuilder enum SmoothieArrayBuilder { static func buildEither(first component: [Smoothie]) -> [Smoothie] { return component } static func buildEither(second component: [Smoothie]) -> [Smoothie] { return component } static func buildOptional(_ component: [Smoothie]?) -> [Smoothie] { return component ?? [] } static func buildExpression(_ expression: Smoothie) -> [Smoothie] { return [expression] } static func buildExpression(_ expression: ()) -> [Smoothie] { return [] } static func buildBlock(_ smoothies: [Smoothie]...) -> [Smoothie] { return smoothies.flatMap { $0 } } } ``` ## SmoothieCommands.swift ```swift /* Abstract: Custom commands that you add to the application's Main Menu. */ import SwiftUI struct SmoothieCommands: Commands { let model: Model var body: some Commands { CommandMenu(Text("Smoothie", comment: "Menu title for smoothie-related actions")) { SmoothieFavoriteButton().environmentObject(model) .keyboardShortcut("+", modifiers: [.option, .command]) } } } ``` ## SmoothieFavoriteButton.swift ```swift /* Abstract: A button to favorite a smoothie, can be placed in a toolbar. */ import SwiftUI struct SmoothieFavoriteButton: View { @EnvironmentObject private var model: Model var isFavorite: Bool { guard let smoothieID = model.selectedSmoothieID else { return false } return model.favoriteSmoothieIDs.contains(smoothieID) } var body: some View { Button(action: toggleFavorite) { if isFavorite { Label { Text("Remove from Favorites", comment: "Toolbar button/menu item to remove a smoothie from favorites") } icon: { Image(systemName: "heart.fill") } } else { Label { Text("Add to Favorites", comment: "Toolbar button/menu item to add a smoothie to favorites") } icon: { Image(systemName: "heart") } } } .disabled(model.selectedSmoothieID == nil) } func toggleFavorite() { guard let smoothieID = model.selectedSmoothieID else { return } model.toggleFavorite(smoothieID: smoothieID) } } struct SmoothieFavoriteButton_Previews: PreviewProvider { static var previews: some View { SmoothieFavoriteButton() .padding() .previewLayout(.sizeThatFits) .environmentObject(Model()) } } ``` ## SmoothieHeaderView.swift ```swift /* Abstract: The view that summarizes the smoothie and adjusts its layout based on the environment and platform. */ import SwiftUI struct SmoothieHeaderView: View { var smoothie: Smoothie #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass #endif var horizontallyConstrained: Bool { #if os(iOS) return horizontalSizeClass == .compact #else return false #endif } var body: some View { Group { if horizontallyConstrained { fullBleedContent } else { wideContent } } .accessibilityElement(children: .combine) } var fullBleedContent: some View { VStack(spacing: 0) { smoothie.image .resizable() .aspectRatio(contentMode: .fill) .accessibility(hidden: true) VStack(alignment: .leading) { Text(smoothie.description) Text(smoothie.energy.formatted(.measurement(width: .wide, usage: .food))) .font(.subheadline) .foregroundStyle(.secondary) } .padding() .frame(maxWidth: .infinity, alignment: .leading) .background() } } var wideClipShape = RoundedRectangle(cornerRadius: 20, style: .continuous) var wideContent: some View { HStack(spacing: 0) { VStack(alignment: .leading, spacing: 4) { #if os(macOS) Text(smoothie.title) .font(Font.largeTitle.bold()) #endif Text(smoothie.description) .font(.title2) Spacer() Text(smoothie.energy.formatted(.measurement(width: .wide, usage: .asProvided))) .foregroundStyle(.secondary) .font(.headline) } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) .background() smoothie.image .resizable() .aspectRatio(contentMode: .fill) .frame(width: 220, height: 250) .clipped() .accessibility(hidden: true) } .frame(height: 250) .clipShape(wideClipShape) .overlay { wideClipShape.strokeBorder(.quaternary, lineWidth: 0.5) } .padding() } } struct SmoothieHeaderView_Previews: PreviewProvider { static var previews: some View { SmoothieHeaderView(smoothie: .berryBlue) } } ``` ## SmoothieList.swift ```swift /* Abstract: A reusable view that can display a list of arbritary smoothies. */ import SwiftUI struct SmoothieList: View { var smoothies: [Smoothie] @EnvironmentObject private var model: Model var listedSmoothies: [Smoothie] { smoothies .filter { $0.matches(model.searchString) } .sorted(by: { $0.title.localizedCompare($1.title) == .orderedAscending }) } var body: some View { ScrollViewReader { proxy in List { ForEach(listedSmoothies) { smoothie in NavigationLink(tag: smoothie.id, selection: $model.selectedSmoothieID) { SmoothieView(smoothie: smoothie) } label: { SmoothieRow(smoothie: smoothie) } .onChange(of: model.selectedSmoothieID) { newValue in // Need to make sure the Smoothie exists. guard let smoothieID = newValue, let smoothie = Smoothie(for: smoothieID) else { return } proxy.scrollTo(smoothie.id) model.selectedSmoothieID = smoothie.id } .swipeActions { Button { withAnimation { model.toggleFavorite(smoothieID: smoothie.id) } } label: { Label { Text("Favorite", comment: "Swipe action button in smoothie list") } icon: { Image(systemName: "heart") } } .tint(.accentColor) } } } .accessibilityRotor("Smoothies", entries: smoothies, entryLabel: \.title) .accessibilityRotor("Favorite Smoothies", entries: smoothies.filter { model.isFavorite(smoothie: $0) }, entryLabel: \.title) .searchable(text: $model.searchString) { ForEach(model.searchSuggestions) { suggestion in Text(suggestion.name).searchCompletion(suggestion.name) } } } } } struct SmoothieList_Previews: PreviewProvider { static var previews: some View { ForEach([ColorScheme.light, .dark], id: \.self) { scheme in NavigationView { SmoothieList(smoothies: Smoothie.all()) .navigationTitle(Text("Smoothies", comment: "Navigation title for the full list of smoothies")) .environmentObject(Model()) } .preferredColorScheme(scheme) } } } ``` ## SmoothieMenu.swift ```swift /* Abstract: The menu tab or content list that includes all smoothies. */ import SwiftUI struct SmoothieMenu: View { var body: some View { SmoothieList(smoothies: Smoothie.all()) .navigationTitle(Text("Menu", comment: "Title of the 'menu' app section showing the menu of available smoothies")) } } struct SmoothieMenu_Previews: PreviewProvider { static var previews: some View { SmoothieMenu() .environmentObject(Model()) } } ``` ## SmoothieRow.swift ```swift /* Abstract: A row used by SmoothieList that adjusts its layout based on environment and platform */ import SwiftUI struct SmoothieRow: View { var smoothie: Smoothie @EnvironmentObject private var model: Model var body: some View { HStack(alignment: .top) { let imageClipShape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) smoothie.image .resizable() .aspectRatio(contentMode: .fill) .frame(width: 60, height: 60) .clipShape(imageClipShape) .overlay(imageClipShape.strokeBorder(.quaternary, lineWidth: 0.5)) .accessibility(hidden: true) VStack(alignment: .leading) { Text(smoothie.title) .font(.headline) Text(listedIngredients) .lineLimit(2) .accessibility(label: Text("Ingredients: (listedIngredients).", comment: "Accessibility label containing the full list of smoothie ingredients")) Text(smoothie.energy.formatted(.measurement(width: .wide, usage: .food))) .foregroundStyle(.secondary) .lineLimit(1) } Spacer(minLength: 0) } .font(.subheadline) .accessibilityElement(children: .combine) } var listedIngredients: String { guard !smoothie.menuIngredients.isEmpty else { return "" } var list = [String]() list.append(smoothie.menuIngredients.first!.ingredient.name.localizedCapitalized) list += smoothie.menuIngredients.dropFirst().map { $0.ingredient.name.localizedLowercase } return ListFormatter.localizedString(byJoining: list) } var cornerRadius: Double { #if os(iOS) return 10 #else return 4 #endif } } // MARK: - Previews struct SmoothieRow_Previews: PreviewProvider { static var previews: some View { Group { SmoothieRow(smoothie: .lemonberry) SmoothieRow(smoothie: .thatsASmore) } .frame(width: 250, alignment: .leading) .padding(.horizontal) .previewLayout(.sizeThatFits) .environmentObject(Model()) } } ``` ## SmoothieView.swift ```swift /* Abstract: The smoothie detail view that offers the smoothie for sale and lists its ingredients. */ import SwiftUI #if APPCLIP import StoreKit #endif struct SmoothieView: View { var smoothie: Smoothie @State private var presentingOrderPlacedSheet = false @State private var presentingSecurityAlert = false @EnvironmentObject private var model: Model @Environment(\.colorScheme) private var colorScheme @State private var selectedIngredientID: Ingredient.ID? @State private var topmostIngredientID: Ingredient.ID? @Namespace private var namespace #if APPCLIP @State private var presentingAppStoreOverlay = false #endif var body: some View { container #if os(macOS) .frame(minWidth: 500, idealWidth: 700, maxWidth: .infinity, minHeight: 400, maxHeight: .infinity) #endif .background() .navigationTitle(smoothie.title) .toolbar { SmoothieFavoriteButton() .environmentObject(model) } .sheet(isPresented: $presentingOrderPlacedSheet) { OrderPlacedView() #if os(macOS) .clipped() .toolbar { ToolbarItem(placement: .confirmationAction) { Button(action: { presentingOrderPlacedSheet = false }) { Text("Done", comment: "Button to dismiss the confirmation sheet after placing an order") } } } #else .overlay(alignment: .topTrailing) { Button { presentingOrderPlacedSheet = false } label: { Text("Done", comment: "Button to dismiss the confirmation sheet after placing an order") } .font(.body.bold()) .buttonStyle(.capsule) .keyboardShortcut(.defaultAction) .padding() } #endif } .alert(isPresented: $presentingSecurityAlert) { Alert( title: Text("Payments Disabled", comment: "Title of alert dialog when payments are disabled"), message: Text("The Fruta QR code was scanned too far from the shop, payments are disabled for your protection.", comment: "Explanatory text of alert dialog when payments are disabled"), dismissButton: .default(Text("OK", comment: "OK button of alert dialog when payments are disabled")) ) } } var container: some View { ZStack { ScrollView { content #if os(macOS) .frame(maxWidth: 600) .frame(maxWidth: .infinity) #endif } .safeAreaInset(edge: .bottom, spacing: 0) { bottomBar } .accessibility(hidden: selectedIngredientID != nil) if selectedIngredientID != nil { Rectangle().fill(.regularMaterial).ignoresSafeArea() } ForEach(smoothie.menuIngredients) { measuredIngredient in let presenting = selectedIngredientID == measuredIngredient.id IngredientCard(ingredient: measuredIngredient.ingredient, presenting: presenting, closeAction: deselectIngredient) .matchedGeometryEffect(id: measuredIngredient.id, in: namespace, isSource: presenting) .aspectRatio(0.75, contentMode: .fit) .shadow(color: Color.black.opacity(presenting ? 0.2 : 0), radius: 20, y: 10) .padding(20) .opacity(presenting ? 1 : 0) .zIndex(topmostIngredientID == measuredIngredient.id ? 1 : 0) .accessibilityElement(children: .contain) .accessibility(sortPriority: presenting ? 1 : 0) .accessibility(hidden: !presenting) } } } var content: some View { VStack(spacing: 0) { SmoothieHeaderView(smoothie: smoothie) VStack(alignment: .leading) { Text("Ingredients.menu", tableName: "Ingredients", comment: "Ingredients in a smoothie. For languages that have different words for \"Ingredient\" based on semantic context.") .font(Font.title).bold() .foregroundStyle(.secondary) LazyVGrid(columns: [GridItem(.adaptive(minimum: 130), spacing: 16, alignment: .top)], alignment: .center, spacing: 16) { ForEach(smoothie.menuIngredients) { measuredIngredient in let ingredient = measuredIngredient.ingredient let presenting = selectedIngredientID == measuredIngredient.id Button(action: { select(ingredient: ingredient) }) { IngredientGraphic(ingredient: measuredIngredient.ingredient, style: presenting ? .cardFront : .thumbnail) .matchedGeometryEffect( id: measuredIngredient.id, in: namespace, isSource: !presenting ) .contentShape(Rectangle()) } .buttonStyle(.squishable(fadeOnPress: false)) .aspectRatio(1, contentMode: .fit) .zIndex(topmostIngredientID == measuredIngredient.id ? 1 : 0) .accessibility(label: Text("(ingredient.name) Ingredient", comment: "Accessibility label for collapsed ingredient card in smoothie overview")) } } } .padding() } } var bottomBar: some View { VStack(spacing: 0) { Divider() Group { if let account = model.account, account.canRedeemFreeSmoothie { RedeemSmoothieButton(action: redeemSmoothie) } else { PaymentButton(action: orderSmoothie) } } .padding(.horizontal, 40) .padding(.vertical, 16) } .background(.bar) } func orderSmoothie() { guard model.isApplePayEnabled else { presentingSecurityAlert = true return } model.orderSmoothie(smoothie) presentingOrderPlacedSheet = true } func redeemSmoothie() { model.redeemSmoothie(smoothie) presentingOrderPlacedSheet = true } func select(ingredient: Ingredient) { topmostIngredientID = ingredient.id withAnimation(.openCard) { selectedIngredientID = ingredient.id } } func deselectIngredient() { withAnimation(.closeCard) { selectedIngredientID = nil } } } struct SmoothieView_Previews: PreviewProvider { static var previews: some View { Group { NavigationView { SmoothieView(smoothie: .berryBlue) } ForEach([Smoothie.thatsBerryBananas, .oneInAMelon, .berryBlue]) { smoothie in SmoothieView(smoothie: smoothie) .previewLayout(.sizeThatFits) .frame(height: 700) } } .environmentObject(Model()) } } ``` ## Animations.swift ```swift /* Abstract: Reusable animations for certain aspects of the app like opening, closing, and flipping cards. */ import SwiftUI extension Animation { static let openCard = Animation.spring(response: 0.45, dampingFraction: 0.9) static let closeCard = Animation.spring(response: 0.35, dampingFraction: 1) static let flipCard = Animation.spring(response: 0.35, dampingFraction: 0.7) } ``` ## CapsuleButtonStyle.swift ```swift /* Abstract: A button style that displays over a capsule background. */ import SwiftUI struct CapsuleButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .dynamicTypeSize(.large) .padding(.horizontal, 15) .padding(.vertical, 8) .background(in: Capsule()) .foregroundStyle(Color.accentColor) .contentShape(Capsule()) #if os(iOS) .hoverEffect(.lift) #endif } } extension ButtonStyle where Self == CapsuleButtonStyle { static var capsule: CapsuleButtonStyle { CapsuleButtonStyle() } } ``` ## CircleToggleStyle.swift ```swift /* Abstract: A toggle style that uses system checkmark images to represent the On state. */ import SwiftUI struct CircleToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { ZStack { configuration.label.hidden() Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle") .accessibility(label: configuration.isOn ? Text("Checked", comment: "Accessibility label for circular style toggle that is checked (on)") : Text("Unchecked", comment: "Accessibility label for circular style toggle that is unchecked (off)")) .foregroundStyle(configuration.isOn ? Color.accentColor : .secondary) .imageScale(.large) .font(Font.title) } } } extension ToggleStyle where Self == CircleToggleStyle { static var circle: CircleToggleStyle { CircleToggleStyle() } } ``` ## PurchaseButtonStyle.swift ```swift /* Abstract: A high contrast button style for initiating purchases. */ import SwiftUI struct PurchaseButtonStyle: ButtonStyle { @Environment(\.colorScheme) private var colorScheme var foregroundColor: Color { colorScheme == .dark ? .black : .white } var backgroundColor: Color { colorScheme == .dark ? .white : .black } var minWidth: Double { #if os(iOS) return 80 #else return 60 #endif } func makeBody(configuration: Configuration) -> some View { configuration.label .font(.subheadline.bold()) .foregroundStyle(foregroundColor) .padding(.horizontal, 16) .padding(.vertical, 8) .frame(minWidth: minWidth) .background(backgroundColor, in: Capsule()) .contentShape(Capsule()) } } extension ButtonStyle where Self == PurchaseButtonStyle { static var purchase: PurchaseButtonStyle { PurchaseButtonStyle() } } ``` ## SquishableButtonStyle.swift ```swift /* Abstract: A button style that squishes its content and optionally slightly fades it out when pressed */ import SwiftUI struct SquishableButtonStyle: ButtonStyle { var fadeOnPress = true func makeBody(configuration: Configuration) -> some View { configuration.label .opacity(configuration.isPressed && fadeOnPress ? 0.75 : 1) .scaleEffect(configuration.isPressed ? 0.95 : 1) } } extension ButtonStyle where Self == SquishableButtonStyle { static var squishable: SquishableButtonStyle { SquishableButtonStyle() } static func squishable(fadeOnPress: Bool = true) -> SquishableButtonStyle { SquishableButtonStyle(fadeOnPress: fadeOnPress) } } ``` ## FeaturedSmoothieWidget.swift ```swift /* Abstract: A widget that highlights featured smoothies. */ import WidgetKit import SwiftUI import Intents struct FeaturedSmoothieWidget: Widget { var supportedFamilies: [WidgetFamily] { #if os(iOS) return [.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge] #else return [.systemSmall, .systemMedium, .systemLarge] #endif } var body: some WidgetConfiguration { StaticConfiguration(kind: "FeaturedSmoothie", provider: Provider()) { entry in FeaturedSmoothieEntryView(entry: entry) } .configurationDisplayName(Text("Featured Smoothie", comment: "The name shown for the widget when the user adds or edits it")) .description(Text("Displays the latest featured smoothie!", comment: "Description shown for the widget when the user adds or edits it")) .supportedFamilies(supportedFamilies) } } extension FeaturedSmoothieWidget { struct Provider: TimelineProvider { typealias Entry = FeaturedSmoothieWidget.Entry func placeholder(in context: Context) -> Entry { Entry(date: Date(), smoothie: .berryBlue) } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { let entry = Entry(date: Date(), smoothie: .berryBlue) completion(entry) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { var entries: [Entry] = [] let currentDate = Date() let smoothies = [Smoothie.berryBlue, .kiwiCutie, .hulkingLemonade, .lemonberry, .mangoJambo, .tropicalBlue] for index in 0..<smoothies.count { let entryDate = Calendar.current.date(byAdding: .hour, value: index, to: currentDate)! let entry = Entry(date: entryDate, smoothie: smoothies[index]) entries.append(entry) } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } } } extension FeaturedSmoothieWidget { struct Entry: TimelineEntry { var date: Date var smoothie: Smoothie } } struct FeaturedSmoothieEntryView: View { var entry: FeaturedSmoothieWidget.Provider.Entry @Environment(\.widgetFamily) private var widgetFamily var title: some View { Text(entry.smoothie.title) .font(widgetFamily == .systemSmall ? Font.body.bold() : Font.title3.bold()) .lineLimit(1) .minimumScaleFactor(0.1) } var description: some View { Text(entry.smoothie.description) .font(.subheadline) } var calories: some View { Text(entry.smoothie.energy.formatted(.measurement(width: .wide, usage: .food))) .foregroundStyle(.secondary) .font(.subheadline) } var image: some View { Rectangle() .overlay { entry.smoothie.image .resizable() .aspectRatio(contentMode: .fill) } .aspectRatio(1, contentMode: .fit) .clipShape(ContainerRelativeShape()) } var body: some View { ZStack { if widgetFamily == .systemMedium { HStack(alignment: .top, spacing: 20) { VStack(alignment: .leading) { title description calories } .frame(maxWidth: .infinity, alignment: .leading) .accessibilityElement(children: .combine) image } .padding() } else { VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading) { title if widgetFamily == .systemLarge { description calories } } .accessibilityElement(children: .combine) image .frame(maxWidth: .infinity, alignment: .bottomTrailing) } .padding() } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background { BubbleBackground() } } } struct FeaturedSmoothieWidget_Previews: PreviewProvider { static var previews: some View { Group { FeaturedSmoothieEntryView(entry: FeaturedSmoothieWidget.Entry(date: Date(), smoothie: .berryBlue)) .previewContext(WidgetPreviewContext(family: .systemSmall)) .redacted(reason: .placeholder) FeaturedSmoothieEntryView(entry: FeaturedSmoothieWidget.Entry(date: Date(), smoothie: .kiwiCutie)) .previewContext(WidgetPreviewContext(family: .systemMedium)) FeaturedSmoothieEntryView(entry: FeaturedSmoothieWidget.Entry(date: Date(), smoothie: .thatsBerryBananas)) .previewContext(WidgetPreviewContext(family: .systemLarge)) } } } ``` ## FrutaWidgets.swift ```swift /* Abstract: A bundle of widgets for the Fruta app. */ import WidgetKit import SwiftUI @main struct FrutaWidgets: WidgetBundle { var body: some Widget { FeaturedSmoothieWidget() RewardsCardWidget() } } ``` ## RewardsCardWidget.swift ```swift /* Abstract: A widget that displays the rewards card, showing progress towards the next free smoothie. */ import WidgetKit import SwiftUI struct RewardsCardWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "RewardsCard", provider: Provider()) { entry in RewardsCardEntryView(entry: entry) } .configurationDisplayName(Text("Rewards Card", comment: "The name shown for the widget when the user adds or edits it")) .description(Text("See your progress towards your next free smoothie!", comment: "Description shown for the widget when the user adds or edits it")) .supportedFamilies([.systemMedium, .systemLarge]) } } extension RewardsCardWidget { struct Provider: TimelineProvider { typealias Entry = RewardsCardWidget.Entry func placeholder(in context: Context) -> Entry { Entry(date: Date(), points: 4) } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { completion(Entry(date: Date(), points: 4)) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { let entry = Entry(date: Date(), points: 4) let timeline = Timeline(entries: [entry], policy: .never) completion(timeline) } } } extension RewardsCardWidget { struct Entry: TimelineEntry { var date: Date var points: Int } } public struct RewardsCardEntryView: View { var entry: RewardsCardWidget.Entry @Environment(\.widgetFamily) private var family var compact: Bool { family != .systemLarge } public var body: some View { ZStack { BubbleBackground() RewardsCard(totalStamps: entry.points, hasAccount: true, compact: compact) } } } struct RewardsCardWidget_Previews: PreviewProvider { static var previews: some View { Group { RewardsCardEntryView(entry: .init(date: Date(), points: 4)) .previewContext(WidgetPreviewContext(family: .systemMedium)) .redacted(reason: .placeholder) RewardsCardEntryView(entry: .init(date: Date(), points: 8)) .previewContext(WidgetPreviewContext(family: .systemMedium)) RewardsCardEntryView(entry: .init(date: Date(), points: 2)) .previewContext(WidgetPreviewContext(family: .systemLarge)) } } } ``` ## AppTabNavigation.swift ```swift /* Abstract: Tab based app structure. */ import SwiftUI struct AppTabNavigation: View { enum Tab { case menu case favorites case rewards case recipes } @State private var selection: Tab = .menu var body: some View { TabView(selection: $selection) { NavigationView { SmoothieMenu() } .tabItem { let menuText = Text("Menu", comment: "Smoothie menu tab title") Label { menuText } icon: { Image(systemName: "list.bullet") }.accessibility(label: menuText) } .tag(Tab.menu) NavigationView { FavoriteSmoothies() } .tabItem { Label { Text("Favorites", comment: "Favorite smoothies tab title") } icon: { Image(systemName: "heart.fill") } } .tag(Tab.favorites) #if EXTENDED_ALL NavigationView { RewardsView() } .tabItem { Label { Text("Rewards", comment: "Smoothie rewards tab title") } icon: { Image(systemName: "seal.fill") } } .tag(Tab.rewards) NavigationView { RecipeList() } .tabItem { Label { Text("Recipes", comment: "Smoothie recipes tab title") } icon: { Image(systemName: "book.closed.fill") } } .tag(Tab.recipes) #endif } } } struct AppTabNavigation_Previews: PreviewProvider { static var previews: some View { AppTabNavigation() } } ``` ## FrutaAppClip.swift ```swift /* Abstract: The single entry point for the Fruta App Clip. */ import SwiftUI import AppClip import CoreLocation @main struct FrutaAppClip: App { @StateObject private var model = Model() var body: some Scene { WindowGroup { NavigationView { SmoothieMenu() } .environmentObject(model) .onContinueUserActivity(NSUserActivityTypeBrowsingWeb, perform: handleUserActivity) } } func handleUserActivity(_ userActivity: NSUserActivity) { guard let incomingURL = userActivity.webpageURL, let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return } if let smoothieID = queryItems.first(where: { $0.name == "smoothie" })?.value { model.selectedSmoothieID = smoothieID } guard let payload = userActivity.appClipActivationPayload, let latitudeValue = queryItems.first(where: { $0.name == "latitude" })?.value, let longitudeValue = queryItems.first(where: { $0.name == "longitude" })?.value, let latitude = Double(latitudeValue), let longitude = Double(longitudeValue) else { return } let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region = CLCircularRegion(center: center, radius: 100, identifier: "smoothie_location") payload.confirmAcquired(in: region) { inRegion, error in if let error = error { print(error.localizedDescription) return } DispatchQueue.main.async { model.isApplePayEnabled = inRegion } } } } ``` ## AppDelegate.swift ```swift /* Abstract: The application-specific delegate class. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: - UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, // this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } } ``` ## SceneDelegate.swift ```swift /* Abstract: The scene delegate to configure the scene's window and user interface. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } let window = UIWindow(windowScene: windowScene) let splitViewController = NavigationSplitViewController() window.rootViewController = splitViewController window.makeKeyAndVisible() self.window = window } } ``` ## DescriptionPopoverViewController.swift ```swift /* Abstract: The popover view controller to describe each menu choice in MenuViewController. */ import UIKit class DescriptionPopoverViewController: UIViewController { private let _title: String private let _description: String init(withTitle title: String, description: String) { self._title = title self._description = description super.init(nibName: nil, bundle: nil) let closeCommand = UIKeyCommand(title: "Close popover", action: #selector(close), input: UIKeyCommand.inputEscape) self.addKeyCommand(closeCommand) // Also trigger on tab. The popover is the only item that would potentially be focusable right now, so we don't // block the focus system. Users may want to 'tab' into the sidebar again though, so handle this like escape. let tabCommand = UIKeyCommand(action: #selector(close), input: "\t") tabCommand.wantsPriorityOverSystemBehavior = true self.addKeyCommand(tabCommand) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .systemBackground let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = .preferredFont(forTextStyle: .headline) self.view.addSubview(titleLabel) let descriptionLabel = UILabel() descriptionLabel.translatesAutoresizingMaskIntoConstraints = false descriptionLabel.font = .preferredFont(forTextStyle: .body) descriptionLabel.numberOfLines = 0 self.view.addSubview(descriptionLabel) let padding = 20.0 NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: padding), titleLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -padding), descriptionLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: padding), descriptionLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -padding), titleLabel.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: padding), descriptionLabel.topAnchor.constraint(equalToSystemSpacingBelow: titleLabel.bottomAnchor, multiplier: 1.0), descriptionLabel.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -padding) ]) titleLabel.text = self._title descriptionLabel.text = self._description } override var preferredContentSize: CGSize { get { self.view.systemLayoutSizeFitting( CGSize(width: 320.0, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) } set { self.preferredContentSize = newValue } } @objc func close() { self.dismiss(animated: true) } } ``` ## EmptyViewController.swift ```swift /* Abstract: The view controller shown on app launch, showing a 'no sample selected' message. */ import UIKit class EmptyViewController: UIViewController { // The implementation of this class is entirely in the xib file. } ``` ## MenuViewController.swift ```swift /* Abstract: The collection view of menu choices for this sample. */ import UIKit private let reuseIdentifier = "Cell" protocol MenuDescribable { static var title: String { get } static var description: String { get } static var iconName: String { get } static func create() -> UIViewController } protocol MenuViewControllerDelegate: AnyObject { func menuViewController(_ menuViewController: MenuViewController, didSelect viewController: UIViewController) } protocol MenuListCellDelegate: AnyObject { func collectionView(_ collectionView: UICollectionView, showDescriptionForItemAt indexPath: IndexPath) } class MenuViewController: UICollectionViewController, MenuListCellDelegate { class MenuListCell: UICollectionViewListCell { private var collectionView: UICollectionView? { var view = self.superview while view != nil && !view!.isKind(of: UICollectionView.self) { view = view!.superview } return view as? UICollectionView } @objc func showDescription() { guard let collectionView = collectionView else { return } guard let indexPath = collectionView.indexPath(for: self) else { return } guard let delegate = collectionView.delegate as? MenuListCellDelegate else { return } delegate.collectionView(collectionView, showDescriptionForItemAt: indexPath) } } private struct Menu: Hashable { private let item: MenuDescribable.Type var title: String { item.title } var description: String { item.description } var icon: UIImage { UIImage(systemName: item.iconName) ?? UIImage(systemName: "questionmark.square.dashed")! } func create() -> UIViewController { item.create() } init(for item: MenuDescribable.Type) { self.item = item } static func == (lhs: MenuViewController.Menu, rhs: MenuViewController.Menu) -> Bool { return lhs.item == rhs.item } func hash(into hasher: inout Hasher) { hasher.combine(self.title) } } private class var menuStructure: [Menu] { return [ Menu(for: SearchResultsSample.self), Menu(for: SelectionSample.self), Menu(for: GroupsSample.self), Menu(for: GroupSortingSample.self), Menu(for: FocusGuideSample.self), Menu(for: KeyCommandsSample.self) ] } private var dataSource: UICollectionViewDiffableDataSource<Int, Menu>? public weak var delegate: MenuViewControllerDelegate? init() { super.init(collectionViewLayout: UICollectionViewCompositionalLayout.list(using: .init(appearance: .sidebar))) let infoCommand = UIKeyCommand(title: "Show sample info", action: #selector(MenuViewController.MenuListCell.showDescription), input: "i", modifierFlags: .command) self.addKeyCommand(infoCommand) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Register cell classes let cellRegistration = UICollectionView.CellRegistration<MenuListCell, Menu>(handler: { cell, indexPath, menu in var configuration = cell.defaultContentConfiguration() configuration.image = menu.icon configuration.text = menu.title cell.contentConfiguration = configuration let button = UIButton(type: .detailDisclosure, primaryAction: UIAction() { [weak cell] _ in if let cell = cell { cell.showDescription() } }) cell.accessories = [ .customView(configuration: .init(customView: button, placement: .trailing())) ] }) let dataSource = UICollectionViewDiffableDataSource<Int, Menu>(collectionView: self.collectionView, cellProvider: { collectionView, indexPath, menu in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: menu) }) self.dataSource = dataSource var snapshot = NSDiffableDataSourceSnapshot<Int, Menu>() snapshot.appendSections([0]) snapshot.appendItems(MenuViewController.menuStructure) dataSource.apply(snapshot, animatingDifferences: false) } // MARK: - MenuListCellDelegate func collectionView(_ collectionView: UICollectionView, showDescriptionForItemAt indexPath: IndexPath) { guard let dataSource = self.dataSource else { fatalError() } guard let cell = collectionView.cellForItem(at: indexPath) else { return } let menu = dataSource.itemIdentifier(for: indexPath)! let description = DescriptionPopoverViewController(withTitle: menu.title, description: menu.description) description.modalPresentationStyle = .popover description.popoverPresentationController?.sourceView = cell description.popoverPresentationController?.permittedArrowDirections = .left self.present(description, animated: true) } // MARK: - UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let dataSource = self.dataSource else { fatalError() } let menu = dataSource.itemIdentifier(for: indexPath)! let viewController = menu.create() self.delegate?.menuViewController(self, didSelect: viewController) } } ``` ## NavigationSplitViewController.swift ```swift /* Abstract: The sample's UISplitViewController's subclass. */ import UIKit class NavigationSplitViewController: UISplitViewController { let menuController = MenuViewController() init() { super.init(style: .doubleColumn) self.menuController.delegate = self self.setViewController(UINavigationController(rootViewController: self.menuController), for: .primary) self.setViewController(UINavigationController(rootViewController: EmptyViewController()), for: .secondary) primaryBackgroundStyle = .sidebar preferredDisplayMode = .oneBesideSecondary } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension NavigationSplitViewController: MenuViewControllerDelegate { func menuViewController(_ menuViewController: MenuViewController, didSelect viewController: UIViewController) { self.showDetailViewController(UINavigationController(rootViewController: viewController), sender: nil) } } ``` ## CustomCollectionViewCell.swift ```swift /* Abstract: UICollectionViewCell subclass describing an SF Symbol image and its name. This cell illustrates how to apply a custom highlight effect. */ import UIKit extension CustomCollectionViewCell { #if targetEnvironment(macCatalyst) override func didUpdateFocus(in context: UIFocusUpdateContext, with animationCoordinator: UIFocusAnimationCoordinator) { super.didUpdateFocus(in: context, with: animationCoordinator) // customize the border of the cell instead of putting a focus ring on top of it. if context.nextFocusedItem === self { let layer = self.imageContainer.layer layer.borderColor = self.tintColor.cgColor layer.borderWidth = 4.0 } else if context.previouslyFocusedItem === self { let layer = self.imageContainer.layer layer.borderColor = UIColor.systemGray.cgColor layer.borderWidth = 1.0 / self.traitCollection.displayScale } } #else override func updateConfiguration(using state: UICellConfigurationState) { // Create a configuration for the cell style that matches our cell design and update it for the current state. let backgroundConfiguration = UIBackgroundConfiguration.listPlainCell().updated(for: state) // The resolved background color can be assigned directly. self.imageContainer.backgroundColor = backgroundConfiguration.resolvedBackgroundColor(for: self.tintColor) // If the background color property is nil that means its the tint color. In that case use a white tint color // for the image view. Otherwise use the default label color. self.imageView.tintColor = backgroundConfiguration.backgroundColor == nil ? .white : .label } #endif } class CustomCollectionViewCell: UICollectionViewCell { var data: SampleData? { didSet { let configuration = UIImage.SymbolConfiguration(font: .systemFont(ofSize: 60.0)) self.imageView.image = self.data?.icon.applyingSymbolConfiguration(configuration)?.withRenderingMode(.alwaysTemplate) self.label.text = self.data?.name } } private let imageView = UIImageView() private let label = UILabel() private let imageContainer = UIView() override init(frame: CGRect) { super.init(frame: frame) self.imageContainer.translatesAutoresizingMaskIntoConstraints = false self.imageContainer.layer.borderColor = UIColor.systemGray.cgColor self.imageContainer.layer.borderWidth = 1.0 / self.traitCollection.displayScale self.imageContainer.layer.cornerRadius = 16.0 self.imageView.translatesAutoresizingMaskIntoConstraints = false self.label.translatesAutoresizingMaskIntoConstraints = false self.label.adjustsFontForContentSizeCategory = true self.label.font = .preferredFont(forTextStyle: .body) self.label.textAlignment = .center self.label.numberOfLines = 0 self.imageView.tintColor = .label self.imageView.contentMode = .scaleAspectFit self.contentView.addSubview(self.imageContainer) self.imageContainer.addSubview(self.imageView) self.contentView.addSubview(self.label) Layout.activate( // Vertical Layout.embed(self.imageContainer, self.label, verticallyIn: self.contentView, spacing: 8.0), // Horizontal [ self.imageContainer.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor), self.imageContainer.leadingAnchor.constraint(greaterThanOrEqualTo: self.contentView.leadingAnchor), self.imageContainer.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).with(priority: .defaultLow), self.label.widthAnchor.constraint(equalTo: self.imageContainer.widthAnchor, multiplier: 1.2) ], Layout.embed(self.label, horizontallyIn: self.contentView), // Image positioning. Layout.square(self.imageContainer), Layout.center(self.imageView, in: self.imageContainer), [ self.imageView.leadingAnchor.constraint(greaterThanOrEqualTo: self.imageContainer.leadingAnchor), self.imageView.leadingAnchor.constraint(equalTo: self.imageView.leadingAnchor).with(priority: .defaultLow), self.imageView.topAnchor.constraint(greaterThanOrEqualTo: self.imageContainer.topAnchor), self.imageView.topAnchor.constraint(equalTo: self.imageView.topAnchor).with(priority: .defaultLow) ] ) self.label.setContentHuggingPriority(.required, for: .vertical) self.label.setContentCompressionResistancePriority(.required, for: .vertical) // Set the focus effect to nil as this cell provides its own custom focus drawing. self.focusEffect = nil } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.imageContainer.layer.borderWidth = 1.0 / self.traitCollection.displayScale } } ``` ## FocusGuideSample.swift ```swift /* Abstract: Example showing focus guides. */ import UIKit struct FocusGuideSample: MenuDescribable { static var title = "Focus Guides" static var iconName = "arrow.up.left.and.down.right.and.arrow.up.right.and.down.left" static var description = """ In this example focus guides are used to remember the last focused item in a row \ of two. When using the arrow keys to move between the top and the bottom row of this 2x2 \ grid, focus will always jump to the item that was last focused in this row. To achieve this, there are two focus guides, one per row. Focus can still move \ freely inside of a row because focus guides are ignored when they overlap with the \ currently focused item. """ static func create() -> UIViewController { FocusGuideViewController() } } class FocusGuideViewController: GridViewController<FocusableView> { let topFocusGuide = UIFocusGuide() let bottomFocusGuide = UIFocusGuide() override func viewDidLoad() { super.viewDidLoad() // Set the default environments the guides should point to // this will make sure that we always start with the leading item. self.topFocusGuide.preferredFocusEnvironments = [ self.gridView.topLeading ] self.bottomFocusGuide.preferredFocusEnvironments = [ self.gridView.bottomLeading ] self.gridView.showsHorizontalDivider = true self.gridView.addLayoutGuide(self.topFocusGuide) self.gridView.addLayoutGuide(self.bottomFocusGuide) // Position guides so that they overlap the top / bottom row of items. Layout.activate( // Horizontal Layout.embed(self.topFocusGuide, horizontallyIn: self.gridView), Layout.embed(self.bottomFocusGuide, horizontallyIn: self.gridView), // Vertical Layout.embed(self.topFocusGuide, self.bottomFocusGuide, verticallyIn: self.gridView, spacing: 0.0), [ self.topFocusGuide.heightAnchor.constraint(equalTo: self.bottomFocusGuide.heightAnchor) ] ) self.updateFocusGuideIndicator() } override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { // Another thing we can do with guides is to update them to point to the last focused item from a list of items. if let nextItem = context.nextFocusedItem { if nextItem === self.gridView.topLeading || nextItem === self.gridView.topTrailing { self.topFocusGuide.preferredFocusEnvironments = [ nextItem ] } else if nextItem === self.gridView.bottomLeading || nextItem === self.gridView.bottomTrailing { self.bottomFocusGuide.preferredFocusEnvironments = [ nextItem ] } coordinator.addCoordinatedAnimations({ self.updateFocusGuideIndicator() }) } } func updateFocusGuideIndicator() { // Just for better visibility, highlight the view that is the preferred environment of a focus guide. self.gridView.enumerateViews({ view in let isChosenOne = view === self.topFocusGuide.preferredFocusEnvironments.first || view === self.bottomFocusGuide.preferredFocusEnvironments.first view.layer.borderColor = UIColor.tintColor.cgColor view.layer.borderWidth = isChosenOne ? 1.0 : 0.0 }) } } ``` ## GroupSortingSample.swift ```swift /* Abstract: Example showing a column of two items, each with their own focus group. */ import UIKit struct GroupSortingSample: MenuDescribable { static var title = "Group Sorting" static var iconName = "rectangle.3.offgrid" static var description = """ Shows a column of two items on the left and a single item on the right. \ Each of these items provide their own focus group so that they can each be \ reached by pressing tab. Focus groups are then used to group them together so \ that the left, vertically stacked items are enumerated before focus jumps to \ the item on the right. """ static func create() -> UIViewController { GroupSortingSampleViewController() } } class GroupSortingSampleViewController: UIViewController { let topLeading = FocusableView() let bottomLeading = FocusableView() let trailing = FocusableView() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .systemBackground let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false let leadingContainer = UIView() leadingContainer.translatesAutoresizingMaskIntoConstraints = false self.topLeading.translatesAutoresizingMaskIntoConstraints = false self.bottomLeading.translatesAutoresizingMaskIntoConstraints = false self.trailing.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(containerView) containerView.addSubview(leadingContainer) leadingContainer.addSubview(self.topLeading) leadingContainer.addSubview(self.bottomLeading) containerView.addSubview(self.trailing) Layout.activate( // Container Layout.center(containerView, in: self.view), // Horizontal Layout.embed(leadingContainer, self.trailing, horizontallyIn: containerView), Layout.embed(self.topLeading, horizontallyIn: leadingContainer), Layout.embed(self.bottomLeading, horizontallyIn: leadingContainer), // Vertical Layout.embed(self.trailing, verticallyIn: containerView), Layout.embed(leadingContainer, verticallyIn: containerView), Layout.embed(self.topLeading, self.bottomLeading, verticallyIn: leadingContainer), // Aspect Layout.square(self.topLeading), Layout.square(self.bottomLeading), Layout.square(self.trailing, size: nil) // Trailing will size itself based on the above aspec and edge constraints. ) // Set the focus groups of the focusable items. self.topLeading.focusGroupIdentifier = FocusGroups.topLeading self.bottomLeading.focusGroupIdentifier = FocusGroups.bottomLeading self.trailing.focusGroupIdentifier = FocusGroups.trailingColumn // To ensure that topLeading and bottomLeading come before trailing, group them together. leadingContainer.focusGroupIdentifier = FocusGroups.leadingColumn } } ``` ## GroupsSample.swift ```swift /* Abstract: Example showing a 2x2 grid of focusable items. */ import UIKit struct GroupsSample: MenuDescribable { static var title = "Groups" static var iconName = "rectangle.grid.1x2" static var description = """ Shows a 2x2 grid of focusable items where the top row and the bottom row items \ are assigned to different focus groups. This allows tabbing between the two \ rows while using the arrow keys to navigate between the two items in each group. \ Or in other words: tab navigates vertically in this sample while arrow keys \ navigate horizontally. """ static func create() -> UIViewController { GroupsSampleViewController() } } class GroupsSampleViewController: GridViewController<FocusableView> { override func viewDidLoad() { super.viewDidLoad() self.gridView.showsHorizontalDivider = true self.gridView.topLeading.focusGroupIdentifier = FocusGroups.topRow self.gridView.topTrailing.focusGroupIdentifier = FocusGroups.topRow self.gridView.bottomLeading.focusGroupIdentifier = FocusGroups.bottomRow self.gridView.bottomTrailing.focusGroupIdentifier = FocusGroups.bottomRow } } ``` ## FocusGroups.swift ```swift /* Abstract: The focus group identifiers used in this sample. */ import Foundation /// Contains all the focus group identifiers used in this sample to make the call sites look nicer. struct FocusGroups { static let searchResults = "com.apple.wwdc21.searchresults" static let topRow = "com.apple.wwdc21.toprow" static let bottomRow = "com.apple.wwdc21.bottomrow" static let leadingColumn = "com.apple.wwdc21.leadingcolumn" static let trailingColumn = "com.apple.wwdc21.trailingcolumn" static let topLeading = "com.apple.wwdc21.topleading" static let bottomLeading = "com.apple.wwdc21.bottomleading" } ``` ## FocusableView.swift ```swift /* Abstract: A simple view subclass that returns true from canBecomeFocused. */ import UIKit class FocusableView: UIView { override var canBecomeFocused: Bool { true } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .secondarySystemFill self.focusEffect = UIFocusHaloEffect() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ``` ## GridView.swift ```swift /* Abstract: A view subclass that creates four subviews of the specified generic type and lays them out in a 2x2 grid. */ import UIKit /// A view that creates four subviews of the specified generic type and lays them out in a 2x2 grid. /// Optionally a hairline divider can be shown horizontally or vertically between them class GridView<T: UIView>: UIView { class HairlineView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .systemFill } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { let hairline = 1.0 / self.traitCollection.displayScale return CGSize(width: hairline, height: hairline) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.invalidateIntrinsicContentSize() } } let topLeading = T() let topTrailing = T() let bottomLeading = T() let bottomTrailing = T() private let horizontalHairline = HairlineView() private let verticalHairline = HairlineView() var showsHorizontalDivider: Bool = false { didSet { self.horizontalHairline.isHidden = !self.showsHorizontalDivider } } var showsVerticalDivider: Bool = false { didSet { self.verticalHairline.isHidden = !self.showsVerticalDivider } } func enumerateViews(_ enumerator: (UIView) -> Void) { enumerator(self.topLeading) enumerator(self.topTrailing) enumerator(self.bottomLeading) enumerator(self.bottomTrailing) } override init(frame: CGRect) { super.init(frame: frame) self.horizontalHairline.isHidden = true self.verticalHairline.isHidden = true self.topLeading.translatesAutoresizingMaskIntoConstraints = false self.topTrailing.translatesAutoresizingMaskIntoConstraints = false self.bottomLeading.translatesAutoresizingMaskIntoConstraints = false self.bottomTrailing.translatesAutoresizingMaskIntoConstraints = false self.horizontalHairline.translatesAutoresizingMaskIntoConstraints = false self.verticalHairline.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.topLeading) self.addSubview(self.topTrailing) self.addSubview(self.bottomLeading) self.addSubview(self.bottomTrailing) self.addSubview(self.horizontalHairline) self.addSubview(self.verticalHairline) Layout.activate( // horizontal Layout.embed(self.topLeading, self.topTrailing, horizontallyIn: self, hasPadding: true), Layout.embed(self.bottomLeading, self.bottomTrailing, horizontallyIn: self, hasPadding: true), // vertical Layout.embed(self.topLeading, self.bottomLeading, verticallyIn: self, hasPadding: true), Layout.embed(self.topTrailing, self.bottomTrailing, verticallyIn: self, hasPadding: true), // aspect Layout.square(self.topLeading), Layout.square(self.topTrailing), Layout.square(self.bottomLeading), Layout.square(self.bottomTrailing), // hairline Layout.center(self.horizontalHairline, in: self), Layout.embed(self.horizontalHairline, horizontallyIn: self), Layout.center(self.verticalHairline, in: self), Layout.embed(self.verticalHairline, verticallyIn: self) ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class GridViewController<T: UIView>: UIViewController { let gridView = GridView<T>() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .systemBackground self.gridView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.gridView) Layout.activate(Layout.center(self.gridView, in: self.view)) } } ``` ## LayoutHelper.swift ```swift /* Abstract: Layout utility for building and embedding NSLayoutConstraints to views. */ import UIKit protocol LayoutAnchorProviding { var leadingAnchor: NSLayoutXAxisAnchor { get } var trailingAnchor: NSLayoutXAxisAnchor { get } var leftAnchor: NSLayoutXAxisAnchor { get } var rightAnchor: NSLayoutXAxisAnchor { get } var topAnchor: NSLayoutYAxisAnchor { get } var bottomAnchor: NSLayoutYAxisAnchor { get } var widthAnchor: NSLayoutDimension { get } var heightAnchor: NSLayoutDimension { get } var centerXAnchor: NSLayoutXAxisAnchor { get } var centerYAnchor: NSLayoutYAxisAnchor { get } } struct Layout { // The value we use to calculate all our spacings. static let defaultSpacing = 40.0 static func activate(_ constraints: [NSLayoutConstraint]...) { NSLayoutConstraint.activate(constraints.flatMap({ $0 })) } static func embed(_ items: LayoutAnchorProviding..., horizontallyIn container: LayoutAnchorProviding, spacing: CGFloat = defaultSpacing, hasPadding: Bool = false) -> [NSLayoutConstraint] { guard !items.isEmpty else { return [] } let padding = hasPadding ? spacing * 0.5 : 0.0 var lastItem: LayoutAnchorProviding? = nil var constraints = [ // Add leading and trailing constraints. items.first!.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: padding), container.trailingAnchor.constraint(equalTo: items.last!.trailingAnchor, constant: padding) ] // Add intermediate constraints. for item in items { if let lastItem = lastItem { constraints.append(item.leadingAnchor.constraint(equalTo: lastItem.trailingAnchor, constant: spacing)) } lastItem = item } return constraints } static func embed(_ items: LayoutAnchorProviding..., verticallyIn container: LayoutAnchorProviding, spacing: CGFloat = defaultSpacing, hasPadding: Bool = false) -> [NSLayoutConstraint] { guard !items.isEmpty else { return [] } let padding = hasPadding ? spacing * 0.5 : 0.0 var lastItem: LayoutAnchorProviding? = nil var constraints = [ // Add leading and trailing constraints. items.first!.topAnchor.constraint(equalTo: container.topAnchor, constant: padding), container.bottomAnchor.constraint(equalTo: items.last!.bottomAnchor, constant: padding) ] // Add intermediate constraints. for item in items { if let lastItem = lastItem { constraints.append(item.topAnchor.constraint(equalTo: lastItem.bottomAnchor, constant: spacing)) } lastItem = item } return constraints } static func center(_ item: LayoutAnchorProviding, in container: LayoutAnchorProviding) -> [NSLayoutConstraint] { return [ item.centerXAnchor.constraint(equalTo: container.centerXAnchor), item.centerYAnchor.constraint(equalTo: container.centerYAnchor) ] } static func square(_ item: LayoutAnchorProviding, size: CGFloat? = defaultSpacing * 3.0) -> [NSLayoutConstraint] { var constraints = [ item.widthAnchor.constraint(equalTo: item.heightAnchor) ] if let size = size { constraints.append(item.widthAnchor.constraint(equalToConstant: size)) } return constraints } } extension NSLayoutConstraint { func with(priority: UILayoutPriority) -> NSLayoutConstraint { self.priority = priority return self } } extension UIView: LayoutAnchorProviding {} extension UILayoutGuide: LayoutAnchorProviding {} ``` ## SampleGenerator.swift ```swift /* Abstract: The data model that describes an individual SF symbol. */ import UIKit struct SampleData: Hashable { let name: String let icon: UIImage } extension SampleData { static func createSampleData() -> [SampleData] { return createSymbolLibrary() } static func createSampleDataSource<CellType: UICollectionViewCell>( collectionView: UICollectionView, cellRegistration: UICollectionView.CellRegistration<CellType, SampleData>) -> UICollectionViewDiffableDataSource<Int, SampleData> { let dataSource = UICollectionViewDiffableDataSource<Int, SampleData>(collectionView: collectionView, cellProvider: { collectionView, indexPath, data in collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: data) }) var snapshot = NSDiffableDataSourceSnapshot<Int, SampleData>() snapshot.appendSections([0]) snapshot.appendItems(createSampleData()) dataSource.apply(snapshot, animatingDifferences: false) return dataSource } } ``` ## SymbolLibrary.swift ```swift /* Abstract: The data model or symbol library of known SF Symbols. */ import UIKit /// A list of all the SF Symbols extension SampleData { static func createSymbolLibrary() -> [SampleData] { return [ SampleData(name: "pencil", icon: UIImage(systemName: "pencil")!), SampleData(name: "pencil.slash", icon: UIImage(systemName: "pencil.slash")!), SampleData(name: "scribble", icon: UIImage(systemName: "scribble")!), SampleData(name: "scribble.variable", icon: UIImage(systemName: "scribble.variable")!), SampleData(name: "highlighter", icon: UIImage(systemName: "highlighter")!), SampleData(name: "pencil.tip", icon: UIImage(systemName: "pencil.tip")!), SampleData(name: "lasso", icon: UIImage(systemName: "lasso")!), SampleData(name: "lasso.sparkles", icon: UIImage(systemName: "lasso.sparkles")!), SampleData(name: "trash", icon: UIImage(systemName: "trash")!), SampleData(name: "trash.slash", icon: UIImage(systemName: "trash.slash")!), SampleData(name: "folder", icon: UIImage(systemName: "folder")!), SampleData(name: "questionmark.folder", icon: UIImage(systemName: "questionmark.folder")!), SampleData(name: "paperplane", icon: UIImage(systemName: "paperplane")!), SampleData(name: "tray", icon: UIImage(systemName: "tray")!), SampleData(name: "tray.2", icon: UIImage(systemName: "tray.2")!), SampleData(name: "tray.full", icon: UIImage(systemName: "tray.full")!), SampleData(name: "externaldrive", icon: UIImage(systemName: "externaldrive")!), SampleData(name: "internaldrive", icon: UIImage(systemName: "internaldrive")!), SampleData(name: "opticaldiscdrive", icon: UIImage(systemName: "opticaldiscdrive")!), SampleData(name: "archivebox", icon: UIImage(systemName: "archivebox")!), SampleData(name: "xmark.bin", icon: UIImage(systemName: "xmark.bin")!), SampleData(name: "doc", icon: UIImage(systemName: "doc")!), SampleData(name: "lock.doc", icon: UIImage(systemName: "lock.doc")!), SampleData(name: "doc.text", icon: UIImage(systemName: "doc.text")!), SampleData(name: "doc.zipper", icon: UIImage(systemName: "doc.zipper")!), SampleData(name: "doc.richtext", icon: UIImage(systemName: "doc.richtext")!), SampleData(name: "doc.plaintext", icon: UIImage(systemName: "doc.plaintext")!), SampleData(name: "doc.append", icon: UIImage(systemName: "doc.append")!), SampleData(name: "terminal", icon: UIImage(systemName: "terminal")!), SampleData(name: "note", icon: UIImage(systemName: "note")!), SampleData(name: "note.text", icon: UIImage(systemName: "note.text")!), SampleData(name: "calendar", icon: UIImage(systemName: "calendar")!), SampleData(name: "book", icon: UIImage(systemName: "book")!), SampleData(name: "newspaper", icon: UIImage(systemName: "newspaper")!), SampleData(name: "books.vertical", icon: UIImage(systemName: "books.vertical")!), SampleData(name: "book.closed", icon: UIImage(systemName: "book.closed")!), SampleData(name: "greetingcard", icon: UIImage(systemName: "greetingcard")!), SampleData(name: "bookmark", icon: UIImage(systemName: "bookmark")!), SampleData(name: "bookmark.slash", icon: UIImage(systemName: "bookmark.slash")!), SampleData(name: "rosette", icon: UIImage(systemName: "rosette")!), SampleData(name: "graduationcap", icon: UIImage(systemName: "graduationcap")!), SampleData(name: "ticket", icon: UIImage(systemName: "ticket")!), SampleData(name: "paperclip", icon: UIImage(systemName: "paperclip")!), SampleData(name: "link", icon: UIImage(systemName: "link")!), SampleData(name: "personalhotspot", icon: UIImage(systemName: "personalhotspot")!), SampleData(name: "lineweight", icon: UIImage(systemName: "lineweight")!), SampleData(name: "person", icon: UIImage(systemName: "person")!), SampleData(name: "person.2", icon: UIImage(systemName: "person.2")!), SampleData(name: "person.3", icon: UIImage(systemName: "person.3")!), SampleData(name: "command", icon: UIImage(systemName: "command")!), SampleData(name: "option", icon: UIImage(systemName: "option")!), SampleData(name: "alt", icon: UIImage(systemName: "alt")!), SampleData(name: "delete.right", icon: UIImage(systemName: "delete.right")!), SampleData(name: "clear", icon: UIImage(systemName: "clear")!), SampleData(name: "delete.left", icon: UIImage(systemName: "delete.left")!), SampleData(name: "shift", icon: UIImage(systemName: "shift")!), SampleData(name: "capslock", icon: UIImage(systemName: "capslock")!), SampleData(name: "escape", icon: UIImage(systemName: "escape")!), SampleData(name: "restart", icon: UIImage(systemName: "restart")!), SampleData(name: "sleep", icon: UIImage(systemName: "sleep")!), SampleData(name: "wake", icon: UIImage(systemName: "wake")!), SampleData(name: "power", icon: UIImage(systemName: "power")!), SampleData(name: "togglepower", icon: UIImage(systemName: "togglepower")!), SampleData(name: "poweron", icon: UIImage(systemName: "poweron")!), SampleData(name: "poweroff", icon: UIImage(systemName: "poweroff")!), SampleData(name: "powersleep", icon: UIImage(systemName: "powersleep")!), SampleData(name: "directcurrent", icon: UIImage(systemName: "directcurrent")!), SampleData(name: "globe", icon: UIImage(systemName: "globe")!), SampleData(name: "network", icon: UIImage(systemName: "network")!), SampleData(name: "sun.min", icon: UIImage(systemName: "sun.min")!), SampleData(name: "sun.max", icon: UIImage(systemName: "sun.max")!), SampleData(name: "sunrise", icon: UIImage(systemName: "sunrise")!), SampleData(name: "sunset", icon: UIImage(systemName: "sunset")!), SampleData(name: "sun.dust", icon: UIImage(systemName: "sun.dust")!), SampleData(name: "sun.haze", icon: UIImage(systemName: "sun.haze")!), SampleData(name: "moon", icon: UIImage(systemName: "moon")!), SampleData(name: "zzz", icon: UIImage(systemName: "zzz")!), SampleData(name: "moon.zzz", icon: UIImage(systemName: "moon.zzz")!), SampleData(name: "sparkle", icon: UIImage(systemName: "sparkle")!), SampleData(name: "sparkles", icon: UIImage(systemName: "sparkles")!), SampleData(name: "moon.stars", icon: UIImage(systemName: "moon.stars")!), SampleData(name: "cloud", icon: UIImage(systemName: "cloud")!), SampleData(name: "cloud.drizzle", icon: UIImage(systemName: "cloud.drizzle")!), SampleData(name: "cloud.rain", icon: UIImage(systemName: "cloud.rain")!), SampleData(name: "cloud.heavyrain", icon: UIImage(systemName: "cloud.heavyrain")!), SampleData(name: "cloud.fog", icon: UIImage(systemName: "cloud.fog")!), SampleData(name: "cloud.hail", icon: UIImage(systemName: "cloud.hail")!), SampleData(name: "cloud.snow", icon: UIImage(systemName: "cloud.snow")!), SampleData(name: "cloud.sleet", icon: UIImage(systemName: "cloud.sleet")!), SampleData(name: "cloud.bolt", icon: UIImage(systemName: "cloud.bolt")!), SampleData(name: "cloud.sun", icon: UIImage(systemName: "cloud.sun")!), SampleData(name: "cloud.moon", icon: UIImage(systemName: "cloud.moon")!), SampleData(name: "smoke", icon: UIImage(systemName: "smoke")!), SampleData(name: "wind", icon: UIImage(systemName: "wind")!), SampleData(name: "wind.snow", icon: UIImage(systemName: "wind.snow")!), SampleData(name: "snow", icon: UIImage(systemName: "snow")!), SampleData(name: "tornado", icon: UIImage(systemName: "tornado")!), SampleData(name: "tropicalstorm", icon: UIImage(systemName: "tropicalstorm")!), SampleData(name: "hurricane", icon: UIImage(systemName: "hurricane")!), SampleData(name: "thermometer.sun", icon: UIImage(systemName: "thermometer.sun")!), SampleData(name: "thermometer.snowflake", icon: UIImage(systemName: "thermometer.snowflake")!), SampleData(name: "thermometer", icon: UIImage(systemName: "thermometer")!), SampleData(name: "aqi.low", icon: UIImage(systemName: "aqi.low")!), SampleData(name: "aqi.medium", icon: UIImage(systemName: "aqi.medium")!), SampleData(name: "aqi.high", icon: UIImage(systemName: "aqi.high")!), SampleData(name: "umbrella", icon: UIImage(systemName: "umbrella")!), SampleData(name: "flame", icon: UIImage(systemName: "flame")!), SampleData(name: "light.min", icon: UIImage(systemName: "light.min")!), SampleData(name: "light.max", icon: UIImage(systemName: "light.max")!), SampleData(name: "rays", icon: UIImage(systemName: "rays")!), SampleData(name: "slowmo", icon: UIImage(systemName: "slowmo")!), SampleData(name: "timelapse", icon: UIImage(systemName: "timelapse")!), SampleData(name: "cursorarrow.rays", icon: UIImage(systemName: "cursorarrow.rays")!), SampleData(name: "cursorarrow", icon: UIImage(systemName: "cursorarrow")!), SampleData(name: "cursorarrow.click", icon: UIImage(systemName: "cursorarrow.click")!), SampleData(name: "cursorarrow.motionlines", icon: UIImage(systemName: "cursorarrow.motionlines")!), SampleData(name: "keyboard", icon: UIImage(systemName: "keyboard")!), SampleData(name: "rectangle.3.offgrid", icon: UIImage(systemName: "rectangle.3.offgrid")!), SampleData(name: "circles.hexagongrid", icon: UIImage(systemName: "circles.hexagongrid")!), SampleData(name: "circles.hexagonpath", icon: UIImage(systemName: "circles.hexagonpath")!), SampleData(name: "seal", icon: UIImage(systemName: "seal")!), SampleData(name: "checkmark.seal", icon: UIImage(systemName: "checkmark.seal")!), SampleData(name: "xmark.seal", icon: UIImage(systemName: "xmark.seal")!), SampleData(name: "exclamationmark.triangle", icon: UIImage(systemName: "exclamationmark.triangle")!), SampleData(name: "drop", icon: UIImage(systemName: "drop")!), SampleData(name: "drop.triangle", icon: UIImage(systemName: "drop.triangle")!), SampleData(name: "play", icon: UIImage(systemName: "play")!), SampleData(name: "play.rectangle", icon: UIImage(systemName: "play.rectangle")!), SampleData(name: "play.slash", icon: UIImage(systemName: "play.slash")!), SampleData(name: "pause", icon: UIImage(systemName: "pause")!), SampleData(name: "pause.rectangle", icon: UIImage(systemName: "pause.rectangle")!), SampleData(name: "stop", icon: UIImage(systemName: "stop")!), SampleData(name: "playpause", icon: UIImage(systemName: "playpause")!), SampleData(name: "backward", icon: UIImage(systemName: "backward")!), SampleData(name: "forward", icon: UIImage(systemName: "forward")!), SampleData(name: "backward.end", icon: UIImage(systemName: "backward.end")!), SampleData(name: "forward.end", icon: UIImage(systemName: "forward.end")!), SampleData(name: "backward.frame", icon: UIImage(systemName: "backward.frame")!), SampleData(name: "forward.frame", icon: UIImage(systemName: "forward.frame")!), SampleData(name: "eject", icon: UIImage(systemName: "eject")!), SampleData(name: "mount", icon: UIImage(systemName: "mount")!), SampleData(name: "memories", icon: UIImage(systemName: "memories")!), SampleData(name: "shuffle", icon: UIImage(systemName: "shuffle")!), SampleData(name: "repeat", icon: UIImage(systemName: "repeat")!), SampleData(name: "repeat.1", icon: UIImage(systemName: "repeat.1")!), SampleData(name: "infinity", icon: UIImage(systemName: "infinity")!), SampleData(name: "megaphone", icon: UIImage(systemName: "megaphone")!), SampleData(name: "speaker", icon: UIImage(systemName: "speaker")!), SampleData(name: "speaker.slash", icon: UIImage(systemName: "speaker.slash")!), SampleData(name: "speaker.zzz", icon: UIImage(systemName: "speaker.zzz")!), SampleData(name: "music.note", icon: UIImage(systemName: "music.note")!), SampleData(name: "music.mic", icon: UIImage(systemName: "music.mic")!), SampleData(name: "arrow.rectanglepath", icon: UIImage(systemName: "arrow.rectanglepath")!), SampleData(name: "goforward", icon: UIImage(systemName: "goforward")!), SampleData(name: "gobackward", icon: UIImage(systemName: "gobackward")!), SampleData(name: "goforward.10", icon: UIImage(systemName: "goforward.10")!), SampleData(name: "gobackward.10", icon: UIImage(systemName: "gobackward.10")!), SampleData(name: "goforward.15", icon: UIImage(systemName: "goforward.15")!), SampleData(name: "gobackward.15", icon: UIImage(systemName: "gobackward.15")!), SampleData(name: "goforward.30", icon: UIImage(systemName: "goforward.30")!), SampleData(name: "gobackward.30", icon: UIImage(systemName: "gobackward.30")!), SampleData(name: "goforward.45", icon: UIImage(systemName: "goforward.45")!), SampleData(name: "gobackward.45", icon: UIImage(systemName: "gobackward.45")!), SampleData(name: "goforward.60", icon: UIImage(systemName: "goforward.60")!), SampleData(name: "gobackward.60", icon: UIImage(systemName: "gobackward.60")!), SampleData(name: "goforward.75", icon: UIImage(systemName: "goforward.75")!), SampleData(name: "gobackward.75", icon: UIImage(systemName: "gobackward.75")!), SampleData(name: "goforward.90", icon: UIImage(systemName: "goforward.90")!), SampleData(name: "gobackward.90", icon: UIImage(systemName: "gobackward.90")!), SampleData(name: "goforward.plus", icon: UIImage(systemName: "goforward.plus")!), SampleData(name: "gobackward.minus", icon: UIImage(systemName: "gobackward.minus")!), SampleData(name: "swift", icon: UIImage(systemName: "swift")!), SampleData(name: "magnifyingglass", icon: UIImage(systemName: "magnifyingglass")!), SampleData(name: "plus.magnifyingglass", icon: UIImage(systemName: "plus.magnifyingglass")!), SampleData(name: "minus.magnifyingglass", icon: UIImage(systemName: "minus.magnifyingglass")!), SampleData(name: "1.magnifyingglass", icon: UIImage(systemName: "1.magnifyingglass")!), SampleData(name: "text.magnifyingglass", icon: UIImage(systemName: "text.magnifyingglass")!), SampleData(name: "loupe", icon: UIImage(systemName: "loupe")!), SampleData(name: "mic", icon: UIImage(systemName: "mic")!), SampleData(name: "mic.slash", icon: UIImage(systemName: "mic.slash")!), SampleData(name: "line.diagonal", icon: UIImage(systemName: "line.diagonal")!), SampleData(name: "circle", icon: UIImage(systemName: "circle")!), SampleData(name: "circle.dashed", icon: UIImage(systemName: "circle.dashed")!), SampleData(name: "circlebadge", icon: UIImage(systemName: "circlebadge")!), SampleData(name: "circlebadge.2", icon: UIImage(systemName: "circlebadge.2")!), SampleData(name: "target", icon: UIImage(systemName: "target")!), SampleData(name: "capsule", icon: UIImage(systemName: "capsule")!), SampleData(name: "capsule.portrait", icon: UIImage(systemName: "capsule.portrait")!), SampleData(name: "oval", icon: UIImage(systemName: "oval")!), SampleData(name: "oval.portrait", icon: UIImage(systemName: "oval.portrait")!), SampleData(name: "square", icon: UIImage(systemName: "square")!), SampleData(name: "square.slash", icon: UIImage(systemName: "square.slash")!), SampleData(name: "square.dashed", icon: UIImage(systemName: "square.dashed")!), SampleData(name: "squareshape", icon: UIImage(systemName: "squareshape")!), SampleData(name: "dot.squareshape", icon: UIImage(systemName: "dot.squareshape")!), SampleData(name: "app", icon: UIImage(systemName: "app")!), SampleData(name: "rectangle", icon: UIImage(systemName: "rectangle")!), SampleData(name: "rectangle.slash", icon: UIImage(systemName: "rectangle.slash")!), SampleData(name: "rectangle.portrait", icon: UIImage(systemName: "rectangle.portrait")!), SampleData(name: "triangle", icon: UIImage(systemName: "triangle")!), SampleData(name: "diamond", icon: UIImage(systemName: "diamond")!), SampleData(name: "octagon", icon: UIImage(systemName: "octagon")!), SampleData(name: "hexagon", icon: UIImage(systemName: "hexagon")!), SampleData(name: "suit.heart", icon: UIImage(systemName: "suit.heart")!), SampleData(name: "suit.club", icon: UIImage(systemName: "suit.club")!), SampleData(name: "suit.spade", icon: UIImage(systemName: "suit.spade")!), SampleData(name: "suit.diamond", icon: UIImage(systemName: "suit.diamond")!), SampleData(name: "heart", icon: UIImage(systemName: "heart")!), SampleData(name: "heart.slash", icon: UIImage(systemName: "heart.slash")!), SampleData(name: "bolt.heart", icon: UIImage(systemName: "bolt.heart")!), SampleData(name: "rhombus", icon: UIImage(systemName: "rhombus")!), SampleData(name: "star", icon: UIImage(systemName: "star")!), SampleData(name: "star.slash", icon: UIImage(systemName: "star.slash")!), SampleData(name: "flag", icon: UIImage(systemName: "flag")!), SampleData(name: "flag.slash", icon: UIImage(systemName: "flag.slash")!), SampleData(name: "location", icon: UIImage(systemName: "location")!), SampleData(name: "location.slash", icon: UIImage(systemName: "location.slash")!), SampleData(name: "location.north", icon: UIImage(systemName: "location.north")!), SampleData(name: "bell", icon: UIImage(systemName: "bell")!), SampleData(name: "bell.slash", icon: UIImage(systemName: "bell.slash")!), SampleData(name: "bell.badge", icon: UIImage(systemName: "bell.badge")!), SampleData(name: "tag", icon: UIImage(systemName: "tag")!), SampleData(name: "tag.slash", icon: UIImage(systemName: "tag.slash")!), SampleData(name: "bolt", icon: UIImage(systemName: "bolt")!), SampleData(name: "bolt.slash", icon: UIImage(systemName: "bolt.slash")!), SampleData(name: "bolt.horizontal", icon: UIImage(systemName: "bolt.horizontal")!), SampleData(name: "eye", icon: UIImage(systemName: "eye")!), SampleData(name: "eye.slash", icon: UIImage(systemName: "eye.slash")!), SampleData(name: "eyes", icon: UIImage(systemName: "eyes")!), SampleData(name: "eyes.inverse", icon: UIImage(systemName: "eyes.inverse")!), SampleData(name: "eyebrow", icon: UIImage(systemName: "eyebrow")!), SampleData(name: "nose", icon: UIImage(systemName: "nose")!), SampleData(name: "mustache", icon: UIImage(systemName: "mustache")!), SampleData(name: "mouth", icon: UIImage(systemName: "mouth")!), SampleData(name: "icloud", icon: UIImage(systemName: "icloud")!), SampleData(name: "icloud.slash", icon: UIImage(systemName: "icloud.slash")!), SampleData(name: "exclamationmark.icloud", icon: UIImage(systemName: "exclamationmark.icloud")!), SampleData(name: "checkmark.icloud", icon: UIImage(systemName: "checkmark.icloud")!), SampleData(name: "xmark.icloud", icon: UIImage(systemName: "xmark.icloud")!), SampleData(name: "link.icloud", icon: UIImage(systemName: "link.icloud")!), SampleData(name: "person.icloud", icon: UIImage(systemName: "person.icloud")!), SampleData(name: "lock.icloud", icon: UIImage(systemName: "lock.icloud")!), SampleData(name: "key.icloud", icon: UIImage(systemName: "key.icloud")!), SampleData(name: "camera", icon: UIImage(systemName: "camera")!), SampleData(name: "message", icon: UIImage(systemName: "message")!), SampleData(name: "plus.message", icon: UIImage(systemName: "plus.message")!), SampleData(name: "bubble.right", icon: UIImage(systemName: "bubble.right")!), SampleData(name: "bubble.left", icon: UIImage(systemName: "bubble.left")!), SampleData(name: "exclamationmark.bubble", icon: UIImage(systemName: "exclamationmark.bubble")!), SampleData(name: "quote.bubble", icon: UIImage(systemName: "quote.bubble")!), SampleData(name: "t.bubble", icon: UIImage(systemName: "t.bubble")!), SampleData(name: "text.bubble", icon: UIImage(systemName: "text.bubble")!), SampleData(name: "captions.bubble", icon: UIImage(systemName: "captions.bubble")!), SampleData(name: "plus.bubble", icon: UIImage(systemName: "plus.bubble")!), SampleData(name: "ellipsis.bubble", icon: UIImage(systemName: "ellipsis.bubble")!), SampleData(name: "phone", icon: UIImage(systemName: "phone")!), SampleData(name: "phone.connection", icon: UIImage(systemName: "phone.connection")!), SampleData(name: "phone.down", icon: UIImage(systemName: "phone.down")!), SampleData(name: "teletype", icon: UIImage(systemName: "teletype")!), SampleData(name: "teletype.answer", icon: UIImage(systemName: "teletype.answer")!), SampleData(name: "video", icon: UIImage(systemName: "video")!), SampleData(name: "video.slash", icon: UIImage(systemName: "video.slash")!), SampleData(name: "questionmark.video", icon: UIImage(systemName: "questionmark.video")!), SampleData(name: "envelope", icon: UIImage(systemName: "envelope")!), SampleData(name: "envelope.open", icon: UIImage(systemName: "envelope.open")!), SampleData(name: "envelope.badge", icon: UIImage(systemName: "envelope.badge")!), SampleData(name: "mail.stack", icon: UIImage(systemName: "mail.stack")!), SampleData(name: "mail", icon: UIImage(systemName: "mail")!), SampleData(name: "gear", icon: UIImage(systemName: "gear")!), SampleData(name: "gearshape", icon: UIImage(systemName: "gearshape")!), SampleData(name: "gearshape.2", icon: UIImage(systemName: "gearshape.2")!), SampleData(name: "signature", icon: UIImage(systemName: "signature")!), SampleData(name: "scissors", icon: UIImage(systemName: "scissors")!), SampleData(name: "ellipsis", icon: UIImage(systemName: "ellipsis")!), SampleData(name: "ellipsis.rectangle", icon: UIImage(systemName: "ellipsis.rectangle")!), SampleData(name: "bag", icon: UIImage(systemName: "bag")!), SampleData(name: "cart", icon: UIImage(systemName: "cart")!), SampleData(name: "creditcard", icon: UIImage(systemName: "creditcard")!), SampleData(name: "giftcard", icon: UIImage(systemName: "giftcard")!), SampleData(name: "wallet.pass", icon: UIImage(systemName: "wallet.pass")!), SampleData(name: "crop", icon: UIImage(systemName: "crop")!), SampleData(name: "crop.rotate", icon: UIImage(systemName: "crop.rotate")!), SampleData(name: "dial.min", icon: UIImage(systemName: "dial.min")!), SampleData(name: "dial.max", icon: UIImage(systemName: "dial.max")!), SampleData(name: "gyroscope", icon: UIImage(systemName: "gyroscope")!), SampleData(name: "nosign", icon: UIImage(systemName: "nosign")!), SampleData(name: "gauge", icon: UIImage(systemName: "gauge")!), SampleData(name: "speedometer", icon: UIImage(systemName: "speedometer")!), SampleData(name: "barometer", icon: UIImage(systemName: "barometer")!), SampleData(name: "metronome", icon: UIImage(systemName: "metronome")!), SampleData(name: "amplifier", icon: UIImage(systemName: "amplifier")!), SampleData(name: "pianokeys", icon: UIImage(systemName: "pianokeys")!), SampleData(name: "pianokeys.inverse", icon: UIImage(systemName: "pianokeys.inverse")!), SampleData(name: "tuningfork", icon: UIImage(systemName: "tuningfork")!), SampleData(name: "paintbrush", icon: UIImage(systemName: "paintbrush")!), SampleData(name: "paintbrush.pointed", icon: UIImage(systemName: "paintbrush.pointed")!), SampleData(name: "bandage", icon: UIImage(systemName: "bandage")!), SampleData(name: "ruler", icon: UIImage(systemName: "ruler")!), SampleData(name: "level", icon: UIImage(systemName: "level")!), SampleData(name: "wrench", icon: UIImage(systemName: "wrench")!), SampleData(name: "hammer", icon: UIImage(systemName: "hammer")!), SampleData(name: "eyedropper", icon: UIImage(systemName: "eyedropper")!), SampleData(name: "eyedropper.halffull", icon: UIImage(systemName: "eyedropper.halffull")!), SampleData(name: "eyedropper.full", icon: UIImage(systemName: "eyedropper.full")!), SampleData(name: "applescript", icon: UIImage(systemName: "applescript")!), SampleData(name: "scroll", icon: UIImage(systemName: "scroll")!), SampleData(name: "stethoscope", icon: UIImage(systemName: "stethoscope")!), SampleData(name: "printer", icon: UIImage(systemName: "printer")!), SampleData(name: "printer.dotmatrix", icon: UIImage(systemName: "printer.dotmatrix")!), SampleData(name: "scanner", icon: UIImage(systemName: "scanner")!), SampleData(name: "faxmachine", icon: UIImage(systemName: "faxmachine")!), SampleData(name: "briefcase", icon: UIImage(systemName: "briefcase")!), SampleData(name: "case", icon: UIImage(systemName: "case")!), SampleData(name: "latch.2.case", icon: UIImage(systemName: "latch.2.case")!), SampleData(name: "cross.case", icon: UIImage(systemName: "cross.case")!), SampleData(name: "puzzlepiece", icon: UIImage(systemName: "puzzlepiece")!), SampleData(name: "homekit", icon: UIImage(systemName: "homekit")!), SampleData(name: "house", icon: UIImage(systemName: "house")!), SampleData(name: "building.columns", icon: UIImage(systemName: "building.columns")!), SampleData(name: "building", icon: UIImage(systemName: "building")!), SampleData(name: "building.2", icon: UIImage(systemName: "building.2")!), SampleData(name: "lock", icon: UIImage(systemName: "lock")!), SampleData(name: "lock.rectangle", icon: UIImage(systemName: "lock.rectangle")!), SampleData(name: "lock.shield", icon: UIImage(systemName: "lock.shield")!), SampleData(name: "lock.slash", icon: UIImage(systemName: "lock.slash")!), SampleData(name: "lock.open", icon: UIImage(systemName: "lock.open")!), SampleData(name: "lock.rotation", icon: UIImage(systemName: "lock.rotation")!), SampleData(name: "key", icon: UIImage(systemName: "key")!), SampleData(name: "wifi", icon: UIImage(systemName: "wifi")!), SampleData(name: "wifi.slash", icon: UIImage(systemName: "wifi.slash")!), SampleData(name: "wifi.exclamationmark", icon: UIImage(systemName: "wifi.exclamationmark")!), SampleData(name: "pin", icon: UIImage(systemName: "pin")!), SampleData(name: "pin.slash", icon: UIImage(systemName: "pin.slash")!), SampleData(name: "mappin", icon: UIImage(systemName: "mappin")!), SampleData(name: "mappin.slash", icon: UIImage(systemName: "mappin.slash")!), SampleData(name: "map", icon: UIImage(systemName: "map")!), SampleData(name: "safari", icon: UIImage(systemName: "safari")!), SampleData(name: "move.3d", icon: UIImage(systemName: "move.3d")!), SampleData(name: "scale.3d", icon: UIImage(systemName: "scale.3d")!), SampleData(name: "rotate.3d", icon: UIImage(systemName: "rotate.3d")!), SampleData(name: "torus", icon: UIImage(systemName: "torus")!), SampleData(name: "rotate.left", icon: UIImage(systemName: "rotate.left")!), SampleData(name: "rotate.right", icon: UIImage(systemName: "rotate.right")!), SampleData(name: "timeline.selection", icon: UIImage(systemName: "timeline.selection")!), SampleData(name: "cpu", icon: UIImage(systemName: "cpu")!), SampleData(name: "memorychip", icon: UIImage(systemName: "memorychip")!), SampleData(name: "opticaldisc", icon: UIImage(systemName: "opticaldisc")!), SampleData(name: "tv", icon: UIImage(systemName: "tv")!), SampleData(name: "4k.tv", icon: UIImage(systemName: "4k.tv")!), SampleData(name: "play.tv", icon: UIImage(systemName: "play.tv")!), SampleData(name: "photo.tv", icon: UIImage(systemName: "photo.tv")!), SampleData(name: "display", icon: UIImage(systemName: "display")!), SampleData(name: "display.2", icon: UIImage(systemName: "display.2")!), SampleData(name: "desktopcomputer", icon: UIImage(systemName: "desktopcomputer")!), SampleData(name: "pc", icon: UIImage(systemName: "pc")!), SampleData(name: "macpro.gen1", icon: UIImage(systemName: "macpro.gen1")!), SampleData(name: "macpro.gen2", icon: UIImage(systemName: "macpro.gen2")!), SampleData(name: "macpro.gen3", icon: UIImage(systemName: "macpro.gen3")!), SampleData(name: "server.rack", icon: UIImage(systemName: "server.rack")!), SampleData(name: "xserve", icon: UIImage(systemName: "xserve")!), SampleData(name: "macpro.gen3.server", icon: UIImage(systemName: "macpro.gen3.server")!), SampleData(name: "laptopcomputer", icon: UIImage(systemName: "laptopcomputer")!), SampleData(name: "macmini", icon: UIImage(systemName: "macmini")!), SampleData(name: "airport.express", icon: UIImage(systemName: "airport.express")!), SampleData(name: "airport.extreme", icon: UIImage(systemName: "airport.extreme")!), SampleData(name: "ipod", icon: UIImage(systemName: "ipod")!), SampleData(name: "flipphone", icon: UIImage(systemName: "flipphone")!), SampleData(name: "candybarphone", icon: UIImage(systemName: "candybarphone")!), SampleData(name: "iphone.homebutton", icon: UIImage(systemName: "iphone.homebutton")!), SampleData(name: "iphone", icon: UIImage(systemName: "iphone")!), SampleData(name: "iphone.landscape", icon: UIImage(systemName: "iphone.landscape")!), SampleData(name: "iphone.slash", icon: UIImage(systemName: "iphone.slash")!), SampleData(name: "apps.iphone", icon: UIImage(systemName: "apps.iphone")!), SampleData(name: "ipodtouch", icon: UIImage(systemName: "ipodtouch")!), SampleData(name: "ipodtouch.landscape", icon: UIImage(systemName: "ipodtouch.landscape")!), SampleData(name: "ipodshuffle.gen1", icon: UIImage(systemName: "ipodshuffle.gen1")!), SampleData(name: "ipodshuffle.gen2", icon: UIImage(systemName: "ipodshuffle.gen2")!), SampleData(name: "ipodshuffle.gen3", icon: UIImage(systemName: "ipodshuffle.gen3")!), SampleData(name: "ipodshuffle.gen4", icon: UIImage(systemName: "ipodshuffle.gen4")!), SampleData(name: "ipad.homebutton", icon: UIImage(systemName: "ipad.homebutton")!), SampleData(name: "ipad", icon: UIImage(systemName: "ipad")!), SampleData(name: "apps.ipad", icon: UIImage(systemName: "apps.ipad")!), SampleData(name: "ipad.landscape", icon: UIImage(systemName: "ipad.landscape")!), SampleData(name: "applewatch", icon: UIImage(systemName: "applewatch")!), SampleData(name: "applewatch.watchface", icon: UIImage(systemName: "applewatch.watchface")!), SampleData(name: "exclamationmark.applewatch", icon: UIImage(systemName: "exclamationmark.applewatch")!), SampleData(name: "lock.applewatch", icon: UIImage(systemName: "lock.applewatch")!), SampleData(name: "applewatch.slash", icon: UIImage(systemName: "applewatch.slash")!), SampleData(name: "earpods", icon: UIImage(systemName: "earpods")!), SampleData(name: "airpods", icon: UIImage(systemName: "airpods")!), SampleData(name: "airpod.right", icon: UIImage(systemName: "airpod.right")!), SampleData(name: "airpod.left", icon: UIImage(systemName: "airpod.left")!), SampleData(name: "airpodspro", icon: UIImage(systemName: "airpodspro")!), SampleData(name: "airpodpro.right", icon: UIImage(systemName: "airpodpro.right")!), SampleData(name: "airpodpro.left", icon: UIImage(systemName: "airpodpro.left")!), SampleData(name: "homepod", icon: UIImage(systemName: "homepod")!), SampleData(name: "homepod.2", icon: UIImage(systemName: "homepod.2")!), SampleData(name: "hifispeaker", icon: UIImage(systemName: "hifispeaker")!), SampleData(name: "hifispeaker.2", icon: UIImage(systemName: "hifispeaker.2")!), SampleData(name: "radio", icon: UIImage(systemName: "radio")!), SampleData(name: "appletv", icon: UIImage(systemName: "appletv")!), SampleData(name: "signpost.left", icon: UIImage(systemName: "signpost.left")!), SampleData(name: "signpost.right", icon: UIImage(systemName: "signpost.right")!), SampleData(name: "airplayvideo", icon: UIImage(systemName: "airplayvideo")!), SampleData(name: "airplayaudio", icon: UIImage(systemName: "airplayaudio")!), SampleData(name: "wave.3.left", icon: UIImage(systemName: "wave.3.left")!), SampleData(name: "wave.3.backward", icon: UIImage(systemName: "wave.3.backward")!), SampleData(name: "wave.3.right", icon: UIImage(systemName: "wave.3.right")!), SampleData(name: "wave.3.forward", icon: UIImage(systemName: "wave.3.forward")!), SampleData(name: "pip", icon: UIImage(systemName: "pip")!), SampleData(name: "pip.exit", icon: UIImage(systemName: "pip.exit")!), SampleData(name: "pip.enter", icon: UIImage(systemName: "pip.enter")!), SampleData(name: "pip.swap", icon: UIImage(systemName: "pip.swap")!), SampleData(name: "pip.remove", icon: UIImage(systemName: "pip.remove")!), SampleData(name: "guitars", icon: UIImage(systemName: "guitars")!), SampleData(name: "car", icon: UIImage(systemName: "car")!), SampleData(name: "bolt.car", icon: UIImage(systemName: "bolt.car")!), SampleData(name: "car.2", icon: UIImage(systemName: "car.2")!), SampleData(name: "bus", icon: UIImage(systemName: "bus")!), SampleData(name: "bus.doubledecker", icon: UIImage(systemName: "bus.doubledecker")!), SampleData(name: "tram", icon: UIImage(systemName: "tram")!), SampleData(name: "bicycle", icon: UIImage(systemName: "bicycle")!), SampleData(name: "bed.double", icon: UIImage(systemName: "bed.double")!), SampleData(name: "lungs", icon: UIImage(systemName: "lungs")!), SampleData(name: "pills", icon: UIImage(systemName: "pills")!), SampleData(name: "cross", icon: UIImage(systemName: "cross")!), SampleData(name: "hare", icon: UIImage(systemName: "hare")!), SampleData(name: "tortoise", icon: UIImage(systemName: "tortoise")!), SampleData(name: "ant", icon: UIImage(systemName: "ant")!), SampleData(name: "ladybug", icon: UIImage(systemName: "ladybug")!), SampleData(name: "leaf", icon: UIImage(systemName: "leaf")!), SampleData(name: "film", icon: UIImage(systemName: "film")!), SampleData(name: "sportscourt", icon: UIImage(systemName: "sportscourt")!), SampleData(name: "face.smiling", icon: UIImage(systemName: "face.smiling")!), SampleData(name: "face.dashed", icon: UIImage(systemName: "face.dashed")!), SampleData(name: "crown", icon: UIImage(systemName: "crown")!), SampleData(name: "comb", icon: UIImage(systemName: "comb")!), SampleData(name: "qrcode", icon: UIImage(systemName: "qrcode")!), SampleData(name: "barcode", icon: UIImage(systemName: "barcode")!), SampleData(name: "viewfinder", icon: UIImage(systemName: "viewfinder")!), SampleData(name: "barcode.viewfinder", icon: UIImage(systemName: "barcode.viewfinder")!), SampleData(name: "qrcode.viewfinder", icon: UIImage(systemName: "qrcode.viewfinder")!), SampleData(name: "plus.viewfinder", icon: UIImage(systemName: "plus.viewfinder")!), SampleData(name: "camera.viewfinder", icon: UIImage(systemName: "camera.viewfinder")!), SampleData(name: "faceid", icon: UIImage(systemName: "faceid")!), SampleData(name: "location.viewfinder", icon: UIImage(systemName: "location.viewfinder")!), SampleData(name: "photo", icon: UIImage(systemName: "photo")!), SampleData(name: "checkerboard.rectangle", icon: UIImage(systemName: "checkerboard.rectangle")!), SampleData(name: "camera.aperture", icon: UIImage(systemName: "camera.aperture")!), SampleData(name: "rectangle.dashed", icon: UIImage(systemName: "rectangle.dashed")!), SampleData(name: "sidebar.left", icon: UIImage(systemName: "sidebar.left")!), SampleData(name: "sidebar.right", icon: UIImage(systemName: "sidebar.right")!), SampleData(name: "sidebar.leading", icon: UIImage(systemName: "sidebar.leading")!), SampleData(name: "sidebar.trailing", icon: UIImage(systemName: "sidebar.trailing")!), SampleData(name: "macwindow", icon: UIImage(systemName: "macwindow")!), SampleData(name: "dock.rectangle", icon: UIImage(systemName: "dock.rectangle")!), SampleData(name: "menubar.rectangle", icon: UIImage(systemName: "menubar.rectangle")!), SampleData(name: "keyboard.macwindow", icon: UIImage(systemName: "keyboard.macwindow")!), SampleData(name: "mosaic", icon: UIImage(systemName: "mosaic")!), SampleData(name: "tablecells", icon: UIImage(systemName: "tablecells")!), SampleData(name: "rectangle.stack", icon: UIImage(systemName: "rectangle.stack")!), SampleData(name: "square.stack", icon: UIImage(systemName: "square.stack")!), SampleData(name: "pano", icon: UIImage(systemName: "pano")!), SampleData(name: "flowchart", icon: UIImage(systemName: "flowchart")!), SampleData(name: "shield", icon: UIImage(systemName: "shield")!), SampleData(name: "shield.slash", icon: UIImage(systemName: "shield.slash")!), SampleData(name: "shield.checkerboard", icon: UIImage(systemName: "shield.checkerboard")!), SampleData(name: "switch.2", icon: UIImage(systemName: "switch.2")!), SampleData(name: "cube", icon: UIImage(systemName: "cube")!), SampleData(name: "cube.transparent", icon: UIImage(systemName: "cube.transparent")!), SampleData(name: "shippingbox", icon: UIImage(systemName: "shippingbox")!), SampleData(name: "arkit", icon: UIImage(systemName: "arkit")!), SampleData(name: "cone", icon: UIImage(systemName: "cone")!), SampleData(name: "pyramid", icon: UIImage(systemName: "pyramid")!), SampleData(name: "livephoto", icon: UIImage(systemName: "livephoto")!), SampleData(name: "livephoto.slash", icon: UIImage(systemName: "livephoto.slash")!), SampleData(name: "livephoto.play", icon: UIImage(systemName: "livephoto.play")!), SampleData(name: "scope", icon: UIImage(systemName: "scope")!), SampleData(name: "helm", icon: UIImage(systemName: "helm")!), SampleData(name: "clock", icon: UIImage(systemName: "clock")!), SampleData(name: "deskclock", icon: UIImage(systemName: "deskclock")!), SampleData(name: "alarm", icon: UIImage(systemName: "alarm")!), SampleData(name: "stopwatch", icon: UIImage(systemName: "stopwatch")!), SampleData(name: "timer", icon: UIImage(systemName: "timer")!), SampleData(name: "gamecontroller", icon: UIImage(systemName: "gamecontroller")!), SampleData(name: "l.joystick", icon: UIImage(systemName: "l.joystick")!), SampleData(name: "r.joystick", icon: UIImage(systemName: "r.joystick")!), SampleData(name: "dpad", icon: UIImage(systemName: "dpad")!), SampleData(name: "rectangle.roundedtop", icon: UIImage(systemName: "rectangle.roundedtop")!), SampleData(name: "rectangle.roundedbottom", icon: UIImage(systemName: "rectangle.roundedbottom")!), SampleData(name: "paintpalette", icon: UIImage(systemName: "paintpalette")!), SampleData(name: "figure.walk", icon: UIImage(systemName: "figure.walk")!), SampleData(name: "figure.stand", icon: UIImage(systemName: "figure.stand")!), SampleData(name: "figure.wave", icon: UIImage(systemName: "figure.wave")!), SampleData(name: "ear", icon: UIImage(systemName: "ear")!), SampleData(name: "hearingaid.ear", icon: UIImage(systemName: "hearingaid.ear")!), SampleData(name: "hand.raised", icon: UIImage(systemName: "hand.raised")!), SampleData(name: "hand.thumbsup", icon: UIImage(systemName: "hand.thumbsup")!), SampleData(name: "hand.thumbsdown", icon: UIImage(systemName: "hand.thumbsdown")!), SampleData(name: "hand.draw", icon: UIImage(systemName: "hand.draw")!), SampleData(name: "hand.tap", icon: UIImage(systemName: "hand.tap")!), SampleData(name: "hand.wave", icon: UIImage(systemName: "hand.wave")!), SampleData(name: "hands.clap", icon: UIImage(systemName: "hands.clap")!), SampleData(name: "hands.sparkles", icon: UIImage(systemName: "hands.sparkles")!), SampleData(name: "cylinder", icon: UIImage(systemName: "cylinder")!), SampleData(name: "chart.bar", icon: UIImage(systemName: "chart.bar")!), SampleData(name: "chart.pie", icon: UIImage(systemName: "chart.pie")!), SampleData(name: "burst", icon: UIImage(systemName: "burst")!), SampleData(name: "waveform.path", icon: UIImage(systemName: "waveform.path")!), SampleData(name: "waveform", icon: UIImage(systemName: "waveform")!), SampleData(name: "staroflife", icon: UIImage(systemName: "staroflife")!), SampleData(name: "simcard", icon: UIImage(systemName: "simcard")!), SampleData(name: "simcard.2", icon: UIImage(systemName: "simcard.2")!), SampleData(name: "esim", icon: UIImage(systemName: "esim")!), SampleData(name: "sdcard", icon: UIImage(systemName: "sdcard")!), SampleData(name: "touchid", icon: UIImage(systemName: "touchid")!), SampleData(name: "bonjour", icon: UIImage(systemName: "bonjour")!), SampleData(name: "atom", icon: UIImage(systemName: "atom")!), SampleData(name: "scalemass", icon: UIImage(systemName: "scalemass")!), SampleData(name: "headphones", icon: UIImage(systemName: "headphones")!), SampleData(name: "gift", icon: UIImage(systemName: "gift")!), SampleData(name: "plus.app", icon: UIImage(systemName: "plus.app")!), SampleData(name: "app.badge", icon: UIImage(systemName: "app.badge")!), SampleData(name: "appclip", icon: UIImage(systemName: "appclip")!), SampleData(name: "app.gift", icon: UIImage(systemName: "app.gift")!), SampleData(name: "airplane", icon: UIImage(systemName: "airplane")!), SampleData(name: "studentdesk", icon: UIImage(systemName: "studentdesk")!), SampleData(name: "hourglass", icon: UIImage(systemName: "hourglass")!), SampleData(name: "banknote", icon: UIImage(systemName: "banknote")!), SampleData(name: "paragraphsign", icon: UIImage(systemName: "paragraphsign")!), SampleData(name: "purchased", icon: UIImage(systemName: "purchased")!), SampleData(name: "perspective", icon: UIImage(systemName: "perspective")!), SampleData(name: "aspectratio", icon: UIImage(systemName: "aspectratio")!), SampleData(name: "camera.filters", icon: UIImage(systemName: "camera.filters")!), SampleData(name: "skew", icon: UIImage(systemName: "skew")!), SampleData(name: "grid", icon: UIImage(systemName: "grid")!), SampleData(name: "burn", icon: UIImage(systemName: "burn")!), SampleData(name: "lifepreserver", icon: UIImage(systemName: "lifepreserver")!), SampleData(name: "recordingtape", icon: UIImage(systemName: "recordingtape")!), SampleData(name: "eyeglasses", icon: UIImage(systemName: "eyeglasses")!), SampleData(name: "binoculars", icon: UIImage(systemName: "binoculars")!), SampleData(name: "battery.100", icon: UIImage(systemName: "battery.100")!), SampleData(name: "battery.25", icon: UIImage(systemName: "battery.25")!), SampleData(name: "battery.0", icon: UIImage(systemName: "battery.0")!), SampleData(name: "battery.100.bolt", icon: UIImage(systemName: "battery.100.bolt")!), SampleData(name: "lightbulb", icon: UIImage(systemName: "lightbulb")!), SampleData(name: "lightbulb.slash", icon: UIImage(systemName: "lightbulb.slash")!), SampleData(name: "fiberchannel", icon: UIImage(systemName: "fiberchannel")!), SampleData(name: "list.dash", icon: UIImage(systemName: "list.dash")!), SampleData(name: "list.bullet", icon: UIImage(systemName: "list.bullet")!), SampleData(name: "list.triangle", icon: UIImage(systemName: "list.triangle")!), SampleData(name: "list.number", icon: UIImage(systemName: "list.number")!), SampleData(name: "list.star", icon: UIImage(systemName: "list.star")!), SampleData(name: "increase.indent", icon: UIImage(systemName: "increase.indent")!), SampleData(name: "decrease.indent", icon: UIImage(systemName: "decrease.indent")!), SampleData(name: "decrease.quotelevel", icon: UIImage(systemName: "decrease.quotelevel")!), SampleData(name: "increase.quotelevel", icon: UIImage(systemName: "increase.quotelevel")!), SampleData(name: "text.insert", icon: UIImage(systemName: "text.insert")!), SampleData(name: "text.append", icon: UIImage(systemName: "text.append")!), SampleData(name: "text.quote", icon: UIImage(systemName: "text.quote")!), SampleData(name: "text.alignleft", icon: UIImage(systemName: "text.alignleft")!), SampleData(name: "text.aligncenter", icon: UIImage(systemName: "text.aligncenter")!), SampleData(name: "text.alignright", icon: UIImage(systemName: "text.alignright")!), SampleData(name: "text.justify", icon: UIImage(systemName: "text.justify")!), SampleData(name: "text.justifyleft", icon: UIImage(systemName: "text.justifyleft")!), SampleData(name: "text.justifyright", icon: UIImage(systemName: "text.justifyright")!), SampleData(name: "text.redaction", icon: UIImage(systemName: "text.redaction")!), SampleData(name: "character", icon: UIImage(systemName: "character")!), SampleData(name: "abc", icon: UIImage(systemName: "abc")!), SampleData(name: "textformat.alt", icon: UIImage(systemName: "textformat.alt")!), SampleData(name: "textformat", icon: UIImage(systemName: "textformat")!), SampleData(name: "textformat.size", icon: UIImage(systemName: "textformat.size")!), SampleData(name: "textformat.superscript", icon: UIImage(systemName: "textformat.superscript")!), SampleData(name: "textformat.subscript", icon: UIImage(systemName: "textformat.subscript")!), SampleData(name: "bold", icon: UIImage(systemName: "bold")!), SampleData(name: "italic", icon: UIImage(systemName: "italic")!), SampleData(name: "underline", icon: UIImage(systemName: "underline")!), SampleData(name: "strikethrough", icon: UIImage(systemName: "strikethrough")!), SampleData(name: "shadow", icon: UIImage(systemName: "shadow")!), SampleData(name: "bold.underline", icon: UIImage(systemName: "bold.underline")!), SampleData(name: "view.2d", icon: UIImage(systemName: "view.2d")!), SampleData(name: "view.3d", icon: UIImage(systemName: "view.3d")!), SampleData(name: "text.cursor", icon: UIImage(systemName: "text.cursor")!), SampleData(name: "fx", icon: UIImage(systemName: "fx")!), SampleData(name: "f.cursive", icon: UIImage(systemName: "f.cursive")!), SampleData(name: "k", icon: UIImage(systemName: "k")!), SampleData(name: "sum", icon: UIImage(systemName: "sum")!), SampleData(name: "percent", icon: UIImage(systemName: "percent")!), SampleData(name: "function", icon: UIImage(systemName: "function")!), SampleData(name: "textformat.abc", icon: UIImage(systemName: "textformat.abc")!), SampleData(name: "fn", icon: UIImage(systemName: "fn")!), SampleData(name: "textformat.123", icon: UIImage(systemName: "textformat.123")!), SampleData(name: "textbox", icon: UIImage(systemName: "textbox")!), SampleData(name: "a.magnify", icon: UIImage(systemName: "a.magnify")!), SampleData(name: "info", icon: UIImage(systemName: "info")!), SampleData(name: "at", icon: UIImage(systemName: "at")!), SampleData(name: "questionmark", icon: UIImage(systemName: "questionmark")!), SampleData(name: "questionmark.diamond", icon: UIImage(systemName: "questionmark.diamond")!), SampleData(name: "exclamationmark", icon: UIImage(systemName: "exclamationmark")!), SampleData(name: "exclamationmark.2", icon: UIImage(systemName: "exclamationmark.2")!), SampleData(name: "exclamationmark.3", icon: UIImage(systemName: "exclamationmark.3")!), SampleData(name: "exclamationmark.octagon", icon: UIImage(systemName: "exclamationmark.octagon")!), SampleData(name: "exclamationmark.shield", icon: UIImage(systemName: "exclamationmark.shield")!), SampleData(name: "plus", icon: UIImage(systemName: "plus")!), SampleData(name: "plus.rectangle", icon: UIImage(systemName: "plus.rectangle")!), SampleData(name: "plus.diamond", icon: UIImage(systemName: "plus.diamond")!), SampleData(name: "minus", icon: UIImage(systemName: "minus")!), SampleData(name: "minus.rectangle", icon: UIImage(systemName: "minus.rectangle")!), SampleData(name: "minus.diamond", icon: UIImage(systemName: "minus.diamond")!), SampleData(name: "plusminus", icon: UIImage(systemName: "plusminus")!), SampleData(name: "multiply", icon: UIImage(systemName: "multiply")!), SampleData(name: "xmark.rectangle", icon: UIImage(systemName: "xmark.rectangle")!), SampleData(name: "xmark.diamond", icon: UIImage(systemName: "xmark.diamond")!), SampleData(name: "xmark.shield", icon: UIImage(systemName: "xmark.shield")!), SampleData(name: "xmark.octagon", icon: UIImage(systemName: "xmark.octagon")!), SampleData(name: "divide", icon: UIImage(systemName: "divide")!), SampleData(name: "equal", icon: UIImage(systemName: "equal")!), SampleData(name: "lessthan", icon: UIImage(systemName: "lessthan")!), SampleData(name: "greaterthan", icon: UIImage(systemName: "greaterthan")!), SampleData(name: "curlybraces", icon: UIImage(systemName: "curlybraces")!), SampleData(name: "number", icon: UIImage(systemName: "number")!), SampleData(name: "x.squareroot", icon: UIImage(systemName: "x.squareroot")!), SampleData(name: "xmark", icon: UIImage(systemName: "xmark")!), SampleData(name: "checkmark", icon: UIImage(systemName: "checkmark")!), SampleData(name: "checkmark.rectangle", icon: UIImage(systemName: "checkmark.rectangle")!), SampleData(name: "checkmark.shield", icon: UIImage(systemName: "checkmark.shield")!), SampleData(name: "chevron.left", icon: UIImage(systemName: "chevron.left")!), SampleData(name: "chevron.backward", icon: UIImage(systemName: "chevron.backward")!), SampleData(name: "chevron.right", icon: UIImage(systemName: "chevron.right")!), SampleData(name: "chevron.forward", icon: UIImage(systemName: "chevron.forward")!), SampleData(name: "chevron.up", icon: UIImage(systemName: "chevron.up")!), SampleData(name: "chevron.down", icon: UIImage(systemName: "chevron.down")!), SampleData(name: "control", icon: UIImage(systemName: "control")!), SampleData(name: "projective", icon: UIImage(systemName: "projective")!), SampleData(name: "arrow.left", icon: UIImage(systemName: "arrow.left")!), SampleData(name: "arrow.backward", icon: UIImage(systemName: "arrow.backward")!), SampleData(name: "arrow.right", icon: UIImage(systemName: "arrow.right")!), SampleData(name: "arrow.forward", icon: UIImage(systemName: "arrow.forward")!), SampleData(name: "arrow.up", icon: UIImage(systemName: "arrow.up")!), SampleData(name: "arrow.down", icon: UIImage(systemName: "arrow.down")!), SampleData(name: "arrow.clockwise", icon: UIImage(systemName: "arrow.clockwise")!), SampleData(name: "arrow.counterclockwise", icon: UIImage(systemName: "arrow.counterclockwise")!), SampleData(name: "return", icon: UIImage(systemName: "return")!), SampleData(name: "arrow.2.squarepath", icon: UIImage(systemName: "arrow.2.squarepath")!), SampleData(name: "arrow.3.trianglepath", icon: UIImage(systemName: "arrow.3.trianglepath")!), SampleData(name: "arrowtriangle.left", icon: UIImage(systemName: "arrowtriangle.left")!), SampleData(name: "arrowtriangle.backward", icon: UIImage(systemName: "arrowtriangle.backward")!), SampleData(name: "arrowtriangle.right", icon: UIImage(systemName: "arrowtriangle.right")!), SampleData(name: "arrowtriangle.forward", icon: UIImage(systemName: "arrowtriangle.forward")!), SampleData(name: "arrowtriangle.up", icon: UIImage(systemName: "arrowtriangle.up")!), SampleData(name: "arrowtriangle.down", icon: UIImage(systemName: "arrowtriangle.down")!), SampleData(name: "applelogo", icon: UIImage(systemName: "applelogo")!) ] } } ``` ## KeyCommandsSample.swift ```swift /* Abstract: Example showing a custom key command provided by the view controller. */ import UIKit struct KeyCommandsSample: MenuDescribable { static var title = "Key Commands" static var iconName = "command" static var description = """ This example shows a custom key command that the view controller provides but whoes method is implemented on each cell individually. The cell then generates a delegate callback from this to let the controller know to delete an item at the currently focused index path. Focus on a cell and press the delete key to delete the item. """ static func create() -> UIViewController { KeyCommandsSampleViewController() } } @objc protocol KeyCommandCollectionViewDelegate: UICollectionViewDelegate { @objc optional func collectionView(_ collectionView: UICollectionView, wantsToRemoveItemAt indexPath: IndexPath) } class KeyCommandSampleCell: CustomCollectionViewCell { private var collectionView: UICollectionView? { var view = self.superview while view != nil && !view!.isKind(of: UICollectionView.self) { view = view!.superview } return view as? UICollectionView } @objc func remove(_ sender: Any) { guard let collectionView = collectionView else { return } guard let indexPath = collectionView.indexPath(for: self) else { return } guard let delegate = collectionView.delegate as? KeyCommandCollectionViewDelegate else { return } delegate.collectionView?(collectionView, wantsToRemoveItemAt: indexPath) } } extension KeyCommandsSampleViewController: KeyCommandCollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, wantsToRemoveItemAt indexPath: IndexPath) { guard let dataSource = self.dataSource else { fatalError("Something is wrong with our internal state. We should never get this method if we don't have a data source.") } guard let itemIdentifierToRemove = dataSource.itemIdentifier(for: indexPath) else { return } var snapshot = dataSource.snapshot() snapshot.deleteItems([itemIdentifierToRemove]) self.dataSource?.apply(snapshot, animatingDifferences: true) } } class KeyCommandsSampleViewController: UICollectionViewController { private var dataSource: UICollectionViewDiffableDataSource<Int, SampleData>? init() { super.init(collectionViewLayout: KeyCommandsSampleViewController.createLayout()) let cellRegistration = UICollectionView.CellRegistration<KeyCommandSampleCell, SampleData>(handler: { cell, indexPath, data in cell.data = data }) let dataSource = SampleData.createSampleDataSource(collectionView: self.collectionView, cellRegistration: cellRegistration) self.dataSource = dataSource self.collectionView.allowsFocus = true // We add the key command to the view controller, but because the cells are the start of the responder chain // when they are focused, their remove(_:) method is actually called. let keyCommand = UIKeyCommand(title: "Delete Symbol", action: #selector(remove(_:)), input: UIKeyCommand.inputDelete, modifierFlags: .command) self.addKeyCommand(keyCommand) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func remove(_ sender: Any) { // Just make sure noone above us gets this call so that we don't // accidentally trigger someone elses remove method. // Also this means we can reference the selector directly when creating the key command instead of referencing // the cell class even though we are not actually limiting the call to that class. } private class func createLayout() -> UICollectionViewLayout { let estimated = NSCollectionLayoutDimension.estimated(Layout.defaultSpacing * 3.0) let itemSize = NSCollectionLayoutSize(widthDimension: estimated, heightDimension: estimated) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: estimated) let group: NSCollectionLayoutGroup = .horizontal(layoutSize: groupSize, subitems: [item]) group.interItemSpacing = .flexible(Layout.defaultSpacing) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = Layout.defaultSpacing let inset = Layout.defaultSpacing section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset) let layout = UICollectionViewCompositionalLayout(section: section) return layout } } ``` ## SearchResultsSample.swift ```swift /* Abstract: Example showing search of a list of SF symbols in a given focus group. */ import UIKit struct SearchResultsSample: MenuDescribable { static var title = "Search Results" static var iconName = "magnifyingglass" static var description = """ Shows a custom search bar that is put into the same focus group than the \ collection view showing the search results. This allows the user to press the \ arrow down key to move focus from the search text field into the search results \ and then navigate the search results with the arrow keys while still being able \ to type into the search field. """ static func create() -> UIViewController { SearchResultsSampleViewController() } } // MARK: - UISearchBarDelegate extension SearchResultsSampleViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let results = !searchText.isEmpty ? self.allData?.filter({ $0.name.lowercased().contains(searchText.lowercased()) }) : self.allData var snapshot = NSDiffableDataSourceSnapshot<Int, SampleData>() snapshot.appendSections([0]) snapshot.appendItems(results!) self.dataSource?.apply(snapshot, animatingDifferences: true) if !searchText.isEmpty { // Actively searching. self.collectionView.focusGroupIdentifier = searchBar.focusGroupIdentifier } else { // No searching, treat the collection view as its own group. self.collectionView.focusGroupIdentifier = FocusGroups.searchResults } } } // MARK: - SearchResultsSampleViewController class SearchResultsSampleViewController: UICollectionViewController { private var allData: [SampleData]? private var dataSource: UICollectionViewDiffableDataSource<Int, SampleData>? init() { super.init(collectionViewLayout: SearchResultsSampleViewController.createLayout()) let cellRegistration = UICollectionView.CellRegistration<CustomCollectionViewCell, SampleData>(handler: { cell, indexPath, data in cell.data = data }) let dataSource = SampleData.createSampleDataSource(collectionView: self.collectionView, cellRegistration: cellRegistration) self.dataSource = dataSource self.allData = dataSource.snapshot().itemIdentifiers self.collectionView.allowsFocus = true let searchBar = UISearchBar() searchBar.sizeToFit() searchBar.frame.size.width = 320.0 searchBar.delegate = self self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchBar) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private class func createLayout() -> UICollectionViewLayout { let estimated = NSCollectionLayoutDimension.estimated(Layout.defaultSpacing * 3.0) let itemSize = NSCollectionLayoutSize(widthDimension: estimated, heightDimension: estimated) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: estimated) let group: NSCollectionLayoutGroup = .horizontal(layoutSize: groupSize, subitems: [item]) group.interItemSpacing = .flexible(Layout.defaultSpacing) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = Layout.defaultSpacing let inset = Layout.defaultSpacing section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset) let layout = UICollectionViewCompositionalLayout(section: section) return layout } } ``` ## SelectionSample.swift ```swift /* Abstract: Example showing a 2x2 grid using a selection gesture recognizer. */ import UIKit struct SelectionSample: MenuDescribable { static var title = "Selection" static var iconName = "hand.tap" static var description = """ Shows a 2x2 grid of focusable items that have a selection gesture recognizer \ attached to them. When the user selects them by hitting return (iPad OS) or \ space (Mac Catalyst), they flash briefly in the tint color. """ static func create() -> UIViewController { GridViewController<SelectionFocusView>() } } class SelectionFocusView: FocusableView { override init(frame: CGRect) { super.init(frame: frame) // Add a gesture recognizer that triggers when the user triggers focus selection (return). let selectGesture = UITapGestureRecognizer(target: self, action: #selector(select(_:))) selectGesture.allowedTouchTypes = [] selectGesture.allowedPressTypes = [ UIPress.PressType.select.rawValue as NSNumber ] self.addGestureRecognizer(selectGesture) // Add a gesture recognizer that triggers when the user touches. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(select(_:))) // Nothing to configure here, a single touch is the default. self.addGestureRecognizer(tapGesture) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc override func select(_ sender: Any?) { self.backgroundColor = .tintColor UIView.animate(withDuration: 1.0, delay: 0.5, options: [.curveEaseOut, .allowUserInteraction], animations: { self.backgroundColor = .secondarySystemFill }) } } ``` ## AppDelegate.swift ```swift /* Abstract: This sample's application delegate. */ import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { /* Pre-load the stack view window controller and its content view controller. Used for state restoration and opening its window via the "Show Stack View" button. */ var stackViewWindowController = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "WindowController") as? WindowController } ``` ## BaseViewController.swift ```swift /* Abstract: Base view controller to be subclassed for any view controller in the stack view. */ import Cocoa class BaseViewController: NSViewController, StackItemBody { @IBOutlet var heightConstraint: NSLayoutConstraint! // The original expanded height of this view controller (used to adjust height between disclosure states). var savedDefaultHeight: CGFloat = 0 // Subclasses determine the header title. func headerTitle() -> String { return "" } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // Remember the default height for disclosing later (subclasses can determine this value in their own viewDidLoad). savedDefaultHeight = view.bounds.height } // MARK: - StackItemContainer lazy var stackItemContainer: StackItemContainer? = { /* We conditionally decide what flavor of header disclosure to use by "DisclosureTriangleAppearance" compilation flag, which is defined in �Active Compilation Conditions� Build Settings (for passing conditional compilation flags to the Swift compiler). If you want to use the non-triangle disclosure version, remove that flag. */ var storyboardIdentifier: String #if DisclosureTriangleAppearance storyboardIdentifier = "HeaderTriangleViewController" #else storyboardIdentifier = "HeaderViewController" #endif let storyboard = NSStoryboard(name: "HeaderViewController", bundle: nil) guard let headerViewController = storyboard.instantiateController(withIdentifier: storyboardIdentifier) as? HeaderViewController else { return .none } headerViewController.title = self.headerTitle() return StackItemContainer(header: headerViewController, body: self) }() } extension BaseViewController { /// Encode state. Helps save the restorable state of this view controller. override func encodeRestorableState(with coder: NSCoder) { // Encode the disclosure state. if let container = stackItemContainer { // Use the header's title as the encoding key. coder.encode(container.state, forKey: String(describing: headerTitle())) } super.encodeRestorableState(with: coder) } /// Decode state. Helps restore any previously stored state. override func restoreState(with coder: NSCoder) { super.restoreState(with: coder) // Restore the disclosure state, use the header's title as the decoding key. if let disclosureState = coder.decodeObject(forKey: headerTitle()) as? NSControl.StateValue { if let container = stackItemContainer { container.state = disclosureState // Expand/collapse the container's body view controller. switch container.state { case .on: container.body.show(animated: false) case .off: container.body.hide(animated: false) default: break } // Update the header's disclosure. container.header.update(toDisclosureState: container.state) } } } } ``` ## CollectionItem.swift ```swift /* Abstract: NSCollectionViewItem subclass custom rendering of selected items. */ import Cocoa // A collection item displays an image. class CollectionItem: NSCollectionViewItem { // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true } override var isSelected: Bool { didSet { if isSelected { // Create visual feedback for the selected collection view item. view.layer?.borderColor = NSColor.lightGray.cgColor view.layer?.borderWidth = 4 } else { view.layer?.borderWidth = 0 } } } } ``` ## CollectionViewController.swift ```swift /* Abstract: Stack item view controller for displaying a simple NSCollectionView of images. */ import Cocoa class CollectionViewController: BaseViewController, NSCollectionViewDataSource, NSCollectionViewDelegate { // The image names for each collection view item. enum SceneImage: String { case scene1, scene2, scene3, scene4 } @IBOutlet weak var collection: NSCollectionView! private static let collectionItemIdentifier = "CollectionItem" override func headerTitle() -> String { return NSLocalizedString("Images Header Title", comment: "") } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // We want a special background color drawn for the collectionView. if let backgroundColor = NSColor(named: "CollectionViewBackgroundColor") { collection.backgroundColors = [backgroundColor] } // Compute the default height of this view so later we can hide/show it later. let size = collection.collectionViewLayout?.collectionViewContentSize savedDefaultHeight = size!.height // Must register the cell we're going to use for display in the collection. collection.register(CollectionItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(CollectionViewController.collectionItemIdentifier)) collection.enclosingScrollView?.borderType = .noBorder collection.reloadData() } // MARK: - NSCollectionViewDataSource func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func numberOfSections(in collectionView: NSCollectionView) -> Int { return 1 } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { // Determine the image to be assigned to this collection view item. let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(CollectionViewController.collectionItemIdentifier), for: indexPath) guard let collectionViewItem = item as? CollectionItem else { return item } // Decide which image name to use for each index path. var imageName = "" switch (indexPath as NSIndexPath).item { case 0: imageName = SceneImage.scene1.rawValue case 1: imageName = SceneImage.scene2.rawValue case 2: imageName = SceneImage.scene3.rawValue case 3: imageName = SceneImage.scene4.rawValue default: break } collectionViewItem.imageView?.image = NSImage(named: imageName) return collectionViewItem } // MARK: - NSCollectionViewDelegate func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) { debugPrint("collectionView: didSelectItemsAt: (indexPaths)") // Invalidate state restoration, which will in turn eventually call "encodeRestorableState". invalidateRestorableState() } } // MARK: - State Restoration extension CollectionViewController { // Restorable key for the collection view's selection. private static let collectionViewSelectionKey = "collectionViewSelectionKey" /// Encode state. Helps save the restorable state of this view controller. override func encodeRestorableState(with coder: NSCoder) { coder.encode(collection.selectionIndexes, forKey: CollectionViewController.collectionViewSelectionKey) super.encodeRestorableState(with: coder) } /// Decode state. Helps restore any previously stored state of the collection view's selection. override func restoreState(with coder: NSCoder) { super.restoreState(with: coder) if let decodedSelection = coder.decodeObject(forKey: CollectionViewController.collectionViewSelectionKey) as? IndexSet { collection.selectionIndexes = decodedSelection } } } ``` ## FormViewController.swift ```swift /* Abstract: Stack item view controller for an example "form" UI. */ import Cocoa class FormViewController: BaseViewController, NSTextFieldDelegate { @IBOutlet weak var textField: NSTextField! override func headerTitle() -> String { return NSLocalizedString("Form Header Title", comment: "") } // MARK: - NSTextFieldDelegate func controlTextDidChange(_ obj: Notification) { // Invalidate state restoration, which will in turn eventually call "encodeRestorableState". invalidateRestorableState() } } // MARK: - State Restoration extension FormViewController { // Restorable key for the edit field. private static let formTextKey = "formTextKey" /// - Tag: FormRestoration /// Encode state. Helps save the restorable state of this view controller. override func encodeRestorableState(with coder: NSCoder) { coder.encode(textField.stringValue, forKey: FormViewController.formTextKey) super.encodeRestorableState(with: coder) } /// Decode state. Helps restore any previously stored state. override func restoreState(with coder: NSCoder) { super.restoreState(with: coder) if let restoredText = coder.decodeObject(forKey: FormViewController.formTextKey) as? String { textField.stringValue = restoredText } } } ``` ## HeaderViewController.swift ```swift /* Abstract: View Controller managing the header user interface for each stack item, containing the title and disclosure button. */ import Cocoa class HeaderView: NSView { override func updateLayer () { // Update the color in case we switched beween light and dark mode. layer?.backgroundColor = NSColor(named: "HeaderColor")?.cgColor } } class HeaderViewController: NSViewController, StackItemHeader { @IBOutlet weak var headerTextField: NSTextField! @IBOutlet weak var showHideButton: NSButton! var disclose: (() -> Swift.Void)? // This state will be set by the stack item host. // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() headerTextField.stringValue = title! #if !DisclosureTriangleAppearance // Track the mouse movement so we can show/hide the disclosure button. let trackingArea = NSTrackingArea(rect: self.view.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.inVisibleRect], owner: self, userInfo: nil) // For the non-triangle disclosure button header, // we want the button to auto hide/show on mouse tracking. view.addTrackingArea(trackingArea) #endif } // MARK: - Actions @IBAction func showHidePressed(_ sender: AnyObject) { disclose?() } // MARK: - Mouse tracking override func mouseEntered(with theEvent: NSEvent) { // Mouse entered the header area, show disclosure button. super.mouseEntered(with: theEvent) showHideButton.isHidden = false } override func mouseExited(with theEvent: NSEvent) { // Mouse exited the header area, hide disclosure button. super.mouseExited(with: theEvent) showHideButton.isHidden = true } // MARK: - StackItemHeader Procotol func update(toDisclosureState: NSControl.StateValue) { showHideButton.state = toDisclosureState } } ``` ## MainViewController.swift ```swift /* Abstract: This sample's primary view controller. */ import Cocoa class MainViewController: NSViewController { /* User wants to show the stack view window. Put this in the area of your project what wants to show the stack view. */ @IBAction func showStackView(_ sender: AnyObject) { if let appDelegate = NSApplication.shared.delegate as? AppDelegate { appDelegate.stackViewWindowController?.showWindow(self) } } } ``` ## OtherViewController.swift ```swift /* Abstract: Stack item view controller for a very simple UI with buttons. */ import Cocoa class OtherViewController: BaseViewController { override func headerTitle() -> String { return NSLocalizedString("Other Header Title", comment: "") } // MARK: - Actions @IBAction func leftButtonAction(_ sender: AnyObject) { debugPrint("left button clicked") } @IBAction func rightButtonAction(_ sender: AnyObject) { debugPrint("right button clicked") } } ``` ## StackView.swift ```swift /* Abstract: Classes and protocols for handling NSStackView architecture. */ import Cocoa // MARK: Protocol Delarations - // The hosting object containing both the header and body. protocol StackItemHost: AnyObject { func disclose(_ stackItem: StackItemContainer) } // The object containing the header portion. protocol StackItemHeader: AnyObject { var viewController: NSViewController { get } var disclose: (() -> Swift.Void)? { get set } func update(toDisclosureState: NSControl.StateValue) } // The object containing the main body portion. protocol StackItemBody: AnyObject { var viewController: NSViewController { get } func show(animated: Bool) func hide(animated: Bool) } // MARK: - Protocol implementations extension StackItemHost { /// The action function for the disclosure button. func disclose(_ stackItem: StackItemContainer) { switch stackItem.state { case .on: hide(stackItem, animated: true) stackItem.state = .off case .off: show(stackItem, animated: true) stackItem.state = .on default: break } } func show(_ stackItem: StackItemContainer, animated: Bool) { // Show the stackItem's body content. stackItem.body.show(animated: animated) if let bodyViewController = stackItem.body.viewController as? BaseViewController { // Tell the view controller to update its disclosure state. // This will in turn eventually call "encodeRestorableState". bodyViewController.invalidateRestorableState() } // Update the stackItem's header disclosure button state. stackItem.header.update(toDisclosureState: .on) } func hide(_ stackItem: StackItemContainer, animated: Bool) { // Hide the stackItem's body content. stackItem.body.hide(animated: animated) if let bodyViewController = stackItem.body.viewController as? BaseViewController { // Tell the view controller to update its disclosure state. // This will in turn eventually call "encodeRestorableState". bodyViewController.invalidateRestorableState() } // Update the stackItem's header disclosure button state. stackItem.header.update(toDisclosureState: .off) } } // MARK: - extension StackItemHeader where Self: NSViewController { var viewController: NSViewController { return self } } // MARK: - extension StackItemBody where Self: NSViewController { var viewController: NSViewController { return self } func animateDisclosure(disclose: Bool, animated: Bool) { if let viewController = self as? BaseViewController { if let constraint = viewController.heightConstraint { let heightValue = disclose ? viewController.savedDefaultHeight : 0 if animated { NSAnimationContext.runAnimationGroup({ (context) -> Void in context.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) constraint.animator().constant = heightValue }, completionHandler: { () -> Void in // animation completed }) } else { constraint.constant = heightValue } } } } func show(animated: Bool) { animateDisclosure(disclose: true, animated: animated) } func hide(animated: Bool) { animateDisclosure(disclose: false, animated: animated) } } // MARK: - /// - Tag: Container class StackItemContainer { // Disclosure state of this container. var state: NSControl.StateValue let header: StackItemHeader let body: StackItemBody init(header: StackItemHeader, body: StackItemBody) { self.header = header self.body = body self.state = .on } } ``` ## TableViewController.swift ```swift /* Abstract: Stack item view controller for displaying a simple NSTableView. */ import Cocoa class TableViewController: BaseViewController { private struct TableItemKeys { static let kFirstNameKey = "firstname" static let kLastNameKey = "lastname" static let kPhoneKey = "phone" } @IBOutlet weak var tableView: NSTableView! @IBOutlet var myContentArray: NSArrayController! override func headerTitle() -> String { return NSLocalizedString("Table Header Title", comment: "") } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.enclosingScrollView?.borderType = .noBorder // Add the people as sample table data to the table view. let person1: [String: String] = [ TableItemKeys.kFirstNameKey: "Joe", TableItemKeys.kLastNameKey: "Smith", TableItemKeys.kPhoneKey: "(444) 444-4444" ] myContentArray.addObject(person1) let person2: [String: String] = [ TableItemKeys.kFirstNameKey: "Sally", TableItemKeys.kLastNameKey: "Allen", TableItemKeys.kPhoneKey: "(555) 555-5555" ] myContentArray.addObject(person2) let person3: [String: String] = [ TableItemKeys.kFirstNameKey: "Mary", TableItemKeys.kLastNameKey: "Miller", TableItemKeys.kPhoneKey: "(777) 777-7777" ] myContentArray.addObject(person3) let person4: [String: String] = [ TableItemKeys.kFirstNameKey: "John", TableItemKeys.kLastNameKey: "Zitmayer", TableItemKeys.kPhoneKey: "(888) 888-8888" ] myContentArray.addObject(person4) // Adjust the tableView's scroll view frame height constraint to match the content in the table. let headerView = tableView.headerView let headerRect = headerView?.headerRect(ofColumn: 0) if let people = myContentArray.arrangedObjects as? [AnyObject] { let preferredSize = people.count * (Int(tableView.rowHeight) + 2) + Int((headerRect?.size.height)!) heightConstraint?.constant = CGFloat(preferredSize) savedDefaultHeight = CGFloat(preferredSize) } } } // MARK: - NSTableViewDelegate extension TableViewController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { if tableView.selectedRow < 0 { debugPrint("table: row de-selected") } else { // Report the selected person in the table. if let selectedPerson = myContentArray.selectedObjects.first as? [String: String] { let name = selectedPerson[TableItemKeys.kFirstNameKey]! + " " + selectedPerson[TableItemKeys.kLastNameKey]! debugPrint("table: row (tableView.selectedRow) was selected: (name as String)") } } // Invalidate state restoration, which will in turn eventually call "encodeRestorableState". invalidateRestorableState() } } // MARK: - State Restoration extension TableViewController { // Restorable key for the table view's selection. private static let tableSelectionKey = "tableSelectionKey" /// Encode state. Helps save the restorable state of this view controller. override func encodeRestorableState(with coder: NSCoder) { coder.encode(myContentArray.selectionIndex, forKey: TableViewController.tableSelectionKey) super.encodeRestorableState(with: coder) } /// Decode state. Helps restore any previously stored state of the table view view's selection. override func restoreState(with coder: NSCoder) { super.restoreState(with: coder) let savedTableSelection = coder.decodeInteger(forKey: TableViewController.tableSelectionKey) _ = myContentArray.setSelectionIndex(savedTableSelection) } } ``` ## ViewController.swift ```swift /* Abstract: View Controller controlling the NSStackView. */ import Cocoa class ViewController: NSViewController, StackItemHost { @IBOutlet weak var stackView: CustomStackView! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // Load and install all the view controllers from the storyboard in the following order. addViewController(withIdentifier: "FormViewController") addViewController(withIdentifier: "TableViewController") addViewController(withIdentifier: "CollectionViewController") addViewController(withIdentifier: "OtherViewController") } /// - Tag: Configure /// Used to add a particular view controller as an item to the stack view. private func addViewController(withIdentifier identifier: String) { let storyboard = NSStoryboard(name: "StackItems", bundle: nil) guard let viewController = storyboard.instantiateController(withIdentifier: identifier) as? BaseViewController else { return } // Set up the view controller's item container. let stackItemContainer = viewController.stackItemContainer! // Set the appropriate action function for toggling the disclosure state of each header. stackItemContainer.header.disclose = { self.disclose(viewController.stackItemContainer!) } // Add the header view. stackView.addArrangedSubview(stackItemContainer.header.viewController.view) // Add the main body content view. stackView.addArrangedSubview(stackItemContainer.body.viewController.view) // Set the default disclosure states (state restoration may restore them to their requested value). show(stackItemContainer, animated: false) } } // MARK: - // To adjust the origin of stack view in its enclosing scroll view. class CustomStackView: NSStackView { override var isFlipped: Bool { return true } } ``` ## WindowController.swift ```swift /* Abstract: This sample's application's primary window controller. */ import Cocoa class WindowController: NSWindowController, NSWindowRestoration { // MARK: - Window Controller Lifecycle override func windowDidLoad() { super.windowDidLoad() /* We support state restoration for this window and all its embedded view controllers. In order for all the view controllers to be restored, this window must be restorable too. This can also be done in the storyboard. */ window?.isRestorable = true window?.identifier = NSUserInterfaceItemIdentifier("StackWindow") // This will ensure restoreWindow will be called. window?.restorationClass = WindowController.self } // MARK: - Window Restoration /// Sent to request that this window be restored. static func restoreWindow(withIdentifier identifier: NSUserInterfaceItemIdentifier, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Swift.Void) { let identifier = identifier.rawValue var restoreWindow: NSWindow? = nil if identifier == "StackWindow" { // This is the identifier for the NSWindow. // We didn't create the window, it was created from the storyboard. if let appDelegate = NSApplication.shared.delegate as? AppDelegate { restoreWindow = appDelegate.stackViewWindowController?.window } } completionHandler(restoreWindow, nil) } } ``` ## AppDelegate.swift ```swift /* Abstract: The application delegate class. */ import UIKit /** Important Note: With the application scene life cycle, UIKit no longer calls the following functions on the UIApplicationDelegate. applicationWillEnterForeground(_ application: UIApplication) applicationDidEnterBackground(_ application: UIApplication) applicationDidBecomeActive(_ application: UIApplication) applicationWillResignActive(_ application: UIApplication) These UISceneDelegate functions replace them: func sceneWillEnterForeground(_ scene: UIScene) func sceneDidEnterBackground(_ scene: UIScene) func sceneDidBecomeActive(_ scene: UIScene) func sceneWillResignActive(_ scene: UIScene) If you choose to use the app scene life cycle (opting in with UIApplicationSceneManifest in the Info.plist), but still deploy to iOS 12.x, you need both sets of delegate functions. */ @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { /** The app delegate must implement the window from UIApplicationDelegate protocol to use a main storyboard file. */ var window: UIWindow? // MARK: - Application Life Cycle /** Tells the delegate the app controller has finished launching. Here you will do any one-time app data setup. */ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } /** iOS 12.x Tells the delegate that the app is about to enter the foreground. Equivalent API for scenes in UISceneDelegate: "sceneWillEnterForeground(_:)" */ func applicationWillEnterForeground(_ application: UIApplication) { //.. } /** iOS 12.x Tells the delegate that the app has become active. Equivalent API for scenes in UISceneDelegate:: "sceneDidBecomeActive(_:)" */ func applicationDidBecomeActive(_ application: UIApplication) { //.. } /** iOS 12.x Tells the delegate that the app is about to become inactive. Equivalent API for scenes in UISceneDelegate:: sceneWillResignActive(_:) */ func applicationWillResignActive(_ application: UIApplication) { // Save any pending changes to the product list. DataModelManager.sharedInstance.saveDataModel() } /** iOS 12.x Tells the delegate that the app is now in the background. Equivalent API for scenes in UISceneDelegate:: sceneDidEnterBackground(_:) */ func applicationDidEnterBackground(_ application: UIApplication) { // Save any pending changes to the product list. DataModelManager.sharedInstance.saveDataModel() } /** iOS 12.x Tells the delegate that the data for continuing an activity is available. Equivalent API for scenes is: scene(_:continue:) */ func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return false // Not applicable here at the app delegate level. } // MARK: - Scene Configuration /** iOS 13 or later UIKit uses this delegate when it is about to create and vend a new UIScene instance to the application. Use this function to select a configuration to create the new scene with. You can define the scene configuration in code here, or define it in the Info.plist. The application delegate may modify the provided UISceneConfiguration within this function. If the UISceneConfiguration instance that returns from this function does not have a systemType that matches the connectingSession's, UIKit asserts. */ @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { var sceneConfig = connectingSceneSession.configuration // Find the user activity, if available, to create the scene configuration. var currentActivity: NSUserActivity? options.userActivities.forEach { activity in currentActivity = activity } if currentActivity != nil { if currentActivity!.activityType == ImageSceneDelegate.ImageSceneActivityType() { sceneConfig = UISceneConfiguration(name: "Second Scene", sessionRole: .windowApplication) } } return sceneConfig } /** iOS 13 or later The system calls this delegate when it removes one or more representations from the -[UIApplication openSessions] set due to a user interaction or a request from the app itself. If the system discards sessions while the app isn't running, it calls this function shortly after the app�s next launch. Use this function to: Release any resources that were specific to the discarded scenes, as they will NOT return. Remove any state or data associated with this session, as it will not return (such as, unsaved draft of a document). */ @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { //.. } } // MARK: - State Restoration extension AppDelegate { // For non-scene-based versions of this app on iOS 13.1 and earlier. func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return true } // For non-scene-based versions of this app on iOS 13.1 and earlier. func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } @available(iOS 13.2, *) // For non-scene-based versions of this app on iOS 13.2 and later. func application(_ application: UIApplication, shouldSaveSecureApplicationState coder: NSCoder) -> Bool { return true } @available(iOS 13.2, *) // For non-scene-based versions of this app on iOS 13.2 and later. func application(_ application: UIApplication, shouldRestoreSecureApplicationState coder: NSCoder) -> Bool { return true } } ``` ## CollectionViewCell.swift ```swift /* Abstract: UICollectionView subclass for displaying the product's data. */ import UIKit class CollectionViewCell: UICollectionViewCell { static let reuseIdentifier = "reuseIdentifier" @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! func configureCell(with product: Product) { imageView.image = UIImage(named: product.imageName) label.text = product.name } } ``` ## CollectionViewController.swift ```swift /* Abstract: This sample's main collection view for displaying a grid of products. */ import UIKit class CollectionViewController: UICollectionViewController { private let sectionInset = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0) override func viewDidLoad() { super.viewDidLoad() // This collection view supports dragging items out to spwan new scenes. collectionView.dragDelegate = self collectionView?.contentInsetAdjustmentBehavior = .always if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.minimumLineSpacing = sectionInset.left flowLayout.minimumInteritemSpacing = sectionInset.left flowLayout.sectionInset = sectionInset flowLayout.itemSize = CGSize(width: 110.0, height: 110.0) } /** You want to know when this view controller returns so you can reset the userActivity for state restoration. In this view controller, you don't restore anything. */ navigationController!.delegate = self } // The user has tapped a collection view item, navigate to the detail parent view controller. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let detailParentViewController = segue.destination as? DetailParentViewController, let selectedIndexPaths = collectionView.indexPathsForSelectedItems { let selectedItemPath = selectedIndexPaths.first let selectedProduct = DataModelManager.sharedInstance.products()[(selectedItemPath?.item)!] detailParentViewController.product = selectedProduct } } } // MARK: - UICollectionViewDataSource extension CollectionViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return DataModelManager.sharedInstance.products().count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseIdentifier, for: indexPath) if let itemCell = cell as? CollectionViewCell { itemCell.configureCell(with: DataModelManager.sharedInstance.products()[indexPath.item]) } return cell } } // MARK: - UICollectionViewDragDelegate extension CollectionViewController: UICollectionViewDragDelegate { // Provide items to begin a drag for a specified indexPath. If an empty array returns, a drag session doesn't begin. public func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { let product = DataModelManager.sharedInstance.products()[indexPath.item] let image = UIImage(named: product.imageName) let itemProvider = NSItemProvider(object: image! as NSItemProviderWriting) if #available(iOS 13.0, *) { // Register the product user activity as part of the drag to create a new scene if dropped to the left or right of the screen. let userActivity = ImageSceneDelegate.activity(for: product) itemProvider.registerObject(userActivity, visibility: .all) } let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = product return [dragItem] } /** Call to request items to add to an existing drag session in response to the add item gesture. You can use the provided point (in the collection view's coordinate space) to do additional hit testing. If you don't implement this, or if an empty array returns, the system doesn't add items to the drag. It handles the gesture normally. */ func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { let dragItem = UIDragItem(itemProvider: NSItemProvider(object: cell.imageView.image!)) dragItem.localObject = true // Hint that makes it faster to drag and drop content within the same app. return [dragItem] } else { return [] } } } // MARK: - UINavigationControllerDelegate extension CollectionViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { if viewController == self && animated == true { /** Returning to this view controller after it popped with animation. Reset the userActivity for state restoration. At this view controller you don't restore anything. */ if #available(iOS 13.0, *) { view.window?.windowScene?.session.scene!.userActivity = nil } } } } // MARK: - ContextMenu Support @available(iOS 13.0, *) extension CollectionViewController { // Create a new window scene for the product indexPath. func openNewWindowAction(indexPath: IndexPath) -> UIAction { let selectedProduct = DataModelManager.sharedInstance.products()[(indexPath.item)] // Create an NSUserActivity from the product to use in ImageSceneDelegate. let userActivity = ImageSceneDelegate.activity(for: selectedProduct) let activationOptions = UIScene.ActivationRequestOptions() // Informs the system of the interface instance the user interacted with to create the new interface for system navigation. activationOptions.requestingScene = self.view.window!.windowScene let newWindowAction = UIAction(title: NSLocalizedString("OpenNewWindowTitle", comment: ""), image: UIImage(systemName: "square.and.arrow.up.on.square")) { action in // Send the user activity (with the product info) to pass along for scene creation. UIApplication.shared.requestSceneSessionActivation( nil, // Pass nil to create a new scene. userActivity: userActivity, options: activationOptions) { (error) in Swift.debugPrint("(error)") } } return newWindowAction } override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in var actions = [UIMenuElement]() // Add the Open New Window action for iPadOS devices only. if UIDevice.current.userInterfaceIdiom == .pad { let openNewWindowAction = self.openNewWindowAction(indexPath: indexPath) actions.append(openNewWindowAction) } return UIMenu(title: "", children: actions) } } } ``` ## DataModel.swift ```swift /* Abstract: The data model for this sample containing the manager and model types. */ import UIKit // Singleton data model. class DataModelManager { static let sharedInstance: DataModelManager = { let instance = DataModelManager() instance.loadDataModel() return instance }() var dataModel: DataModel! private let dataFileName = "Products" private func documentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } private func dataModelURL() -> URL { let docURL = documentsDirectory() return docURL.appendingPathComponent(dataFileName) } func saveDataModel() { let encoder = JSONEncoder() if let encoded = try? encoder.encode(dataModel) { do { // Save the 'Products' data file to the Documents directory. try encoded.write(to: dataModelURL()) } catch { print("Couldn't write to save file: " + error.localizedDescription) } } } func loadDataModel() { // Load the data model from the 'Products' data file in the Documents directory. guard let codedData = try? Data(contentsOf: dataModelURL()) else { // No data on disk, create a new data model. dataModel = DataModel() return } // Decode the JSON file into a DataModel object. let decoder = JSONDecoder() if let decoded = try? decoder.decode(DataModel.self, from: codedData) { dataModel = decoded } } // MARK: - Accessors func products() -> [Product] { return dataModel.products } func product(fromTitle: String) -> Product? { let filteredProducts = dataModel.products.filter { product in let productTitle = product.name.lowercased() if productTitle == fromTitle.lowercased() { return true } else { return false } } if filteredProducts.count == 1 { return filteredProducts[0] } else { return nil } } func product(fromIdentifier: String) -> Product? { let filteredProducts = dataModel.products.filter { product in let productIdentifier = product.identifier.uuidString if productIdentifier == fromIdentifier { return true } else { return false } } if filteredProducts.isEmpty { fatalError("Can't find product from identifier.") } return filteredProducts[0] } // MARK: - Actions func remove(atLocation: Int) { dataModel.products.remove(at: atLocation) } func insert(product: Product, atLocation: Int) { dataModel.products.insert(product, at: atLocation) } } // MARK: - Data Model struct DataModel: Codable { var products: [Product] = [] private enum CodingKeys: String, CodingKey { case products } // MARK: - Codable func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(products, forKey: .products) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) products = try values.decode(Array.self, forKey: .products) } init() { // No data on disk, read the products from the JSON file. products = Bundle.main.decode("products.json") } } // MARK: Bundle extension Bundle { func decode(_ file: String) -> [Product] { guard let url = self.url(forResource: file, withExtension: nil) else { fatalError("Failed to locate (file) in bundle.") } guard let data = try? Data(contentsOf: url) else { fatalError("Failed to load (file) from bundle.") } let decoder = JSONDecoder() guard let loaded = try? decoder.decode([Product].self, from: data) else { fatalError("Failed to decode (file) from bundle.") } return loaded } } ``` ## DetailParentViewController.swift ```swift /* Abstract: The view controller for displaying the detailed information on each product. */ import UIKit class DetailParentViewController: UIViewController { // The storyboard identifier for this view controller. static let viewControllerIdentifier = "DetailParentViewController" // MARK: - Properties var product: Product! { didSet { title = product.name updateChildDetailViewControllers(product: product) } } var parentTabbarController: UITabBarController! // The restored selected tab index for UITabBarController. var restoredSelectedTab: Int = 0 // The restored EditViewController (iOS 12.x). var restoredEditor: EditViewController! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() let editButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editAction(sender:))) navigationItem.rightBarButtonItem = editButton } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 13.0, *) { // For iOS 13 and later, restore the editor from the user activity state. // Restore and present the EditViewController? if let activityUserInfo = view.window?.windowScene?.userActivity?.userInfo { if activityUserInfo[SceneDelegate.presentedEditorKey] != nil { // Restore the edit view controller. if let editNavViewController = EditViewController.loadEditViewController() { if let editViewController = editNavViewController.topViewController as? EditViewController { editViewController.product = product //�Restore the edit fields. editViewController.restoredTitle = activityUserInfo[SceneDelegate.editorTitleKey] as? String editViewController.restoredPrice = activityUserInfo[SceneDelegate.editorPriceKey] as? String editViewController.restoredYear = activityUserInfo[SceneDelegate.editorYearKey] as? String self.present(editNavViewController, animated: false, completion: nil) } } } } /** Set up the activation predicates to determine which scenes to activate. Restrictions: Block-based predicates are not allowed. Regular expression predicates are not allowed. The only keyPath you can reference is "self". */ let conditions = view.window!.windowScene!.activationConditions // The primary "can" predicate (the kind of content this scene can display -� specific targetContentIdenfiers). conditions.canActivateForTargetContentIdentifierPredicate = NSPredicate(value: false) // The secondary "prefers" predicate (this scene displays certain content -� the product's identifier). let preferPredicate = NSPredicate(format: "self == %@", product.identifier.uuidString) conditions.prefersToActivateForTargetContentIdentifierPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [preferPredicate]) // Update the user activity with this product and tab selection for scene-based state restoration. updateUserActivity() } else { // For iOS 12.x, restore the editor from the encoded restoration store. if let editor = restoredEditor { let navController = UINavigationController(rootViewController: editor) self.present(navController, animated: false, completion: { self.restoredEditor = nil }) } } if parentTabbarController != nil { parentTabbarController.selectedIndex = restoredSelectedTab } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // This view controller is going away, no more user activity to track. if #available(iOS 13.0, *) { view.window?.windowScene?.userActivity = nil } else { userActivity = nil } } // MARK: - Actions @objc func editAction(sender: Any) { // Present the edit view controller to edit the product's data. guard let editNavViewController = EditViewController.loadEditViewController() else { return } if let editViewController = editNavViewController.topViewController as? EditViewController { editViewController.product = product self.present(editNavViewController, animated: true, completion: nil) } } func updateChildDetailViewControllers(product: Product) { guard let tabbarController = parentTabbarController else { return } guard let tabViewControllers = tabbarController.viewControllers else { return } if let infoViewController = tabViewControllers[0] as? InfoViewController { infoViewController.product = product } if let photoViewController = tabViewControllers[1] as? ImageViewController { photoViewController.product = product } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Preparation of the embed segue to hold the tab bar controller. Pass the product to the tab bar controller's children. if segue.identifier == "embedTabbar" { if let destinationTabbarController = segue.destination as? UITabBarController { parentTabbarController = destinationTabbarController // Receive a notification when the tab selection changes (to restore later). parentTabbarController.delegate = self // Pass the product to both child view controllers inside the tab bar controller. if product != nil { updateChildDetailViewControllers(product: product) } } } } @available(iOS 13.0, *) /** Update the user activity for this view controller's scene. viewDidAppear calls this upon initial presentation. The tabBarController.didSlect delegate also calls it. */ func updateUserActivity() { var currentUserActivity = view.window?.windowScene?.userActivity if currentUserActivity == nil { /** Note: You must include the activityType string below in your Info.plist file under the `NSUserActivityTypes` array. More info: https://developer.apple.com/documentation/foundation/nsuseractivity */ currentUserActivity = NSUserActivity(activityType: SceneDelegate.MainSceneActivityType()) } /** The target content identifier is a structured way to represent data in your model. Set a string that identifies the content of this NSUserActivity. Here the userActivity's targetContentIdentifier is the product's title. */ currentUserActivity?.title = product.name currentUserActivity?.targetContentIdentifier = product.identifier.uuidString // Add the tab bar selection to the user activity. let selectedTab = parentTabbarController!.selectedIndex currentUserActivity?.addUserInfoEntries(from: [SceneDelegate.selectedTabKey: selectedTab]) // Add the product to the user activity (as a coded JSON object). currentUserActivity?.addUserInfoEntries(from: [SceneDelegate.productKey: product.identifier.uuidString]) // Update the product to both child view controllers in the tab bar controller. updateChildDetailViewControllers(product: product) view.window?.windowScene?.userActivity = currentUserActivity // Mark this scene's session with this userActivity product identifier, so you can update the UI later. view.window?.windowScene?.session.userInfo = [SceneDelegate.productIdentifierKey: product.identifier.uuidString] } } // MARK: - DoneEditDelegate extension DetailParentViewController: DoneEditDelegate { // The EditViewController is done editing the product. func doneEdit(_ editViewController: EditViewController, product: Product) { title = product.name } } // MARK: - UITabBarControllerDelegate extension DetailParentViewController: UITabBarControllerDelegate { // The user selected a tab bar controller tab. func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { if #available(iOS 13.0, *) { // Remember this tab selection as part of the user activity for scene-based state restoration. updateUserActivity() } restoredSelectedTab = tabBarController.selectedIndex } } // MARK: - UIStateRestoring (iOS 12.x) // The system calls these overrides for nonscene-based versions of this app in iOS 12.x. extension DetailParentViewController { // Keys for restoring this view controller. static let tabbarController = "tabbar" // The embedded child tab bar controller. static let restoreProductKey = "product" // The encoded product identifier. static let restoreSelectedTabKey = "selectedTab" // The tab bar controller's selected tab. static let restorePresentedEditorKey = "presentedEditor" // Indicates whether the system presented the editor view controller. static let restoreEditorKey = "editor" // The stored editor view controller. override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(product.identifier.uuidString, forKey: DetailParentViewController.restoreProductKey) /** Because you�re using a custom container view controller (to hold the UITabBarController), you must encode it to restore its child view controllers. This allows the system to call encodeRestorableState/decodeRestorableState functions for each child. Note: Each child you encode must have a unique restoration identifier. */ coder.encode(parentTabbarController, forKey: DetailParentViewController.tabbarController) // Save the tab bar's selected index page. coder.encode(parentTabbarController.selectedIndex, forKey: DetailParentViewController.restoreSelectedTabKey) if let presentedNavController = presentedViewController as? UINavigationController { let presentedViewController = presentedNavController.topViewController // Note: You don't need to encode the navigation controller. coder.encode(presentedViewController is EditViewController, forKey: DetailParentViewController.restorePresentedEditorKey) /** EditViewController is a presented or child view controller so you must encode it to restore it. This allows the system to call encodeRestorableState/decodeRestorableState functions for the EditViewController. */ coder.encode(presentedViewController, forKey: DetailParentViewController.restoreEditorKey) } } override func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) guard let decodedProductIdentifier = coder.decodeObject(forKey: DetailParentViewController.restoreProductKey) as? String else { fatalError("A product did not exist in the restore. In your app, handle this gracefully.") } product = DataModelManager.sharedInstance.product(fromIdentifier: decodedProductIdentifier) restoredSelectedTab = coder.decodeInteger(forKey: DetailParentViewController.restoreSelectedTabKey) if let editor = coder.decodeObject(forKey: DetailParentViewController.restoreEditorKey) as? EditViewController { restoredEditor = editor restoredEditor.product = product } // Note: The child view controllers inside the tab bar and the EditViewController each restore themselves. } } ``` ## EditViewController.swift ```swift /* Abstract: View controller for editing the product's data. */ import UIKit class EditViewController: UITableViewController { static let storyboardName = "EditViewController" static let viewControllerIdentifier = "EditNavViewController" // MARK: - Properties var product: Product! @IBOutlet var imageView: UIImageView! @IBOutlet var titleField: UITextField! @IBOutlet var yearIntroducedField: UITextField! @IBOutlet var introPrice: UITextField! var restoredTitle: String! var restoredPrice: String! var restoredYear: String! weak var doneDelegate: DoneEditDelegate? // MARK: - Storyboard Support class func loadEditViewController() -> UINavigationController? { let storyboard = UIStoryboard(name: storyboardName, bundle: .main) if let navigationController = storyboard.instantiateViewController(withIdentifier: viewControllerIdentifier) as? UINavigationController { return navigationController } return nil } // MARK: - View Life Cycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) imageView.image = UIImage(named: product.imageName) // If you are restoring, use the restored values, otherwise use the product information. titleField.text = restoredTitle != nil ? restoredTitle : product.name yearIntroducedField.text = restoredYear != nil ? restoredYear : String("(product.year)") introPrice.text = restoredPrice != nil ? restoredPrice : String("(product.price)") if #available(iOS 13.0, *) { updateUserActivity() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if #available(iOS 13.0, *) { if let currentUserActivity = view.window?.windowScene?.userActivity { // The system is dismissing the scene. Remove user activity-related data. currentUserActivity.userInfo?.removeValue(forKey: SceneDelegate.presentedEditorKey) currentUserActivity.userInfo?.removeValue(forKey: SceneDelegate.editorTitleKey) currentUserActivity.userInfo?.removeValue(forKey: SceneDelegate.editorPriceKey) currentUserActivity.userInfo?.removeValue(forKey: SceneDelegate.editorYearKey) } } } // MARK: - Actions func performSceneUpdates() { if #available(iOS 13.0, *) { let scenes = UIApplication.shared.connectedScenes // Filter out the scenes that have this product's identifier for session refresh. let filteredScenes = scenes.filter { scene in var productUserInfoKey: String? if let userInfo = scene.session.userInfo { if let mainSceneDelegate = scene.delegate as? SceneDelegate { productUserInfoKey = SceneDelegate.productIdentifierKey mainSceneDelegate.updateScene(with: self.product) } else if let imageSceneDelegate = scene.delegate as? ImageSceneDelegate { productUserInfoKey = ImageSceneDelegate.productIdentifierKey if let productID = userInfo[productUserInfoKey!] as? String { if productID == self.product.identifier.uuidString { // Ask ImageSceneDelegate to update. imageSceneDelegate.updateScene(with: self.product) } } } guard let productIdentifier = userInfo[productUserInfoKey!] as? String, productIdentifier == self.product.identifier.uuidString else { return false } } return true } filteredScenes.forEach { scene in /** This updates the UI and the snapshot in the task switcher, the state restoration acitvity, and so forth. The system doesn't always fulfill this request right away. */ UIApplication.shared.requestSceneSessionRefresh(scene.session) } } } @IBAction func doneAction(sender: Any) { let newProduct = Product(identifier: self.product.identifier, name: titleField.text!, imageName: self.product.imageName, year: Int(yearIntroducedField.text!)!, price: Double(introPrice.text!)!) // Replace the old product with the newly edited one. if let productIndexToReplace = DataModelManager.sharedInstance.dataModel.products.firstIndex(of: self.product) { DataModelManager.sharedInstance.dataModel.products.remove(at: productIndexToReplace) DataModelManager.sharedInstance.dataModel.products.insert(newProduct, at: productIndexToReplace) self.product = newProduct DataModelManager.sharedInstance.saveDataModel() } // Notify an optional delegate that the system has completed editing. if self.doneDelegate != nil { self.doneDelegate?.doneEdit(self, product: self.product) } // Update the rest of the app due to the change. if #available(iOS 13.0, *) { performSceneUpdates() } else { //�iOS 12.x view controller updates. if let presentingViewController = self.presentingViewController as? UINavigationController { if let collectionView = presentingViewController.viewControllers[0] as? CollectionViewController { // Update the collection view. collectionView.collectionView.reloadData() } if let detailParentViewController = presentingViewController.topViewController as? DetailParentViewController { // Update the detail view controller. detailParentViewController.product = product } } } // The user committed the product edit. Update any scenes that use that product. self.dismiss(animated: true, completion: nil) } @IBAction func cancelAction(sender: Any) { self.dismiss(animated: true, completion: nil) } @available(iOS 13.0, *) /** Update the user activity for this view controller's scene. viewDidAppear calls this upon initial presentation. The SceneDelegate stateRestorationActivity delegate also calls it. */ func updateUserActivity() { var currentUserActivity = view.window?.windowScene?.userActivity if currentUserActivity == nil { /** Note: You must include the activityType string below in your Info.plist file under the `NSUserActivityTypes` array. More info: https://developer.apple.com/documentation/foundation/nsuseractivity */ currentUserActivity = NSUserActivity(activityType: SceneDelegate.MainSceneActivityType()) } // Add the presented state. currentUserActivity?.addUserInfoEntries(from: [SceneDelegate.presentedEditorKey: true]) // Add the editor's edit fields values. let editFieldEntries = [ SceneDelegate.editorTitleKey: titleField.text, SceneDelegate.editorPriceKey: introPrice.text, SceneDelegate.editorYearKey: yearIntroducedField.text ] currentUserActivity?.addUserInfoEntries(from: editFieldEntries as [AnyHashable: Any]) view.window?.windowScene?.userActivity = currentUserActivity } } // MARK: - UITextFieldDelegate extension EditViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) } } // MARK: - UIStateRestoring (iOS 12.x) // The system calls these overrides for nonscene-based versions of this app in iOS 12.x. extension EditViewController { static let restoreEditorTitle = "editorTitle" static let restoreEditorIntroPrice = "editorPrice" static let restoreEditorYearIntroduced = "editorYear" override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(titleField.text, forKey: EditViewController.restoreEditorTitle) coder.encode(yearIntroducedField.text, forKey: EditViewController.restoreEditorYearIntroduced) coder.encode(introPrice.text, forKey: EditViewController.restoreEditorIntroPrice) } override func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) if let title = coder.decodeObject(forKey: EditViewController.restoreEditorTitle) as? String { restoredTitle = title } if let price = coder.decodeObject(forKey: EditViewController.restoreEditorIntroPrice) as? String { restoredPrice = price } if let year = coder.decodeObject(forKey: EditViewController.restoreEditorYearIntroduced) as? String { restoredYear = year } } } // MARK: - DoneEditDelegate protocol DoneEditDelegate: AnyObject { // Notifies the delegate that the system has completed editing the product. func doneEdit(_ editViewController: EditViewController, product: Product) } ``` ## ImageSceneDelegate+StateRestoration.swift ```swift /* Abstract: State restoration support for this sample's secondary product image scene. */ import UIKit @available(iOS 13.0, *) extension ImageSceneDelegate { // Activity type for restoring (loaded from the plist). static let ImageSceneActivityType = { () -> String in // Load the activity type from the Info.plist. let activityTypes = Bundle.main.infoDictionary?["NSUserActivityTypes"] as? [String] return activityTypes![1] } /** Data key for storing in the session's userInfo. Mark this session's userInfo with the current product's identifier so you can use it later to update this scene if it's in the background. */ static let productIdentifierKey = "productIdentifier" /** Return a Product instance from a user activity. Used by: scene:willConnectTo, scene:continue userActivity */ class func product(for activity: NSUserActivity) -> Product? { var product: Product! if let userInfo = activity.userInfo { // Decode the user activity product identifier from the userInfo. if let productIdentifier = userInfo[ImageSceneDelegate.productIdentifierKey] as? String { product = DataModelManager.sharedInstance.product(fromIdentifier: productIdentifier) } } return product } class func activity(for product: Product) -> NSUserActivity { /** Create an NSUserActivity from the product. Note: You must include the activityType string below in your Info.plist file under the `NSUserActivityTypes` array. More info: https://developer.apple.com/documentation/foundation/nsuseractivity */ let userActivity = NSUserActivity(activityType: ImageSceneDelegate.ImageSceneActivityType()) /** Target content identifier is a structured way to represent data in your model. Set a string that identifies the content of this NSUserActivity. Here the userActivity's targetContentIdentifier is the product's UUID string. */ userActivity.title = product.name userActivity.targetContentIdentifier = product.identifier.uuidString // Add the product identifier to the user activity. userActivity.addUserInfoEntries(from: [ImageSceneDelegate.productIdentifierKey: product.identifier.uuidString]) return userActivity } /** This is the NSUserActivity for restoring the state when the Scene reconnects. It can be the same activity that you use for handoff or spotlight, or it can be a separate activity with a different activity type and userInfo. After the system calls this function, and before it saves the activity in the restoration file, if the returned NSUserActivity has a delegate (NSUserActivityDelegate), the function userActivityWillSave calls that delegate. Additionally, if any UIResponders have the activity set as their userActivity property, the system calls the UIResponder updateUserActivityState function to update the activity. This happens synchronously and ensures that the system has filled in all the information for the activity before saving it. */ /** The user might be editing this product in another scene, so you can call this when you want to update this scene when calling "requestSceneSessionRefresh". */ func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { return scene.userActivity } } ``` ## ImageSceneDelegate.swift ```swift /* Abstract: Window scene delegate for managing the secondary product image scene. */ import UIKit @available(iOS 13.0, *) class ImageSceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? /** Apps configure their UIWindow and attach it to the provided UIWindowScene. This is once per UI setup. When using a storyboard file, as specified by the Info.plist key, UISceneStoryboardFile, the system automatically configures the window property and attaches it to the windowScene. Remember to retain the SceneDelegate's UIWindow. The recommended approach is for the SceneDelegate to retain the scene's window. */ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Determine the user activity from a new connection or from a session's state restoration. guard let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity else { return } if configure(window: window, session: session, with: userActivity) { scene.userActivity = userActivity /** Set the title for this scene to allow the system to differentiate multiple scenes for the user. If set to nil or an empty string, the system doesn't display a title. */ scene.title = userActivity.title // Mark this scene's session with this userActivity product identifier so you can update the UI later. if let sessionProduct = ImageSceneDelegate.product(for: userActivity) { session.userInfo = [ImageSceneDelegate.productIdentifierKey: sessionProduct.identifier.uuidString] } } else { Swift.debugPrint("Failed to restore scene from (userActivity)") } /** Set up the activation predicates to determine which scenes to activate. Restrictions: Block-based predicates are not allowed. Regular expression predicates are not allowed. The only keyPath you can reference is "self". */ let conditions = scene.activationConditions // The primary "can" predicate (the kind of content this scene can display � specific targetContentIdenfiers). conditions.canActivateForTargetContentIdentifierPredicate = NSPredicate(value: false) // The secondary "prefers" predicate (this scene displays certain content � the product's identifier). if let activityProductIdentifier = session.userInfo![SceneDelegate.productIdentifierKey] as? String { let preferPredicate = NSPredicate(format: "self == %@", activityProductIdentifier) conditions.prefersToActivateForTargetContentIdentifierPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [preferPredicate]) } } // willConnectTo uses this delegate to set up the view controller and user activity. func configure(window: UIWindow?, session: UISceneSession, with activity: NSUserActivity) -> Bool { var succeeded = false /** Manually set the rootViewController to this window with our own storyboard. This is useful if you have one view controller per storyboard. */ let storyboard = UIStoryboard(name: ImageViewController.storyboardName, bundle: .main) guard let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController else { return false } guard let imageViewController = navigationController.topViewController as? ImageViewController else { return false } /** Use the appropriate user activity, either from the connection options when the system created the scene, or from the session the system is restoring. */ /** If there were no user activities, you don't have to do anything. The `window` property automatically loads with the storyboard's initial view controller. */ if activity.activityType == ImageSceneDelegate.ImageSceneActivityType() { if let product = ImageSceneDelegate.product(for: activity) { imageViewController.product = product succeeded = true } } else { // The incoming activity is not recognizable here. } window?.rootViewController = navigationController return succeeded } /** On window close. The system uses this delegate as it's releasing the scene or on window close.. This occurs shortly after the scene enters the background, or when the system discards its session. Release any scene-related resources that the system can recreate the next time the scene connects. The scene may reconnect later because the system didn�t necessarily discard its session (see`application:didDiscardSceneSessions` instead), so don't delete any user data or state permanently. */ func sceneDidDisconnect(_ scene: UIScene) { //.. } // On window open or in iOS resume. func sceneWillEnterForeground(_ scene: UIScene) { //.. } // On window close or in iOS enter background. func sceneWillResignActive(_ scene: UIScene) { if let userActivity = window?.windowScene?.userActivity { userActivity.resignCurrent() } } // On window activation. // The system calls this delegate every time a scene becomes active so set up your scene UI here. func sceneDidBecomeActive(_ scene: UIScene) { if let userActivity = window?.windowScene?.userActivity { userActivity.becomeCurrent() } } // MARK: - Window Scene func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) { //Swift.debugPrint("Window scene (windowScene.session.role) updated coordinates.") //Swift.debugPrint("coord space = (String(describing: self.window?.rootViewController?.view.coordinateSpace))") // The scene size has changed. (User moved the slider horizontally in either direction.) } func updateScene(with product: Product) { if let navController = window!.rootViewController as? UINavigationController { if let imageViewController = navController.topViewController as? ImageViewController { imageViewController.product = product window?.windowScene!.title = product.name } } } // MARK: - Handoff support func scene(_ scene: UIScene, willContinueUserActivityWithType userActivityType: String) { //.. } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard userActivity.activityType == ImageSceneDelegate.ImageSceneActivityType() else { return } // Pass the user activity product over to this view controller. if let navController = window?.rootViewController as? UINavigationController { if let imageViewController = navController.topViewController as? ImageViewController { imageViewController.product = ImageSceneDelegate.product(for: userActivity) } } } func scene(_ scene: UIScene, didFailToContinueUserActivityWithType userActivityType: String, error: Error) { let alert = UIAlertController(title: NSLocalizedString("UnableToContinueTitle", comment: ""), message: error.localizedDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: NSLocalizedString("OKTitle", comment: ""), style: .default) { (action) in alert.dismiss(animated: true, completion: nil) } alert.addAction(okAction) window?.rootViewController?.present(alert, animated: true, completion: nil) } } ``` ## ImageViewController.swift ```swift /* Abstract: The view controller for displaying the product's full image. */ import UIKit class ImageViewController: UIViewController { // The storyboard name that holds this view controller. // Other parts of the app use it to load this view controller. static let storyboardName = "ImageViewController" // MARK: - Properties @IBOutlet private weak var imageView: UIImageView! var product: Product? { didSet { if isViewLoaded { updateUIElements() } } } // MARK: - View Life Cycle override func awakeFromNib() { super.awakeFromNib() if #available(iOS 13.0, *) { tabBarItem = UITabBarItem(title: "Photo", image: UIImage(systemName: "photo"), selectedImage: UIImage(systemName: "photo.fill")) } } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13.0, *) { // Add a Close button to remove the scene. let closeButton = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(closeAction(sender:))) navigationItem.rightBarButtonItem = closeButton } } func updateUIElements() { imageView.image = UIImage(named: product!.imageName) navigationItem.title = product!.name } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateUIElements() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // This view controller is going away, no more user activity to track. if #available(iOS 13.0, *) { view.window?.windowScene?.userActivity = nil } else { userActivity = nil } } @objc func closeAction(sender: Any) { if #available(iOS 13.0, *) { // The Close button removes the scene. let options = UIWindowSceneDestructionRequestOptions() options.windowDismissalAnimation = .standard let session = view.window!.windowScene!.session UIApplication.shared.requestSceneSessionDestruction(session, options: options, errorHandler: nil) } } } // MARK: - UIStateRestoring (iOS 12.x) // The system calls these overrides for nonscene-based versions of this app in iOS 12.x. extension ImageViewController { // Keys for restoring this view controller. private static let restoreProductKey = "restoreProduct" override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(product?.identifier.uuidString, forKey: ImageViewController.restoreProductKey) } override func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) guard let decodedProductIdentifier = coder.decodeObject(forKey: ImageViewController.restoreProductKey) as? String else { fatalError("A product did not exist in the restore. In your app, handle this gracefully.") } product = DataModelManager.sharedInstance.product(fromIdentifier: decodedProductIdentifier) } } ``` ## InfoViewController.swift ```swift /* Abstract: View controller tab for displaying the product's data. */ import UIKit class InfoViewController: UIViewController { // MARK: - Properties var product: Product? { didSet { if isViewLoaded { updateUIElements() } } } @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var yearLabel: UILabel! @IBOutlet private weak var priceLabel: UILabel! @IBOutlet private weak var imageView: UIImageView! var priceFormatter: NumberFormatter! // MARK: - View Life Cycle override func awakeFromNib() { super.awakeFromNib() if #available(iOS 13.0, *) { tabBarItem = UITabBarItem(title: "Detail", image: UIImage(systemName: "info.circle"), selectedImage: UIImage(systemName: "info.circle.fill")) } } override func viewDidLoad() { super.viewDidLoad() priceFormatter = NumberFormatter() priceFormatter.locale = Locale.current priceFormatter.numberStyle = .currency } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateUIElements() } func updateUIElements() { titleLabel.text = product?.name if let yearValue = product?.year { yearLabel.text = "(yearValue)" } let formattedPrice = priceFormatter.string(from: NSNumber(value: product!.price)) priceLabel.text = formattedPrice imageView.image = UIImage(named: product!.imageName) } } // MARK: - UIStateRestoring (iOS 12.x) // The system calls these overrides for nonscene-based versions of this app in iOS 12.x. extension InfoViewController { // Keys for restoring this view controller. private static let restoreProductKey = "restoreProduct" override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(product?.identifier.uuidString, forKey: InfoViewController.restoreProductKey) } override func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) guard let decodedProductIdentifier = coder.decodeObject(forKey: InfoViewController.restoreProductKey) as? String else { fatalError("A product did not exist in the restore. In your app, handle this gracefully.") } product = DataModelManager.sharedInstance.product(fromIdentifier: decodedProductIdentifier) } } ``` ## Item.swift ```swift /* Abstract: Struct representing each item in the data source array. */ import Foundation class Item: NSObject, Codable { var identifier = "" var title = "" var notes = "" // MARK: - Codable private enum CodingKeys: String, CodingKey { case identifier case title case notes } init(title: String, notes: String, identifier: String?) { self.title = title self.notes = notes self.identifier = identifier ?? UUID().uuidString } override var hash: Int { return identifier.hash } override func isEqual(_ object: Any?) -> Bool { guard let otherItem = object as? Item else { return false } return identifier == otherItem.identifier } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(title, forKey: .title) try container.encode(notes, forKey: .notes) try container.encode(identifier, forKey: .identifier) } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) title = try values.decode(String.self, forKey: .title) notes = try values.decode(String.self, forKey: .notes) identifier = try values.decode(String.self, forKey: .identifier) } } ``` ## Product.swift ```swift /* Abstract: This sample's main data model describing the product. */ import Foundation struct Product: Hashable, Codable { // MARK: - Types private enum CoderKeys: String, CodingKey { case name case imageName case year case price case identifier } // MARK: - Properties var name: String var imageName: String var year: Int var price: Double var identifier: UUID // MARK: - Initializers init(identifier: UUID, name: String, imageName: String, year: Int, price: Double) { self.identifier = identifier self.name = name self.imageName = imageName self.year = year self.price = price } // MARK: - Data Representation // Given the endoded JSON representation, return a product instance. func decodedProduct(data: Data) -> Product? { var product: Product? let decoder = JSONDecoder() if let decodedProduct = try? decoder.decode(Product.self, from: data) { product = decodedProduct } return product } // MARK: - Codable // For NSUserActivity scene-based state restoration. func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CoderKeys.self) try container.encode(name, forKey: .name) try container.encode(imageName, forKey: .imageName) try container.encode(year, forKey: .year) try container.encode(price, forKey: .price) try container.encode(identifier, forKey: .identifier) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CoderKeys.self) name = try values.decode(String.self, forKey: .name) year = try values.decode(Int.self, forKey: .year) price = try values.decode(Double.self, forKey: .price) imageName = try values.decode(String.self, forKey: .imageName) let decodedIdentifier = try values.decode(String.self, forKey: .identifier) identifier = UUID(uuidString: decodedIdentifier)! } } ``` ## SceneDelegate+StateRestoration.swift ```swift /* Abstract: State restoration support for this sample's main window scene delegate. */ import UIKit @available(iOS 13.0, *) extension SceneDelegate { // Activity type for restoring this scene (loaded from the plist). static let MainSceneActivityType = { () -> String in // Load the activity type from the Info.plist. let activityTypes = Bundle.main.infoDictionary?["NSUserActivityTypes"] as? [String] return activityTypes![0] } // State restoration keys: static let productKey = "product" // The product identifier. static let selectedTabKey = "selectedTab" // The selected tab bar item. static let presentedEditorKey = "presentedEditor" // Editor presentation state (true = presented). static let editorTitleKey = "editorTitle" // Editor title edit field. static let editorPriceKey = "editorPrice" // Editor price edit field. static let editorYearKey = "editorYear" // Editor year edit field. /** Data key for storing the session's userInfo. The system marks this session's userInfo with the current product's identifier so you can use it later to update this scene if it�s in the background. */ static let productIdentifierKey = "productIdentifier" /** This is the NSUserActivity that you use to restore state when the Scene reconnects. It can be the same activity that you use for handoff or spotlight, or it can be a separate activity with a different activity type and/or userInfo. This object must be lightweight. You should store the key information about what the user was doing last. After the system calls this function, and before it saves the activity in the restoration file, if the returned NSUserActivity has a delegate (NSUserActivityDelegate), the function userActivityWillSave calls that delegate. Additionally, if any UIResponders have the activity set as their userActivity property, the system calls the UIResponder updateUserActivityState function to update the activity. This happens synchronously and ensures that the system has filled in all the information for the activity before saving it. */ func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { // Offer the user activity for this scene. // Check whether the EditViewController is showing. if let rootViewController = window?.rootViewController as? UINavigationController, let detailParentViewController = rootViewController.topViewController as? DetailParentViewController, let presentedNavController = detailParentViewController.presentedViewController as? UINavigationController, let presentedViewController = presentedNavController.topViewController as? EditViewController { presentedViewController.updateUserActivity() } return scene.userActivity } // Utility function to return a Product instance from the input user activity. class func product(for activity: NSUserActivity) -> Product? { var product: Product! if let userInfo = activity.userInfo { // Decode the user activity product identifier from the userInfo. if let productIdentifier = userInfo[SceneDelegate.productKey] as? String { product = DataModelManager.sharedInstance.product(fromIdentifier: productIdentifier) } } return product } } ``` ## SceneDelegate.swift ```swift /* Abstract: This sample's main window scene delegate. */ import UIKit @available(iOS 13.0, *) class SceneDelegate: UIResponder, UIWindowSceneDelegate { static let storyboardName = "Main" var window: UIWindow? /** Apps configure their UIWindow and attach it to the provided UIWindowScene scene. The system calls willConnectTo shortly after the app delegate's "configurationForConnecting" function. Use this function to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. When using a storyboard file, as specified by the Info.plist key, UISceneStoryboardFile, the system automatically configures the window property and attaches it to the windowScene. Remember to retain the SceneDelegate's UIWindow. The recommended approach is for the SceneDelegate to retain the scene's window. */ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Determine the user activity from a new connection or from a session's state restoration. guard let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity else { return } if configure(window: window, session: session, with: userActivity) { // Remember this activity for later when this app quits or suspends. scene.userActivity = userActivity /** Set the title for this scene to allow the system to differentiate multiple scenes for the user. If set to nil or an empty string, the system doesn't display a title. */ scene.title = userActivity.title // Mark this scene's session with this userActivity product identifier so you can update the UI later. if let sessionProduct = SceneDelegate.product(for: userActivity) { session.userInfo = [SceneDelegate.productIdentifierKey: sessionProduct.identifier] } } else { Swift.debugPrint("Failed to restore scene from (userActivity)") } /** Set up the activation predicates to determine which scenes to activate. Restrictions: Block-based predicates are not allowed. Regular expression predicates are not allowed. The only keyPath you can reference is "self". */ let conditions = scene.activationConditions // The primary "can" predicate (the kind of content this scene can display � specific targetContentIdenfiers). conditions.canActivateForTargetContentIdentifierPredicate = NSPredicate(value: false) // The secondary "prefers" predicate (this scene displays certain content -� the product's identifier). if let activityProductIdentifier = session.userInfo![SceneDelegate.productIdentifierKey] as? String { let preferPredicate = NSPredicate(format: "self == %@", activityProductIdentifier) conditions.prefersToActivateForTargetContentIdentifierPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [preferPredicate]) } } func configure(window: UIWindow?, session: UISceneSession, with activity: NSUserActivity) -> Bool { var succeeded = false // Check the user activity type to know which part of the app to restore. if activity.activityType == SceneDelegate.MainSceneActivityType() { // The activity type is for restoring DetailParentViewController. // Present a parent detail view controller with the specified product and selected tab. let storyboard = UIStoryboard(name: SceneDelegate.storyboardName, bundle: .main) guard let detailParentViewController = storyboard.instantiateViewController(withIdentifier: DetailParentViewController.viewControllerIdentifier) as? DetailParentViewController else { return false } if let userInfo = activity.userInfo { // Decode the user activity product identifier from the userInfo. if let productIdentifier = userInfo[SceneDelegate.productKey] as? String { let product = DataModelManager.sharedInstance.product(fromIdentifier: productIdentifier) detailParentViewController.product = product } // Decode the selected tab bar controller tab from the userInfo. if let selectedTab = userInfo[SceneDelegate.selectedTabKey] as? Int { detailParentViewController.restoredSelectedTab = selectedTab } // Push the detail view controller for the user activity product. if let navigationController = window?.rootViewController as? UINavigationController { navigationController.pushViewController(detailParentViewController, animated: false) } succeeded = true } } else { // The incoming userActivity is not recognizable here. } return succeeded } /** Use this delegate as the system is releasing the scene or on window close. This occurs shortly after the scene enters the background, or when the system discards its session. Release any scene-related resources that the system can recreate the next time the scene connects. The scene may reconnect later because the system didn't necessarily discard its session (see`application:didDiscardSceneSessions` instead), so don't delete any user data or state permanently. */ func sceneDidDisconnect(_ scene: UIScene) { //.. } /** Use this delegate when the scene moves from an active state to an inactive state, on window close, or in iOS enter background. This may occur due to temporary interruptions (for example, an incoming phone call). */ func sceneWillResignActive(_ scene: UIScene) { // Save any pending changes to the product list. DataModelManager.sharedInstance.saveDataModel() if let userActivity = window?.windowScene?.userActivity { userActivity.resignCurrent() } } /** Use this delegate as the scene transitions from the background to the foreground, on window open, or in iOS resume. Use it to undo the changes made on entering the background. */ func sceneWillEnterForeground(_ scene: UIScene) { //.. } /** Use this delegate when the scene "has moved" from an inactive state to an active state. Also use it to restart any tasks that the system paused (or didn't start) when the scene was inactive. The system calls this delegate every time a scene becomes active so set up your scene UI here. */ func sceneDidBecomeActive(_ scene: UIScene) { if let userActivity = window?.windowScene?.userActivity { userActivity.becomeCurrent() } } /** Use this delegate as the scene transitions from the foreground to the background. Also use it to save data, release shared resources, and store enough scene-specific state information to restore the scene to its current state. */ func sceneDidEnterBackground(_ scene: UIScene) { // Save any pending changes to the product list. DataModelManager.sharedInstance.saveDataModel() } // MARK: - Window Scene // Listen for size change. func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) { // The scene size has changed. (User moved the slider horizontally in either direction.) } func updateScene(with product: Product) { if let navController = window!.rootViewController as? UINavigationController { if let collectionView = navController.viewControllers[0] as? CollectionViewController { // Update the collection view. collectionView.collectionView.reloadData() } // Update the detail view controller. if let detailParentViewController = navController.topViewController as? DetailParentViewController { // Check that the view controller product identifier matches the incoming product identifier. if product.identifier.uuidString == detailParentViewController.product.identifier.uuidString { detailParentViewController.product = product window?.windowScene!.title = product.name } } } } // MARK: - Handoff support func scene(_ scene: UIScene, willContinueUserActivityWithType userActivityType: String) { //.. } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard userActivity.activityType == SceneDelegate.MainSceneActivityType() else { return } if let rootViewController = window?.rootViewController as? UINavigationController { // Update the detail view controller. if let detailParentViewController = rootViewController.topViewController as? DetailParentViewController { detailParentViewController.product = SceneDelegate.product(for: userActivity) } } } func scene(_ scene: UIScene, didFailToContinueUserActivityWithType userActivityType: String, error: Error) { let alert = UIAlertController(title: NSLocalizedString("UnableToContinueTitle", comment: ""), message: error.localizedDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: NSLocalizedString("OKTitle", comment: ""), style: .default) { (action) in alert.dismiss(animated: true, completion: nil) } alert.addAction(okAction) window?.rootViewController?.present(alert, animated: true, completion: nil) } } ``` ## DataManager.swift ```swift /* Abstract: A data manager that manages data conforming to `Codable` and stores it in `UserDefaults`. */ import Foundation import os.log /// Provides storage configuration information to `DataManager` struct UserDefaultsStorageDescriptor { /// A `String` value used as the key name when reading and writing to `UserDefaults`. let key: String /// A key path to a property on `UserDefaults` for observing changes. let keyPath: KeyPath<UserDefaults, Data?> } /// Clients of `DataManager` that want to know when the data changes can listen for this notification. public let dataChangedNotificationKey = NSNotification.Name(rawValue: "DataChangedNotification") /// `DataManager` is an abstract class manging data conforming to `Codable` that is saved to `UserDefaults`. public class DataManager<ManagedDataType: Codable> { /// This sample uses App Groups to share a suite of data between the main app and the different extensions. let userDefaults = UserDefaults.dataSuite /// To prevent data races, all access to `UserDefaults` uses this queue. private let userDefaultsAccessQueue = DispatchQueue(label: "User Defaults Access Queue") /// Storage and observation information. private let storageDescriptor: UserDefaultsStorageDescriptor /// A flag to avoid receiving notifications about data this instance just wrote to `UserDefaults`. private var ignoreLocalUserDefaultsChanges = false /// The observer object handed back after registering to observe a property. private var userDefaultsObserver: NSKeyValueObservation? /// The data managed by this `DataManager`. Only access this via on the `dataAccessQueue`. var managedData: ManagedDataType! /// Access to `managedData` needs to occur on a dedicated queue to avoid data races. let dataAccessQueue = DispatchQueue(label: "Data Access Queue") init(storageDescriptor: UserDefaultsStorageDescriptor) { self.storageDescriptor = storageDescriptor loadData() if managedData == nil { deployInitialData() writeData() } observeChangesInUserDefaults() } /// Subclasses are expected to implement this method and set their own initial data for `managedData`. func deployInitialData() { } private func observeChangesInUserDefaults() { userDefaultsObserver = userDefaults.observe(storageDescriptor.keyPath) { [weak self] (_, _) in // Ignore any change notifications coming from data this instance just saved to `UserDefaults`. guard self?.ignoreLocalUserDefaultsChanges == false else { return } // The underlying data changed in `UserDefaults`, so update this instance with the change and notify clients of the change. self?.loadData() self?.notifyClientsDataChanged() } } /// Notifies clients the data changed by posting a `Notification` with the key `dataChangedNotificationKey`. private func notifyClientsDataChanged() { NotificationCenter.default.post(Notification(name: dataChangedNotificationKey, object: self)) } /// Loads the data from `UserDefaults`. private func loadData() { userDefaultsAccessQueue.sync { guard let archivedData = userDefaults.data(forKey: storageDescriptor.key) else { return } do { let decoder = PropertyListDecoder() managedData = try decoder.decode(ManagedDataType.self, from: archivedData) } catch let error as NSError { Logger().debug("Error decoding data: (error)") } } } /// Writes the data to `UserDefaults`. func writeData() { userDefaultsAccessQueue.async { do { let encoder = PropertyListEncoder() let encodedData = try encoder.encode(self.managedData) self.ignoreLocalUserDefaultsChanges = true self.userDefaults.set(encodedData, forKey: self.storageDescriptor.key) self.ignoreLocalUserDefaultsChanges = false self.notifyClientsDataChanged() } catch let error as NSError { Logger().debug("Could not encode data (error)") } } } } ``` ## MenuItem.swift ```swift /* Abstract: This type encapsulates the attributes of a soup menu item. */ import Foundation public struct MenuItem: Codable, Hashable, Identifiable { public enum Identifier: String, Codable { case chickenNoodleSoup case tomatoSoup case newEnglandClamChowder case manhattanClamChowder } public struct Attributes: OptionSet, Codable, Hashable { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let available = Attributes(rawValue: 1 << 0) public static let regularItem = Attributes(rawValue: 1 << 1) public static let dailySpecialItem = Attributes(rawValue: 1 << 2) public static let secretItem = Attributes(rawValue: 1 << 3) } public let id: Identifier public let price: Decimal public var itemsInStock: Int public var attributes: Attributes } extension MenuItem { public var iconImageName: String { switch id { case .newEnglandClamChowder, .manhattanClamChowder: return "clam_chowder" case .chickenNoodleSoup: return "chicken_noodle_soup" case .tomatoSoup: return "tomato_soup" } } } extension MenuItem: LocalizableShortcutString { // See comments on `LocalizableShortcutString` to understand the `useDeferredIntentLocalization` value. public func localizedName(useDeferredIntentLocalization: Bool = false) -> String { return localizedString(for: localizedNameKey, useDeferredIntentLocalization: useDeferredIntentLocalization) } // See comments on `LocalizableShortcutString` to understand the `useDeferredIntentLocalization` value. public func localizedItemDescription(useDeferredIntentLocalization: Bool = false) -> String { return localizedString(for: localizedDescriptionKey, useDeferredIntentLocalization: useDeferredIntentLocalization) } // See comments on `LocalizableShortcutString` to understand the `useDeferredIntentLocalization` value. public func localizedItemSubtitle(useDeferredIntentLocalization: Bool = false) -> String { return localizedString(for: localizedSubtitleKey, useDeferredIntentLocalization: useDeferredIntentLocalization) } // See comments on `LocalizableShortcutString` to understand the `useDeferredIntentLocalization` value. private func localizedString(for key: String, useDeferredIntentLocalization: Bool = false) -> String { if useDeferredIntentLocalization { return NSString.deferredLocalizedIntentsString(with: key) as String } else { return NSLocalizedString(key, comment: "Menu item") } } private var localizedNameKey: String { switch id { case .newEnglandClamChowder: return "NE_CLAM_CHOWDER" case .manhattanClamChowder: return "MANHATTAN_CLAM_CHOWDER" case .chickenNoodleSoup: return "CHICKEN_NOODLE_SOUP" case .tomatoSoup: return "TOMATO_SOUP" } } private var localizedSubtitleKey: String { return localizedNameKey + "_SUBTITLE" } private var localizedDescriptionKey: String { switch id { case .newEnglandClamChowder: return "NE_CLAM_CHOWDER_DESCRIPTION" case .manhattanClamChowder: return "MANHATTAN_CLAM_CHOWDER_DESCRIPTION" case .chickenNoodleSoup: return "CHICKEN_NOODLE_SOUP_DESCRIPTION" case .tomatoSoup: return "TOMATO_SOUP_DESCRIPTION" } } } extension MenuItem: LocalizableCurrency { public var localizedCurrencyValue: String { return NumberFormatter.currencyFormatter.string(from: price as NSDecimalNumber) ?? "" } } ``` ## Order.swift ```swift /* Abstract: This type encapsulates the attributes of a soup order. */ import Foundation import Contacts import CoreLocation import Intents public struct Order: Codable, Identifiable { public enum MenuItemTopping: String, Codable, CaseIterable, LocalizableShortcutString { case cheese = "Cheese" case redPepper = "Red Pepper" case croutons = "Croutons" // See comments on `LocalizableShortcutString` to understand the `useDeferredIntentLocalization` value. public func localizedName(useDeferredIntentLocalization: Bool = false) -> String { if useDeferredIntentLocalization { return NSString.deferredLocalizedIntentsString(with: localizationKey) as String } else { return NSLocalizedString(localizationKey, comment: "Topping name") } } private var localizationKey: String { switch self { case .cheese: return "CHEESE" case .redPepper: return "RED_PEPPER" case .croutons: return "CROUTONS" } } } public static let storeLocations: [CLPlacemark] = [ CLPlacemark(location: CLLocation(latitude: 37.795_316, longitude: -122.393_76), name: "Ferry Building", postalAddress: nil), CLPlacemark(location: CLLocation(latitude: 37.779_379, longitude: -122.418_433), name: "Civic Center", postalAddress: nil) ] public let date: Date public let id: UUID public let menuItem: MenuItem public var quantity: Int public var menuItemToppings: Set<MenuItemTopping> public var total: Decimal { return Decimal(quantity) * menuItem.price } public var storeLocation: Location? public var deliveryLocation: Location? public var orderType: OrderType public init(date: Date = Date(), identifier: UUID = UUID(), quantity: Int, menuItem: MenuItem, menuItemToppings: Set<MenuItemTopping>, storeLocation: Location? = nil) { self.date = date self.id = identifier self.quantity = quantity self.menuItem = menuItem self.menuItemToppings = menuItemToppings self.orderType = .pickup self.storeLocation = storeLocation } public init(date: Date = Date(), identifier: UUID = UUID(), quantity: Int, menuItem: MenuItem, menuItemToppings: Set<MenuItemTopping>, deliveryLocation: Location?) { self.init(date: date, identifier: identifier, quantity: quantity, menuItem: menuItem, menuItemToppings: menuItemToppings) self.deliveryLocation = deliveryLocation self.orderType = .delivery } } extension Order: Hashable { public static func ==(lhs: Order, rhs: Order) -> Bool { return lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } } extension Order: LocalizableCurrency { public var localizedCurrencyValue: String { return NumberFormatter.currencyFormatter.string(from: total as NSDecimalNumber) ?? "" } } public struct Location: Codable { public var name: String? public var latitude: Double public var longitude: Double init(name: String?, latitude: Double, longitude: Double) { self.name = name self.latitude = latitude self.longitude = longitude } init?(_ placemark: CLPlacemark?) { guard let placemark = placemark, let location = placemark.location else { return nil } self.init(name: placemark.name, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) } } extension Location { public var location: CLLocation { return CLLocation(latitude: self.latitude, longitude: self.longitude) } public var placemark: CLPlacemark { return CLPlacemark(location: self.location, name: self.name, postalAddress: nil) } } extension OrderType: Codable { } ``` ## SoupMenuManager.swift ```swift /* Abstract: */ import Foundation public typealias SoupMenu = Set<MenuItem> public class SoupMenuManager: DataManager<Set<MenuItem>> { // MARK: - SoupMenuManager private static let defaultMenu: SoupMenu = [ MenuItem(itemName: "Chicken Noodle Soup", price: 4.55, iconImageName: "chicken_noodle_soup", isAvailable: false, isDailySpecial: true), MenuItem(itemName: "Minestrone Soup", price: 3.75, iconImageName: "minestrone_soup", isAvailable: true, isDailySpecial: false), MenuItem(itemName: "Tomato Soup", price: 2.95, iconImageName: "tomato_soup", isAvailable: true, isDailySpecial: false) ] // MARK: - Data Manager public convenience init() { let storageInfo = UserDefaultsStorageDescriptor(key: UserDefaults.Keys.soupMenuStorage.rawValue, keyPath: \UserDefaults.menu) self.init(storageDescriptor: storageInfo) } override func deployInitialData() -> Set<MenuItem>! { return SoupMenuManager.defaultMenu } } extension SoupMenuManager { // MARK: - Public API public var dailySpecialItems: [MenuItem] { var specials: [MenuItem] = [] dataAccessQueue.sync { specials = managedDataBackingInstance.filter { $0.isDailySpecial == true } } return specials } public var allRegularItems: [MenuItem] { var specials: [MenuItem] = [] dataAccessQueue.sync { specials = managedDataBackingInstance.filter { $0.isDailySpecial == false } } return specials } public var availableRegularItems: [MenuItem] { return allRegularItems.filter { $0.isAvailable == true } } public func replaceMenuItem(_ currentMenuItem: MenuItem, with newMenuItem: MenuItem) { dataAccessQueue.sync { managedDataBackingInstance.remove(currentMenuItem) managedDataBackingInstance.insert(newMenuItem) } // Access to UserDefaults is gated behind a seperate access queue writeData() } } private extension UserDefaults { @objc var menu: Data? { return data(forKey: Keys.soupMenuStorage.rawValue) } } ``` ## SoupOrderDataManager.swift ```swift /* Abstract: A data manager that manages an array of `Order` structs. */ import Foundation import Intents import os.log /// A concrete `DataManager` for reading and writing data of type `[Order]`. public class SoupOrderDataManager: DataManager<[Order]> { public convenience init() { let storageInfo = UserDefaultsStorageDescriptor(key: UserDefaults.StorageKeys.orderHistory.rawValue, keyPath: \UserDefaults.orderHistory) self.init(storageDescriptor: storageInfo) } override func deployInitialData() { dataAccessQueue.sync { // Order history is empty the first time the app is used. managedData = [] } } /// Converts an `Order` into `OrderSoupIntent` and donates it as an interaction to the system /// so that this order can be suggested in the future or turned into a shortcut for /// quickly placing the same order in the future. /// - Tag: donate_order private func donateInteraction(for order: Order) { let interaction = INInteraction(intent: order.intent, response: nil) // Store the order identifier with the interaction so that it is easy // to locate an interaction from an order. When a soup is removed from // the menu, the app deletes the interaction so the soup isn't suggested // to the user. interaction.identifier = order.id.uuidString interaction.donate { (error) in if error != nil { if let error = error as NSError? { Logger().debug("Interaction donation failed: (error)") } } else { Logger().debug("Successfully donated interaction") } } } /// Typically, you only want to delete interactions that are no longer relevant, such as when a soup /// is no longer available, as shown in `removeDonation(for:)`. For this app, removing all donations /// is only used as part of clearing the entire order history for testing and demonstration purposes. func removeAllDonations() { INInteraction.deleteAll { error in if error != nil { if let error = error as NSError? { Logger().debug("Deleting all interaction donations failed: (error)") } } else { Logger().debug("Successfully deleted all interactions") } } } } /// Public API for clients of `SoupOrderDataManager` extension SoupOrderDataManager { /// Convenience method to access the data with a property name that makes sense in the caller's context. public var orderHistory: [Order] { return dataAccessQueue.sync { return managedData } } /// Tries to find an order by its identifier. public func order(matching identifier: UUID) -> Order? { return orderHistory.first { $0.id == identifier } } /// Stores the order in the data manager. /// Note: This project does not share data between iOS and watchOS. Orders placed on watchOS will not display in the iOS order history. public func placeOrder(order: Order) { // Access to `managedDataBackingInstance` is only valid on `dataAccessQueue`. dataAccessQueue.sync { managedData.insert(order, at: 0) } // Access to UserDefaults is gated behind a separate access queue. writeData() // Donate an interaction to the system. donateInteraction(for: order) } /// Clear the order history and delete all associated intent donations. public func clearOrderHistory() { removeAllDonations() deployInitialData() writeData() } } /// Enables observation of `UserDefaults` for the `orderHistory` key. private extension UserDefaults { @objc var orderHistory: Data? { return data(forKey: StorageKeys.orderHistory.rawValue) } } ``` ## Order+Intents.swift ```swift /* Abstract: Conversion utilities for converting between `Order` and `OrderSoupIntent`. */ import Foundation import Intents extension Order { public var intent: OrderSoupIntent { let orderSoupIntent = OrderSoupIntent() orderSoupIntent.quantity = quantity as NSNumber orderSoupIntent.soup = Soup(identifier: menuItem.id.rawValue, display: menuItem.localizedName(useDeferredIntentLocalization: true)) orderSoupIntent.orderType = orderType orderSoupIntent.setImage(INImage(named: menuItem.iconImageName), forParameterNamed: \OrderSoupIntent.soup) orderSoupIntent.toppings = menuItemToppings.map { (topping) -> Topping in return Topping(identifier: topping.rawValue, display: topping.localizedName(useDeferredIntentLocalization: true)) } orderSoupIntent.suggestedInvocationPhrase = NSString.deferredLocalizedIntentsString(with: "ORDER_SOUP_SUGGESTED_PHRASE") as String return orderSoupIntent } public init?(from intent: OrderSoupIntent) { let menuManager = SoupMenuManager() guard let soup = intent.soup, let menuItem = menuManager.findItem(soup), let quantity = intent.quantity else { return nil } let rawToppings = intent.toppings?.compactMap { (toppping) -> MenuItemTopping? in guard let toppingID = toppping.identifier else { return nil } return MenuItemTopping(rawValue: toppingID) } ?? [MenuItemTopping]() // If the result of the map is nil (because `intent.toppings` is nil), provide an empty array. switch intent.orderType { case .unknown: self.init(quantity: quantity.intValue, menuItem: menuItem, menuItemToppings: Set(rawToppings)) case .delivery: self.init(quantity: quantity.intValue, menuItem: menuItem, menuItemToppings: Set(rawToppings), deliveryLocation: Location(intent.deliveryLocation)) case .pickup: self.init(quantity: quantity.intValue, menuItem: menuItem, menuItemToppings: Set(rawToppings), storeLocation: Location(intent.storeLocation)) } } } extension Topping { public static var allToppings: [Topping] { // Map menu item toppings to custom objects and provide them to the user. // The user will be able to choose one or more options. return Order.MenuItemTopping.allCases.map { (topping) -> Topping in return Topping(identifier: topping.rawValue, display: topping.localizedName(useDeferredIntentLocalization: true)) } } } extension Soup { @available(iOSApplicationExtension 14.0, watchOSApplicationExtension 7.0, *) convenience init(menuItem: MenuItem) { self.init(identifier: menuItem.id.rawValue, display: menuItem.localizedName(useDeferredIntentLocalization: true), subtitle: menuItem.localizedItemDescription(useDeferredIntentLocalization: true), image: INImage(named: menuItem.iconImageName)) } } extension Soup { public static var allSoups: [Soup] { let activeMenu = SoupMenuManager() return activeMenu.findItems(exactlyMatching: [.available, .regularItem], [.available, .dailySpecialItem]).map { // Map all available menu items to custom Soup objects and provide them to the user. if #available(iOSApplicationExtension 14.0, watchOSApplicationExtension 7.0, *) { return Soup(menuItem: $0) } else { return Soup(identifier: $0.id.rawValue, display: $0.localizedName(useDeferredIntentLocalization: true)) } } } } ``` ## OrderSoupIntentHandler.swift ```swift /* Abstract: Intent handler for `OrderSoupIntent`. */ import UIKit import CoreLocation import Intents public class OrderSoupIntentHandler: NSObject, OrderSoupIntentHandling { // The Dynamic Options API allows you to provide a set of values for eligible parameters // dynamically when the user configures this intent parameter in the Shortcuts app. // // The system calls this method repeatedly while the user types their search term. @available(iOSApplicationExtension 14.0, watchOSApplicationExtension 7.0, *) public func provideSoupOptionsCollection(for intent: OrderSoupIntent, searchTerm: String?, with completion: @escaping (INObjectCollection<Soup>?, Error?) -> Void) { let soupMenuManager = SoupMenuManager() // Dynamic search should only be adopted for searching large catalogs, and not for small static colletions. // The Shortcuts app supports filtering of small collections by default. let availableRegularItems = soupMenuManager.findItems(exactlyMatching: [.available, .regularItem], searchTerm: searchTerm) let availableDailySpecialItems = soupMenuManager.findItems(exactlyMatching: [.available, .dailySpecialItem], searchTerm: searchTerm) let objectCollection = INObjectCollection(sections: [ INObjectSection(title: "Regular", items: availableRegularItems.map { Soup(menuItem: $0) }), INObjectSection(title: "Special", items: availableDailySpecialItems.map { Soup(menuItem: $0) }) ]) completion(objectCollection, nil) } @available(iOSApplicationExtension 14.0, watchOSApplicationExtension 7.0, *) public func provideToppingsOptionsCollection(for intent: OrderSoupIntent, with completion: @escaping (INObjectCollection<Topping>?, Error?) -> Void) { completion(INObjectCollection(items: Topping.allToppings), nil) } @available(iOSApplicationExtension 14.0, watchOSApplicationExtension 7.0, *) public func provideStoreLocationOptionsCollection(for intent: OrderSoupIntent, with completion: @escaping (INObjectCollection<CLPlacemark>?, Error?) -> Void) { completion(INObjectCollection(items: Order.storeLocations), nil) } /// - Tag: resolve_intent public func resolveToppings(for intent: OrderSoupIntent, with completion: @escaping ([ToppingResolutionResult]) -> Void) { guard let toppings = intent.toppings else { completion([ToppingResolutionResult.needsValue()]) return } if toppings.isEmpty { completion([ToppingResolutionResult.notRequired()]) return } completion(toppings.map { (topping) -> ToppingResolutionResult in return ToppingResolutionResult.success(with: topping) }) } public func resolveSoup(for intent: OrderSoupIntent, with completion: @escaping (SoupResolutionResult) -> Void) { guard let soup = intent.soup else { completion(SoupResolutionResult.disambiguation(with: Soup.allSoups)) return } completion(SoupResolutionResult.success(with: soup)) } public func resolveQuantity(for intent: OrderSoupIntent, with completion: @escaping (OrderSoupQuantityResolutionResult) -> Void) { let soupMenuManager = SoupMenuManager() guard let soup = intent.soup, let menuItem = soupMenuManager.findItem(soup) else { completion(OrderSoupQuantityResolutionResult.unsupported()) return } // A soup order requires a quantity. guard let quantity = intent.quantity else { completion(OrderSoupQuantityResolutionResult.needsValue()) return } // If the user asks to order more soups than we have in stock, // provide a specific response informing the user why we can't handle the order. if quantity.intValue > menuItem.itemsInStock { completion(OrderSoupQuantityResolutionResult.unsupported(forReason: .notEnoughInStock)) return } // Ask the user to confirm that they actually want to order 5 or more soups. if quantity.intValue >= 5 { completion(OrderSoupQuantityResolutionResult.confirmationRequired(with: quantity.intValue)) return } completion(OrderSoupQuantityResolutionResult.success(with: quantity.intValue)) } public func resolveOrderType(for intent: OrderSoupIntent, with completion: @escaping (OrderTypeResolutionResult) -> Void) { if intent.orderType == .unknown { completion(OrderTypeResolutionResult.needsValue()) } else { completion(OrderTypeResolutionResult.success(with: intent.orderType)) } } public func resolveDeliveryLocation(for intent: OrderSoupIntent, with completion: @escaping (INPlacemarkResolutionResult) -> Void) { guard let deliveryLocation = intent.deliveryLocation else { completion(INPlacemarkResolutionResult.needsValue()) return } completion(INPlacemarkResolutionResult.success(with: deliveryLocation)) } public func resolveStoreLocation(for intent: OrderSoupIntent, with completion: @escaping (INPlacemarkResolutionResult) -> Void) { guard let storeLocation = intent.storeLocation else { completion(INPlacemarkResolutionResult.needsValue()) return } completion(INPlacemarkResolutionResult.success(with: storeLocation)) } /// - Tag: confirm_intent public func confirm(intent: OrderSoupIntent, completion: @escaping (OrderSoupIntentResponse) -> Void) { /* The confirm phase provides an opportunity for you to perform any final validation of the intent parameters and to verify that any needed services are available. You might confirm that you can communicate with your company�s server. */ let soupMenuManager = SoupMenuManager() guard let soup = intent.soup, let menuItem = soupMenuManager.findItem(soup) else { completion(OrderSoupIntentResponse(code: .failure, userActivity: nil)) return } if menuItem.attributes.contains(.available) == false { // Here's an example of how to use a custom response for a failure case when a particular soup item is unavailable. completion(OrderSoupIntentResponse.failureOutOfStock(soup: soup)) return } // Once the intent is validated, indicate that the intent is ready to handle. completion(OrderSoupIntentResponse(code: .ready, userActivity: nil)) } public func handle(intent: OrderSoupIntent, completion: @escaping (OrderSoupIntentResponse) -> Void) { guard let order = Order(from: intent), let soup = intent.soup else { completion(OrderSoupIntentResponse(code: .failure, userActivity: nil)) return } // The handle method is also an appropriate place to handle payment via Apple Pay. // A declined payment is another example of a failure case that could take advantage of a custom response. // Place the soup order via the order manager. let orderManager = SoupOrderDataManager() orderManager.placeOrder(order: order) // For the success case, we want to indicate a wait time so the user knows when their soup order will be ready. // This sample uses a hardcoded value, but your implementation could use a time returned by your server. let orderDate = Date() let readyDate = Date(timeInterval: 10 * 60, since: orderDate) // 10 minutes let userActivity = NSUserActivity(activityType: NSUserActivity.orderCompleteActivityType) userActivity.addUserInfoEntries(from: [NSUserActivity.ActivityKeys.orderID.rawValue: order.id]) let formatter = DateComponentsFormatter() formatter.unitsStyle = .full let orderDetails = OrderDetails(identifier: nil, display: formatter.string(from: orderDate, to: readyDate) ?? "") orderDetails.estimatedTime = Calendar.current.dateComponents([.minute, .hour, .day, .month, .year], from: readyDate) orderDetails.total = INCurrencyAmount(amount: NSDecimalNumber(decimal: order.total), currencyCode: NumberFormatter.currencyFormatter.currencyCode) let response: OrderSoupIntentResponse if let formattedWaitTime = formatter.string(from: orderDate, to: readyDate) { response = OrderSoupIntentResponse.success(orderDetails: orderDetails, soup: soup, waitTime: formattedWaitTime) } else { // A fallback success code with a less specific message string. response = OrderSoupIntentResponse.successReadySoon(orderDetails: orderDetails, soup: soup) } response.userActivity = userActivity completion(response) } } ``` ## SoupMenuManager+Intents.swift ```swift /* Abstract: An extension on SoupMenuManager that creates shortcuts to menu items. */ import Foundation import Intents import os.log /// This extension contains supporting methods for using the Intents framework. extension SoupMenuManager { /// Inform Siri of changes to the menu. func updateShortcuts() { updateMenuItemShortcuts() updateSuggestions() } /// Each time an order is placed, we instantiate an `INInteraction` object and donate it to the system (see SoupOrderDataManager extension). /// After instantiating the `INInteraction`, its identifier property is set to the same value as the identifier /// property for the corresponding order. Compile a list of all the order identifiers to pass to the `INInteraction.delete(with:)` method. func removeDonation(for menuItem: MenuItem) { if menuItem.attributes.contains(.available) == false { guard let orderHistory = orderManager?.orderHistory else { return } let ordersAssociatedWithRemovedMenuItem = orderHistory.filter { $0.menuItem.id == menuItem.id } let orderIdentifiersToRemove = ordersAssociatedWithRemovedMenuItem.map { $0.id.uuidString } INInteraction.delete(with: orderIdentifiersToRemove) { (error) in if error != nil { if let error = error as NSError? { Logger().debug("Failed to delete interactions with error (error)") } } else { Logger().debug("Successfully deleted interactions") } } } } /// Configures a secret menu item to be made available as a relevant shortcut. This item /// is not available on the regular menu to demonstrate how relevant shortcuts are able to /// suggest tasks the user may want to start, but haven't used in the app before. private func updateSuggestions() { let availableSecretItems = findItems(exactlyMatching: [.available, .secretItem]) let secretMenuSuggestedShortcuts = availableSecretItems.compactMap { (menuItem) -> INRelevantShortcut? in let order = Order(quantity: 1, menuItem: menuItem, menuItemToppings: []) let orderIntent = order.intent guard let shortcut = INShortcut(intent: orderIntent) else { return nil } let suggestedShortcut = INRelevantShortcut(shortcut: shortcut) let localizedTitle = NSString.deferredLocalizedIntentsString(with: "ORDER_LUNCH_TITLE") as String let template = INDefaultCardTemplate(title: localizedTitle) // Using the subtitle instead of item name because relevant shortcuts have // different guidelines for wording and capitalization. See the Siri section of // the Human Interface Guidelines. template.subtitle = menuItem.localizedItemSubtitle(useDeferredIntentLocalization: true) template.image = INImage(named: menuItem.iconImageName) suggestedShortcut.watchTemplate = template // Make a lunch suggestion when arriving to work. let routineRelevanceProvider = INDailyRoutineRelevanceProvider(situation: .work) // This sample uses a single relevance provider, but using multiple relevance providers is supported. suggestedShortcut.relevanceProviders = [routineRelevanceProvider] return suggestedShortcut } INRelevantShortcutStore.default.setRelevantShortcuts(secretMenuSuggestedShortcuts) { (error) in if let error = error as NSError? { Logger().debug("Providing relevant shortcut failed. \n(error)") } else { Logger().debug("Providing relevant shortcut succeeded") } } } /// Provides shortcuts for orders the user may want to place, based on a menu item's availability. /// The results of this method are visible in the Shortcuts app. private func updateMenuItemShortcuts() { let availableRegularItems = findItems(exactlyMatching: [.available, .regularItem]) let availableShortcuts = availableRegularItems.compactMap { (menuItem) -> INShortcut? in let order = Order(quantity: 1, menuItem: menuItem, menuItemToppings: []) return INShortcut(intent: order.intent) } INVoiceShortcutCenter.shared.setShortcutSuggestions(availableShortcuts) } } ``` ## SoupMenuManager.swift ```swift /* Abstract: A DataManager subclass that persists the active menu items. */ import Foundation import os.log public typealias SoupMenu = Set<MenuItem> public class SoupMenuManager: DataManager<Set<MenuItem>> { private static let defaultMenu: SoupMenu = [ MenuItem(id: .chickenNoodleSoup, price: 4.55, itemsInStock: 5, attributes: [.available, .dailySpecialItem]), MenuItem(id: .newEnglandClamChowder, price: 3.75, itemsInStock: 7, attributes: [.available, .regularItem]), MenuItem(id: .manhattanClamChowder, price: 3.50, itemsInStock: 2, attributes: [.available, .secretItem]), MenuItem(id: .tomatoSoup, price: 2.95, itemsInStock: 4, attributes: [.available, .regularItem]) ] public var orderManager: SoupOrderDataManager? public convenience init() { let storageInfo = UserDefaultsStorageDescriptor(key: UserDefaults.StorageKeys.soupMenu.rawValue, keyPath: \UserDefaults.menu) self.init(storageDescriptor: storageInfo) } override func deployInitialData() { dataAccessQueue.sync { managedData = SoupMenuManager.defaultMenu } updateShortcuts() } } /// Public API for clients of `SoupMenuManager` extension SoupMenuManager { public func replaceMenuItem(_ previousMenuItem: MenuItem, with menuItem: MenuItem) { dataAccessQueue.sync { managedData.remove(previousMenuItem) managedData.insert(menuItem) } // Access to UserDefaults is gated behind a seperate access queue. writeData() removeDonation(for: menuItem) updateShortcuts() } public func findItem(_ soup: Soup) -> MenuItem? { return dataAccessQueue.sync { return managedData.first { $0.id == MenuItem.Identifier(rawValue: soup.identifier!) } } } /// Locates items by exactly matching the attributes. This means searching for `[.available]` and `[.available, .regularMenuItem]` /// return different results. public func findItems(exactlyMatching searchAttributes: MenuItem.Attributes..., searchTerm: String? = nil) -> [MenuItem] { return dataAccessQueue.sync { return managedData.filter { searchAttributes.contains($0.attributes) }.sortedByName().filter { searchTerm == nil || $0.localizedName(useDeferredIntentLocalization: true).localizedCaseInsensitiveContains(searchTerm ?? "") } } } /// Locates items containing the attributes. This means searching for `[.regularMenuItem]` will return results for both /// `[.regularMenuItem]` and `[.available, .regularMenuItem]`. public func findItems(containing searchAttributes: MenuItem.Attributes...) -> [MenuItem] { return dataAccessQueue.sync { return searchAttributes.reduce([MenuItem]()) { (result, attribute) -> [MenuItem] in return result + managedData.filter { $0.attributes.contains(attribute) } }.sortedByName() } } } /// Enables observation of `UserDefaults` for the `soupMenuStorage` key. private extension UserDefaults { @objc var menu: Data? { return data(forKey: StorageKeys.soupMenu.rawValue) } } private extension Array where Element == MenuItem { func sortedByName() -> [MenuItem] { return sorted { (item1, item2) -> Bool in item1.localizedName().localizedCaseInsensitiveCompare(item2.localizedName()) == .orderedAscending } } } ``` ## Localizable.swift ```swift /* Abstract: A utility for requesting localized strings for the user interface. */ import Foundation /// A type with a localized string that will load the appropriate localized value for a shortcut. protocol LocalizableShortcutString { /// - Parameter useDeferredIntentLocalization: Use deferred localization for any user-facing values that the system will /// display as part of a shortcut on behalf of your app in the future. This allows the system to display the value of the string using /// the device's language settings at the time the shortcut is displayed, which might be a different language from when the shortcut /// was created. This supports users who switch between multiple languages. /// - Returns: A localized string for the item description. func localizedName(useDeferredIntentLocalization: Bool) -> String } /// A type with a localized currency string that is appropiate to display in UI. protocol LocalizableCurrency { /// - Returns: A string that displays a locale sensitive currency format. var localizedCurrencyValue: String { get } } ``` ## NSUserActivity+IntentData.swift ```swift /* Abstract: Convenience utility for working with NSUserActivity. */ import Foundation import UniformTypeIdentifiers #if canImport(CoreSpotlight) import CoreSpotlight import UIKit #endif extension NSUserActivity { public enum ActivityKeys: String { case orderID } public static let viewMenuActivityType = "com.example.apple-samplecode.SoupChef.viewMenu" public static let orderCompleteActivityType = "com.example.apple-samplecode.SoupChef.orderComplete" public static var viewMenuActivity: NSUserActivity { let userActivity = NSUserActivity(activityType: NSUserActivity.viewMenuActivityType) // User activites should be as rich as possible, with icons and localized strings for appropiate content attributes. userActivity.title = NSLocalizedString("ORDER_LUNCH_TITLE", comment: "View menu activity title") userActivity.isEligibleForPrediction = true #if canImport(CoreSpotlight) let attributes = CSSearchableItemAttributeSet(contentType: UTType.content) attributes.thumbnailData = #imageLiteral(resourceName: "tomato").pngData() // Used as an icon in Search. attributes.keywords = ["Order", "Soup", "Menu"] attributes.displayName = NSLocalizedString("ORDER_LUNCH_TITLE", comment: "View menu activity title") let localizationComment = "View menu content description" attributes.contentDescription = NSLocalizedString("VIEW_MENU_CONTENT_DESCRIPTION", comment: localizationComment) userActivity.contentAttributeSet = attributes #endif let phrase = NSString.deferredLocalizedIntentsString(with: "ORDER_LUNCH_SUGGESTED_PHRASE") as String userActivity.suggestedInvocationPhrase = phrase return userActivity } } ``` ## NumberFormatter+Currency.swift ```swift /* Abstract: Convenience utility to format numbers as currency. */ import Foundation extension NumberFormatter { public static var currencyFormatter: NumberFormatter { let formatter = NumberFormatter() formatter.numberStyle = .currency return formatter } } ``` ## UIImage+Extension.swift ```swift /* Abstract: Utility extension on `UIImageView` for visual appearance. */ import UIKit extension UIImageView { public func applyRoundedCorners() { layer.cornerRadius = 8 clipsToBounds = true } } ``` ## UserDefaults+DataSource.swift ```swift /* Abstract: Convenience utility for working with UserDefaults. */ import Foundation extension UserDefaults { /// - Tag: app_group // Note: This project does not share data between iOS and watchOS. Orders placed on watchOS will not display in the iOS order history. private static let AppGroup = "group.com.example.apple-samplecode.SoupChef.Shared" enum StorageKeys: String { case soupMenu case orderHistory case voiceShortcutHistory } static let dataSuite = { () -> UserDefaults in guard let dataSuite = UserDefaults(suiteName: AppGroup) else { fatalError("Could not load UserDefaults for app group (AppGroup)") } return dataSuite }() } ``` ## AddToSiriCollectionViewCell.swift ```swift /* Abstract: A specalized collection view cell containing an Add to Siri button. */ import UIKit import IntentsUI import SoupKit class AddToSiriCollectionViewCell: UICollectionViewCell { var data: (OrderSoupIntent?, INUIAddVoiceShortcutButtonDelegate?) { didSet { setNeedsUpdateConfiguration() } } override func updateConfiguration(using state: UICellConfigurationState) { var content = AddToSiriCellContentConfiguration().updated(for: state) content.intent = data.0 content.delegate = data.1 contentConfiguration = content } } struct AddToSiriCellContentConfiguration: UIContentConfiguration, Hashable { var intent: OrderSoupIntent? weak var delegate: INUIAddVoiceShortcutButtonDelegate? func makeContentView() -> UIView & UIContentView { return AddToSiriCollectionViewCellContentView(configuration: self) } func updated(for state: UIConfigurationState) -> Self { return self } static func == (lhs: AddToSiriCellContentConfiguration, rhs: AddToSiriCellContentConfiguration) -> Bool { return lhs.intent == rhs.intent } func hash(into hasher: inout Hasher) { hasher.combine(intent) } } private class AddToSiriCollectionViewCellContentView: UIView, UIContentView { init(configuration: AddToSiriCellContentConfiguration) { super.init(frame: .zero) apply(configuration: configuration) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var configuration: UIContentConfiguration { get { appliedConfiguration } set { guard let newConfig = newValue as? AddToSiriCellContentConfiguration else { return } apply(configuration: newConfig) } } private var addShortcutButton: INUIAddVoiceShortcutButton! = nil private var appliedConfiguration: AddToSiriCellContentConfiguration! private func apply(configuration: AddToSiriCellContentConfiguration) { guard appliedConfiguration != configuration else { return } appliedConfiguration = configuration guard let orderSoupIntent = appliedConfiguration.intent else { return } addShortcutButton = INUIAddVoiceShortcutButton(style: .automaticOutline) addShortcutButton.shortcut = INShortcut(intent: orderSoupIntent) addShortcutButton.delegate = configuration.delegate addShortcutButton.translatesAutoresizingMaskIntoConstraints = false addSubview(addShortcutButton) centerXAnchor.constraint(equalTo: addShortcutButton.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: addShortcutButton.centerYAnchor).isActive = true heightAnchor.constraint(equalTo: addShortcutButton.heightAnchor).isActive = true addShortcutButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 146).isActive = true backgroundColor = .systemGroupedBackground } } ``` ## AppDelegate.swift ```swift /* Abstract: The application delegate. */ import UIKit import SoupKit import os.log @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { } ``` ## ConfigureMenuTableViewController.swift ```swift /* Abstract: This view controller allows you to enable and disable menu items from the active menu. `SoupMenuViewController` displays the active menu. When a menu item is disabled, any donated actions associated with the menu item are deleted from the system. */ import UIKit import SoupKit class ConfigureMenuTableViewController: UITableViewController { private enum SectionType { case visibleMenu, hiddenMenu } private typealias SectionModel = (sectionType: SectionType, sectionHeaderText: String, sectionFooterText: String, rowContent: [MenuItem]) public var soupMenuManager: SoupMenuManager! public var soupOrderDataManager: SoupOrderDataManager! { didSet { soupMenuManager.orderManager = soupOrderDataManager } } private var sectionData: [SectionModel]! override func viewDidLoad() { super.viewDidLoad() reloadData() } private func reloadData() { sectionData = [SectionModel(sectionType: .visibleMenu, sectionHeaderText: "Visible Menu", sectionFooterText: "Uncheck a row to delete any donated shortcuts associated with the menu item.", rowContent: soupMenuManager.findItems(containing: [.regularItem], [.dailySpecialItem])), SectionModel(sectionType: .hiddenMenu, sectionHeaderText: "Hidden Menu", sectionFooterText: "These menu items will only appear as relevant shortcuts on the Siri watch face.", rowContent: soupMenuManager.findItems(containing: [.secretItem]))] tableView.reloadData() } } extension ConfigureMenuTableViewController { // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return sectionData.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionData[section].rowContent.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Basic Cell", for: indexPath) let menuItem = sectionData[indexPath.section].rowContent[indexPath.row] cell.textLabel?.text = menuItem.localizedName() cell.accessoryType = menuItem.attributes.contains(.available) ? .checkmark : .none return cell } } extension ConfigureMenuTableViewController { // MARK: - Table delegate override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionData[section].sectionHeaderText } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sectionData[section].sectionFooterText } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sectionModel = sectionData[indexPath.section] let currentMenuItem = sectionModel.rowContent[indexPath.row] var newMenuItem = currentMenuItem if newMenuItem.attributes.contains(.available) { newMenuItem.attributes.remove(.available) } else { newMenuItem.attributes.insert(.available) } soupMenuManager.replaceMenuItem(currentMenuItem, with: newMenuItem) reloadData() } } ``` ## OrderDetailViewController.swift ```swift /* Abstract: This class shows soup order details. When configured with a 'newOrder' purpose, the view controller collects details of a new order. When configured with a 'historicalOrder' purpose, the view controller displays details of a previously placed order. */ import UIKit import SoupKit import os.log import IntentsUI class OrderDetailViewController: UIViewController { enum Purpose { case newOrder, historicalOrder } var order: Order! { didSet { configureDataSource() } } var purpose: Purpose = .newOrder { didSet { navigationItem.rightBarButtonItem = (purpose == .newOrder) ? orderButton : nil } } private var collectionView: UICollectionView! = nil private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! = nil private var titleCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, Item>! private var sectionHeaderCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, Item>! private var priceCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, Item>! private var quantityCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, Item>! private var choiceCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, Item>! private var siriCellRegistration: UICollectionView.CellRegistration<AddToSiriCollectionViewCell, Item>! private var orderButton: UIBarButtonItem! override func awakeFromNib() { super.awakeFromNib() orderButton = navigationItem.rightBarButtonItem configureCollectionView() } } // MARK: - IntentsUI Delegates extension OrderDetailViewController: INUIAddVoiceShortcutButtonDelegate { func present(_ addVoiceShortcutViewController: INUIAddVoiceShortcutViewController, for addVoiceShortcutButton: INUIAddVoiceShortcutButton) { addVoiceShortcutViewController.delegate = self present(addVoiceShortcutViewController, animated: true, completion: nil) } /// - Tag: edit_phrase func present(_ editVoiceShortcutViewController: INUIEditVoiceShortcutViewController, for addVoiceShortcutButton: INUIAddVoiceShortcutButton) { editVoiceShortcutViewController.delegate = self present(editVoiceShortcutViewController, animated: true, completion: nil) } } extension OrderDetailViewController: INUIAddVoiceShortcutViewControllerDelegate { func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) { if let error = error as NSError? { Logger().debug("Error adding voice shortcut (error)") } controller.dismiss(animated: true, completion: nil) } func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } } extension OrderDetailViewController: INUIEditVoiceShortcutViewControllerDelegate { func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) { if let error = error as NSError? { Logger().debug("Error editing voice shortcut (error)") } controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) { controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } } // MARK: - Collection View Setup extension OrderDetailViewController: UICollectionViewDelegate { private func configureCollectionView() { let layout = createCollectionViewLayout() let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) view.addSubview(collectionView) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = .systemGroupedBackground collectionView.delegate = self self.collectionView = collectionView } private func createCollectionViewLayout() -> UICollectionViewLayout { let sectionProvider = { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in let section = self.visibleSections(for: self.purpose)[sectionIndex] var configuration: UICollectionLayoutListConfiguration if section == .soupDescription || section == .siri { configuration = UICollectionLayoutListConfiguration(appearance: .sidebar) } else { configuration = UICollectionLayoutListConfiguration(appearance: .grouped) configuration.headerMode = .firstItemInSection } configuration.backgroundColor = .systemGroupedBackground let sectionLayout = NSCollectionLayoutSection.list(using: configuration, layoutEnvironment: layoutEnvironment) return sectionLayout } return UICollectionViewCompositionalLayout(sectionProvider: sectionProvider) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) guard purpose == .newOrder else { return } if let item = dataSource.itemIdentifier(for: indexPath), item.type == .choice, let rawValue = item.rawValue, let rawString = rawValue as? String, let topping = Order.MenuItemTopping(rawValue: rawString) { if order.menuItemToppings.contains(topping) { order.menuItemToppings.remove(topping) } else { order.menuItemToppings.insert(topping) } updateSnapshot() } } } // MARK: - Collection View Data Mangement extension OrderDetailViewController { private enum Section: String { case soupDescription case price = "Price" case quantity = "Quantity" case toppings = "Toppings" case total = "Total" case siri } private enum CellType { case titleBanner case sectionHeader case price // Unit price and total price case quantity // Number of units case choice // Toppings case siri } private class Item: Hashable, Identifiable { let type: CellType let text: String? let rawValue: AnyHashable? let enabled: Bool init(type: CellType, text: String? = nil, rawValue: AnyHashable? = nil, enabled: Bool = false) { self.type = type self.text = text self.rawValue = rawValue self.enabled = enabled } func hash(into hasher: inout Hasher) { hasher.combine(id) } static func == (lhs: Item, rhs: Item) -> Bool { return lhs.id == rhs.id } } private func visibleSections(for purpose: OrderDetailViewController.Purpose) -> [Section] { if purpose == .newOrder { return [.soupDescription, .price, .quantity, .toppings, .total] } else { return [.soupDescription, .quantity, .toppings, .total, .siri] } } private func items(for order: Order, in section: Section) -> [Item] { switch section { case .soupDescription: return [Item(type: .titleBanner, text: order.menuItem.localizedName(), rawValue: order.menuItem)] case .price: return [Item(type: .sectionHeader, text: section.rawValue), Item(type: .price, text: NumberFormatter.currencyFormatter.string(from: (order.menuItem.price as NSDecimalNumber)))] case .total: return [Item(type: .sectionHeader, text: section.rawValue), Item(type: .price, text: NumberFormatter.currencyFormatter.string(from: (order.total as NSDecimalNumber)))] case .quantity: return [Item(type: .sectionHeader, text: section.rawValue), Item(type: .quantity, text: "(order.quantity)", rawValue: order.quantity)] case .toppings: var toppings = Order.MenuItemTopping.allCases.map { (topping) -> Item in Item(type: .choice, text: topping.localizedName(), rawValue: topping.rawValue, enabled: order.menuItemToppings.contains(topping)) } let sectionHeader = Item(type: .sectionHeader, text: section.rawValue) toppings.insert(sectionHeader, at: 0) return toppings case .siri: return [Item(type: .siri)] } } private func configureDataSource() { prepareCellRegistrations() dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, item: Item) -> UICollectionViewCell? in switch item.type { case .titleBanner: return collectionView.dequeueConfiguredReusableCell(using: self.titleCellRegistration, for: indexPath, item: item) case .choice: return collectionView.dequeueConfiguredReusableCell(using: self.choiceCellRegistration, for: indexPath, item: item) case .price: return collectionView.dequeueConfiguredReusableCell(using: self.priceCellRegistration, for: indexPath, item: item) case .quantity: return collectionView.dequeueConfiguredReusableCell(using: self.quantityCellRegistration, for: indexPath, item: item) case .siri: return collectionView.dequeueConfiguredReusableCell(using: self.siriCellRegistration, for: indexPath, item: item) case .sectionHeader: return collectionView.dequeueConfiguredReusableCell(using: self.sectionHeaderCellRegistration, for: indexPath, item: item) } } updateSnapshot() } private func prepareCellRegistrations() { titleCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in var content = cell.defaultContentConfiguration() content.text = item.text content.textProperties.font = UIFont.preferredFont(forTextStyle: .body) if let menuItem = item.rawValue as? MenuItem { content.image = UIImage(named: menuItem.iconImageName) content.imageProperties.cornerRadius = 8 cell.contentConfiguration = content cell.contentView.backgroundColor = .systemGroupedBackground } } sectionHeaderCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in var content = cell.defaultContentConfiguration() content.text = item.text content.textProperties.font = UIFont.preferredFont(forTextStyle: .footnote) cell.contentConfiguration = content } priceCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in var contentConfiguration = UIListContentConfiguration.cell() contentConfiguration.text = item.text cell.contentConfiguration = contentConfiguration } quantityCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in var contentConfiguration = UIListContentConfiguration.cell() contentConfiguration.text = item.text cell.contentConfiguration = contentConfiguration let hidden = self.purpose == .historicalOrder let stepper = self.createStepper(value: item.rawValue as? Double ?? 1) var accessory = UICellAccessory.CustomViewConfiguration(customView: stepper, placement: .trailing(), isHidden: hidden) accessory.reservedLayoutWidth = .actual cell.accessories = [UICellAccessory.customView(configuration: accessory)] } choiceCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in var contentConfiguration = UIListContentConfiguration.cell() contentConfiguration.text = item.text cell.contentConfiguration = contentConfiguration cell.accessories = item.enabled ? [.checkmark()] : [] } siriCellRegistration = UICollectionView.CellRegistration<AddToSiriCollectionViewCell, Item> { cell, indexPath, item in var contentConfiguration = AddToSiriCellContentConfiguration() contentConfiguration.intent = self.order.intent contentConfiguration.delegate = self cell.contentConfiguration = contentConfiguration } } private func createStepper(value: Double) -> UIStepper { let stepper = UIStepper() stepper.value = value stepper.minimumValue = 1 stepper.maximumValue = 100 stepper.stepValue = 1 stepper.addTarget(self, action: #selector(OrderDetailViewController.quantityStepperDidChange(_:)), for: .valueChanged) return stepper } private func updateSnapshot() { var snapshot = NSDiffableDataSourceSnapshot<Section, Item>() let sections = order != nil ? visibleSections(for: purpose) : [] snapshot.appendSections(sections) for section in sections { snapshot.appendItems(items(for: order, in: section), toSection: section) } dataSource.apply(snapshot, animatingDifferences: false, completion: nil) } @objc private func quantityStepperDidChange(_ sender: UIStepper) { order.quantity = Int(sender.value) updateSnapshot() } } ``` ## OrderHistoryViewController.swift ```swift /* Abstract: This class displays a list of previously placed orders. */ import UIKit import SoupKit class OrderHistoryViewController: UIViewController { private let soupMenuManager = SoupMenuManager() private let soupOrderManager = SoupOrderDataManager() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear configureCollectionView() configureDataSource() } // MARK: - Navigation private enum SegueIdentifiers: String { case soupMenu = "Soup Menu" case configureMenu = "Configure Menu" } // This IBAction exposes a unwind segue in the storyboard. @IBAction private func unwindToOrderHistory(segue: UIStoryboardSegue) {} @IBAction private func placeNewOrder(segue: UIStoryboardSegue) { if let source = segue.source as? OrderDetailViewController { soupOrderManager.placeOrder(order: source.order) } } private func displayOrderDetail(_ order: Order) { guard let detailVC = splitViewController?.viewController(for: .secondary) as? OrderDetailViewController else { return } detailVC.order = order splitViewController?.show(.secondary) } @IBAction private func clearHistory(_ sender: Any) { soupOrderManager.clearOrderHistory() guard let detailVC = splitViewController?.viewController(for: .secondary) as? OrderDetailViewController else { return } detailVC.order = nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueIdentifiers.configureMenu.rawValue { if let navController = segue.destination as? UINavigationController, let configureMenuTableViewController = navController.viewControllers.first as? ConfigureMenuTableViewController { configureMenuTableViewController.soupMenuManager = soupMenuManager configureMenuTableViewController.soupOrderDataManager = soupOrderManager } } else if segue.identifier == SegueIdentifiers.soupMenu.rawValue { if let navController = segue.destination as? UINavigationController, let menuController = navController.viewControllers.first as? SoupMenuViewController { if let activity = sender as? NSUserActivity, activity.activityType == NSStringFromClass(OrderSoupIntent.self) { menuController.userActivity = activity } else { menuController.userActivity = NSUserActivity.viewMenuActivity } } } } /// - Tag: continue_nsua /// The system calls this method when continuing a user activity through the restoration handler /// in `UISceneDelegate scene(_:continue:)`. override func restoreUserActivityState(_ activity: NSUserActivity) { super.restoreUserActivityState(activity) if activity.activityType == NSUserActivity.viewMenuActivityType { // This order came from the "View Menu" shortcut that is based on NSUserActivity. prepareForUserActivityRestoration() { self.performSegue(withIdentifier: SegueIdentifiers.soupMenu.rawValue, sender: nil) } } else if activity.activityType == NSStringFromClass(OrderSoupIntent.self) { // This order started as a shortcut, but isn't complete because the user tapped on the SoupChef Intent UI // during the order process. Let the user finish customizing their order. prepareForUserActivityRestoration() { self.performSegue(withIdentifier: SegueIdentifiers.soupMenu.rawValue, sender: activity) } } else if activity.activityType == NSUserActivity.orderCompleteActivityType, let orderID = activity.userInfo?[NSUserActivity.ActivityKeys.orderID.rawValue] as? UUID, let order = soupOrderManager.order(matching: orderID) { // This order was just created outside of the main app through an intent. // Display the order in the order history. prepareForUserActivityRestoration() { self.displayOrderDetail(order) } } } /// Ensures this view controller is visible and not presenting anything. private func prepareForUserActivityRestoration(completion: @escaping () -> Void) { splitViewController?.show(.primary) if presentedViewController != nil { dismiss(animated: false, completion: { completion() }) } else { completion() } } // MARK: - Collection View Setup private var collectionView: UICollectionView! = nil func configureCollectionView() { let listConfiguration = UICollectionLayoutListConfiguration(appearance: .plain) let layout = UICollectionViewCompositionalLayout.list(using: listConfiguration) let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) view.addSubview(collectionView) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.collectionView = collectionView collectionView.delegate = self } // MARK: - Collection View Data Mangement private var ordersChangedObserver: NSObjectProtocol? private var dataSource: UICollectionViewDiffableDataSource<Section, Order>! = nil private enum Section { case history } private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .long return formatter }() func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Order> { cell, indexPath, order in var contentConfiguration = UIListContentConfiguration.subtitleCell() contentConfiguration.text = "(order.quantity) (order.menuItem.localizedName())" contentConfiguration.secondaryText = self.dateFormatter.string(from: order.date) contentConfiguration.image = UIImage(named: order.menuItem.iconImageName) contentConfiguration.imageProperties.cornerRadius = 8 cell.contentConfiguration = contentConfiguration cell.accessories = [.disclosureIndicator()] } dataSource = UICollectionViewDiffableDataSource<Section, Order>(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, item: Order) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item) } var snapshot = NSDiffableDataSourceSectionSnapshot<Order>() snapshot.append(soupOrderManager.orderHistory) dataSource.apply(snapshot, to: .history, animatingDifferences: false) ordersChangedObserver = NotificationCenter.default.addObserver(forName: dataChangedNotificationKey, object: soupOrderManager, queue: OperationQueue.main) { [unowned self] (notification) in var snapshot = NSDiffableDataSourceSectionSnapshot<Order>() snapshot.append(self.soupOrderManager.orderHistory) self.dataSource.apply(snapshot, to: .history, animatingDifferences: true) } } } extension OrderHistoryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) displayOrderDetail(soupOrderManager.orderHistory[indexPath.item]) } } ``` ## SceneDelegate.swift ```swift /* Abstract: The application scene delegate. */ import UIKit import SoupKit import os.log class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = scene as? UIWindowScene else { return } #if targetEnvironment(macCatalyst) if let titlebar = windowScene.titlebar { titlebar.titleVisibility = .hidden titlebar.toolbar = nil } #endif if let splitViewController = window?.rootViewController as? UISplitViewController { splitViewController.primaryBackgroundStyle = .sidebar splitViewController.delegate = self if let detailController = splitViewController.viewController(for: .secondary) as? OrderDetailViewController { detailController.purpose = .historicalOrder } } } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard userActivity.activityType == NSStringFromClass(OrderSoupIntent.self) || userActivity.activityType == NSUserActivity.viewMenuActivityType || userActivity.activityType == NSUserActivity.orderCompleteActivityType else { Logger().debug("Can't continue unknown NSUserActivity type (userActivity.activityType)") return } // Pass the user activity to a view controller that is able to continue the specific activity. if let splitViewController = window?.rootViewController as? UISplitViewController, let navController = splitViewController.viewController(for: .primary) as? UINavigationController, let orderHistoryController = navController.topViewController as? OrderHistoryViewController { orderHistoryController.restoreUserActivityState(userActivity) } } } extension SceneDelegate: UISplitViewControllerDelegate { func splitViewController(_ svc: UISplitViewController, topColumnForCollapsingToProposedTopColumn proposedTopColumn: UISplitViewController.Column) -> UISplitViewController.Column { // Display the primary column when transitioning to a compact size class. return .primary } } ``` ## SoupMenuViewController.swift ```swift /* Abstract: This view controller displays the list of active menu items to the user. */ import UIKit import SoupKit import os.log class SoupMenuViewController: UIViewController { private var menuItems: [MenuItem] = SoupMenuManager().findItems(exactlyMatching: [.available, .regularItem], [.available, .dailySpecialItem]) override func viewDidLoad() { super.viewDidLoad() configureCollectionView() configureDataSource() } // MARK: - Navigation private enum SegueIdentifiers: String { case newOrder = "Show New Order Detail Segue" } override var userActivity: NSUserActivity? { didSet { if userActivity?.activityType == NSStringFromClass(OrderSoupIntent.self) { performSegue(withIdentifier: SegueIdentifiers.newOrder.rawValue, sender: userActivity) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueIdentifiers.newOrder.rawValue { guard let destination = segue.destination as? OrderDetailViewController else { return } var order: Order? if let sender = sender as? MenuItem { order = Order(quantity: 1, menuItem: sender, menuItemToppings: []) } else if let activity = sender as? NSUserActivity, let orderIntent = activity.interaction?.intent as? OrderSoupIntent { order = Order(from: orderIntent) } if let order = order { destination.order = order } } } // MARK: - Collection View Setup private enum Section { case menu } private var dataSource: UICollectionViewDiffableDataSource<Section, MenuItem>! = nil private var collectionView: UICollectionView! = nil func configureCollectionView() { let listConfiguration = UICollectionLayoutListConfiguration(appearance: .plain) let layout = UICollectionViewCompositionalLayout.list(using: listConfiguration) let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) view.addSubview(collectionView) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.collectionView = collectionView collectionView.delegate = self } func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, MenuItem> { cell, indexPath, menuItem in var contentConfiguration = UIListContentConfiguration.cell() contentConfiguration.text = menuItem.localizedName() contentConfiguration.image = UIImage(named: menuItem.iconImageName) contentConfiguration.imageProperties.cornerRadius = 8 cell.contentConfiguration = contentConfiguration cell.accessories = [.disclosureIndicator()] } dataSource = UICollectionViewDiffableDataSource<Section, MenuItem>(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, item: MenuItem) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item) } var snapshot = NSDiffableDataSourceSectionSnapshot<MenuItem>() snapshot.append(menuItems) dataSource.apply(snapshot, to: .menu, animatingDifferences: false) } } extension SoupMenuViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let menuItem = menuItems[indexPath.item] performSegue(withIdentifier: SegueIdentifiers.newOrder.rawValue, sender: menuItem) collectionView.deselectItem(at: indexPath, animated: true) } } ``` ## IntentViewController.swift ```swift /* Abstract: Create a custom user interface that shows in the Siri interface, as well by touch and holding on a shortcut on the Lock screen or in Spotlight. */ import IntentsUI import SoupKit class IntentViewController: UIViewController, INUIHostedViewControlling { /// Prepare your view controller for displaying the details of the soup order. func configureView(for parameters: Set<INParameter>, of interaction: INInteraction, interactiveBehavior: INUIInteractiveBehavior, context: INUIHostedViewContext, completion: @escaping (Bool, Set<INParameter>, CGSize) -> Void) { guard let intent = interaction.intent as? OrderSoupIntent else { completion(false, Set(), .zero) return } /* Different UIs can be displayed depending if the intent is in the confirmation phase or the handle phase. This example uses view controller containment to manage each of the different views via a dedicated view controller. */ if interaction.intentHandlingStatus == .ready { let viewController = InvoiceViewController(for: intent) attachChild(viewController) completion(true, parameters, desiredSize) } else if interaction.intentHandlingStatus == .success { if let response = interaction.intentResponse as? OrderSoupIntentResponse { let viewController = OrderConfirmedViewController(for: intent, with: response) attachChild(viewController) completion(true, parameters, desiredSize) } } completion(false, parameters, .zero) } private var desiredSize: CGSize { let width = self.extensionContext?.hostedViewMaximumAllowedSize.width ?? 320 return CGSize(width: width, height: 120) } private func attachChild(_ viewController: UIViewController) { addChild(viewController) if let subview = viewController.view { view.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false // Set the child controller's view to be the exact same size as the parent controller's view. subview.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true subview.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true subview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true subview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } viewController.didMove(toParent: self) } } ``` ## InvoiceViewController.swift ```swift /* Abstract: A view that lists the order invoice. */ import UIKit import SoupKit class InvoiceViewController: UIViewController { private let intent: OrderSoupIntent @IBOutlet weak var invoiceView: InvoiceView! init(for soupIntent: OrderSoupIntent) { intent = soupIntent super.init(nibName: "InvoiceView", bundle: Bundle(for: InvoiceViewController.self)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() if let order = Order(from: intent) { invoiceView.itemNameLabel.text = order.menuItem.localizedName() invoiceView.imageView.applyRoundedCorners() invoiceView.totalPriceLabel.text = order.localizedCurrencyValue invoiceView.unitPriceLabel.text = "(order.quantity) @ (order.menuItem.localizedCurrencyValue)" invoiceView.imageView.image = UIImage(named: order.menuItem.iconImageName) switch order.orderType { case .unknown: invoiceView.infoLabel.text = "" case .delivery: if let deliveryLocation = order.deliveryLocation, let name = deliveryLocation.name { invoiceView.infoLabel.text = "Deliver to (name)" } case .pickup: if let storeLocation = order.storeLocation, let name = storeLocation.name { invoiceView.infoLabel.text = "Pickup from (name)" } } let flattenedToppings = order.menuItemToppings.map { (topping) -> String in return topping.rawValue }.joined(separator: ", ") invoiceView.toppingsLabel.text = flattenedToppings } } } class InvoiceView: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var itemNameLabel: UILabel! @IBOutlet weak var unitPriceLabel: UILabel! @IBOutlet weak var toppingsLabel: UILabel! @IBOutlet weak var totalPriceLabel: UILabel! @IBOutlet weak var infoLabel: UILabel! } ``` ## OrderConfirmedViewController.swift ```swift /* Abstract: A view controller that confirms an order was placed. */ import UIKit import Intents import SoupKit class OrderConfirmedViewController: UIViewController { private let intent: OrderSoupIntent private let intentResponse: OrderSoupIntentResponse @IBOutlet var confirmationView: OrderConfirmedView! init(for soupIntent: OrderSoupIntent, with response: OrderSoupIntentResponse) { intent = soupIntent intentResponse = response super.init(nibName: "OrderConfirmedView", bundle: Bundle(for: OrderConfirmedViewController.self)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() confirmationView = view as? OrderConfirmedView if let order = Order(from: intent) { confirmationView.itemNameLabel.text = order.menuItem.localizedName() confirmationView.imageView.applyRoundedCorners() if let orderDetails = intentResponse.orderDetails { confirmationView.timeLabel.text = orderDetails.displayString } confirmationView.imageView.image = UIImage(named: order.menuItem.iconImageName) switch order.orderType { case .unknown: confirmationView.infoLabel.text = "" case .delivery: if let deliveryLocation = order.deliveryLocation, let name = deliveryLocation.name { confirmationView.infoLabel.text = "Deliver to (name)" } case .pickup: if let storeLocation = order.storeLocation, let name = storeLocation.name { confirmationView.infoLabel.text = "Pickup from (name)" } } } } } class OrderConfirmedView: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var itemNameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var infoLabel: UILabel! } ``` ## IntentHandler.swift ```swift /* Abstract: IntentHandler that vends instances of `OrderSoupIntentHandler` for iOS. */ import Intents import SoupKit class IntentHandler: INExtension { override func handler(for intent: INIntent) -> Any { guard intent is OrderSoupIntent else { fatalError("Unhandled intent type: (intent)") } return OrderSoupIntentHandler() } } ``` ## IntentHandler.swift ```swift /* Abstract: IntentHandler that vends instances of `OrderSoupIntentHandler` for watchOS. */ import Intents import SoupKit class IntentHandler: INExtension { override func handler(for intent: INIntent) -> Any { guard intent is OrderSoupIntent else { fatalError("Unhandled intent type: (intent)") } return OrderSoupIntentHandler() } } ``` ## ExtensionDelegate.swift ```swift /* Abstract: The watch extension delegate. */ import WatchKit import SoupKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func handle(_ userActivity: NSUserActivity) { guard let rootController = WKExtension.shared().rootInterfaceController else { return } rootController.popToRootController() if userActivity.activityType == NSStringFromClass(OrderSoupIntent.self), let intent = userActivity.interaction?.intent as? OrderSoupIntent { // This order can come from the "Chicken Noodle Soup" special menu item that is // donated to the system as a relevant shortcut on the Siri watch face. let order = Order(from: intent) rootController.pushController(withName: MenuInterfaceController.controllerIdentifier, context: order) } else if userActivity.activityType == NSUserActivity.viewMenuActivityType { rootController.pushController(withName: MenuInterfaceController.controllerIdentifier, context: nil) } else if userActivity.activityType == NSUserActivity.orderCompleteActivityType, (userActivity.userInfo?[NSUserActivity.ActivityKeys.orderID.rawValue] as? UUID) != nil { // Order complete, go to the order history interface. rootController.pushController(withName: HistoryInterfaceController.controllerIdentifier, context: nil) } } } ``` ## HistoryInterfaceController.swift ```swift /* Abstract: A `WKInterfaceController` that displays a list of previously placed orders. */ import WatchKit import Foundation import SoupKit import os.log class HistoryInterfaceController: WKInterfaceController { static let controllerIdentifier = "history" let tableData = SoupOrderDataManager().orderHistory @IBOutlet var interfaceTable: WKInterfaceTable! lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short return formatter }() override func awake(withContext context: Any?) { super.awake(withContext: context) loadTableRows() } func loadTableRows() { guard !tableData.isEmpty else { return } interfaceTable.setNumberOfRows(self.tableData.count, withRowType: "history") // Create rows for all of the items in the menu. for rowIndex in 0 ... tableData.count - 1 { guard let elementRow = interfaceTable.rowController(at: rowIndex) as? HistoryItemRowController else { Logger().debug("Unexpected row controller") return } let rowData = tableData[rowIndex] let dateString = dateFormatter.string(from: rowData.date) elementRow.itemOrdered.setText(rowData.menuItem.localizedName()) elementRow.orderTime.setText(dateString) } } } class HistoryItemRowController: NSObject { @IBOutlet var itemOrdered: WKInterfaceLabel! @IBOutlet var orderTime: WKInterfaceLabel! } ``` ## MenuInterfaceController.swift ```swift /* Abstract: A `WKInterfaceController` that displays a menu. */ import WatchKit import Foundation import SoupKit import os.log /// Displays a table of menu items that can be ordered from the watch. class MenuInterfaceController: WKInterfaceController { static let controllerIdentifier = "menu" private static let confirmOrderSegue = "confirmOrderSegue" let tableData = SoupMenuManager().findItems(exactlyMatching: [.available, .regularItem], [.available, .dailySpecialItem]) @IBOutlet var interfaceTable: WKInterfaceTable! override func awake(withContext context: Any?) { super.awake(withContext: context) if let order = context as? Order { presentController(withName: OrderConfirmedInterfaceController.controllerIdentifier, context: order) } loadTableRows() } override func didAppear() { // Inform the system of this activity, as it is one that a shortcut makes easy to repeat. let userActivity = NSUserActivity.viewMenuActivity update(userActivity) } private func loadTableRows() { guard !tableData.isEmpty else { return } interfaceTable.setNumberOfRows(self.tableData.count, withRowType: "menu") // Create rows for all of the items in the menu. for rowIndex in 0 ... tableData.count - 1 { guard let elementRow = interfaceTable.rowController(at: rowIndex) as? MenuItemRowController else { Logger().debug("Unexpected row controller") return } let rowData = tableData[rowIndex] elementRow.soupName.setText(rowData.localizedName()) elementRow.soupImage.setImage(UIImage(named: rowData.iconImageName)) } } override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? { guard segueIdentifier == MenuInterfaceController.confirmOrderSegue else { return nil } let menuItem = tableData[rowIndex] let newOrder = Order(quantity: 1, menuItem: menuItem, menuItemToppings: []) return newOrder } } /// Defines the layout of a menu item table cell on the watch. class MenuItemRowController: NSObject { @IBOutlet var soupImage: WKInterfaceImage! @IBOutlet var soupName: WKInterfaceLabel! } ``` ## OrderConfirmedInterfaceController.swift ```swift /* Abstract: A `WKInterfaceController` that displays confirmation an order was placed successfully. */ import WatchKit import Foundation import SoupKit /// Displays confirmation after placing an order. class OrderConfirmedInterfaceController: WKInterfaceController { static let controllerIdentifier = "orderComplete" @IBOutlet var image: WKInterfaceImage! override func awake(withContext context: Any?) { guard let order = context as? Order else { return } image.setImage(UIImage(named: order.menuItem.iconImageName)) /* Placing an order on the watch uses the same code as in the iOS app. This means the order will be turned into an INInteraction, and donated to the system. The interaction object is marked eligible for prediction, and may show up on the Siri Watch Face at appropiate times in the future. */ let orderManager = SoupOrderDataManager() orderManager.placeOrder(order: order) } @IBAction func dismissConfirmation() { dismiss() } } ``` ## AppDelegate.swift ```swift /* Abstract: The application delegate class. */ import UIKit extension UIApplication { /** The activityTypes are included in your Info.plist file under the `NSUserActivityTypes` array. More info: https://developer.apple.com/documentation/foundation/nsuseractivity */ static var userActivitiyTypes: [String]? { return Bundle.main.object(forInfoDictionaryKey: "NSUserActivityTypes") as? [String] } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } } ``` ## DetailViewController.swift ```swift /* Abstract: The detail view controller navigated to from our main and results table. */ import UIKit class DetailViewController: UIViewController { // The suffix portion of the user activity type for this view controller. static let activitySuffix = "detailRestored" // The user activity userInfo key to the archived product data. private static let restoredProductKey = "restoredProduct" // MARK: - Properties var product: Product! @IBOutlet private weak var yearLabel: UILabel! @IBOutlet private weak var priceLabel: UILabel! // Used by our scene delegate to return an instance of this class from our storyboard. static func loadFromStoryboard() -> DetailViewController? { let storyboard = UIStoryboard(name: "Main", bundle: .main) return storyboard.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController } class func detailViewControllerForProduct(_ product: Product) -> UIViewController { let detailViewController = loadFromStoryboard() detailViewController!.product = product return detailViewController! } /** Returns the NSUserActivity string for this view controller. The activity string comes from the Info.plist that ends with the "activitySuffix" string. */ func viewControllerActivityType() -> String { var returnActivityType = "" if let definedAppUserActivities = UIApplication.userActivitiyTypes { for activityType in definedAppUserActivities { if activityType.hasSuffix(DetailViewController.activitySuffix) { returnActivityType = activityType break } } } return returnActivityType } // MARK: - View Life Cycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) assert(product != nil, "Error: a product must be assigned.") // Obtain the userActivity representation of the product. userActivity = productUserActivity(activityType: viewControllerActivityType()) // Set the title's color to match the product color. let color = ResultsTableController.suggestedColor(fromIndex: product.color) let textAttributes = [NSAttributedString.Key.foregroundColor: color] navigationController?.navigationBar.titleTextAttributes = textAttributes title = product.title yearLabel.text = product.formattedDate() priceLabel.text = product.formattedPrice() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Reset the title's color to normal label color. let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.label] navigationController?.navigationBar.titleTextAttributes = textAttributes // No longer interested in the current activity. view.window?.windowScene?.userActivity = nil } } // MARK: - State Restoration extension DetailViewController { // MARK: - UIUserActivityRestoring /** Returns the activity object you can use to restore the previous contents of your scene's interface. Before disconnecting a scene, the system asks your delegate for an NSUserActivity object containing state information for that scene. If you provide that object, the system puts a copy of it in this property. Use the information in the user activity object to restore the scene to its previous state. */ override func updateUserActivityState(_ activity: NSUserActivity) { super.updateUserActivityState(activity) if let productDataToArchive = activityUserInfoEntry() { userActivity!.addUserInfoEntries(from: productDataToArchive) } } /** Restores the state needed to continue the given user activity. Subclasses override this method to restore the responder�s state with the given user activity. The override should use the state data contained in the userInfo dictionary of the given user activity to restore the object. */ override func restoreUserActivityState(_ activity: NSUserActivity) { product = productFromUserActivity(activity) super.restoreUserActivityState(activity) } // MARK: - NSUserActivity Support func activityUserInfoEntry() -> [String: Any]? { let encoder = JSONEncoder() do { let data = try encoder.encode(product.self) return [DetailViewController.restoredProductKey: data as Any] } catch { Swift.debugPrint("Error encoding product: (error)") } return nil } // Return the NSUserActivity representation of the product. func productUserActivity(activityType: String) -> NSUserActivity { // Setup the user activity as the Product to pass to the app which product we want to open. /** Create an NSUserActivity from the product. Note: The activityType string below must be included in your Info.plist file under the `NSUserActivityTypes` array. More info: https://developer.apple.com/documentation/foundation/nsuseractivity */ let userActivity = NSUserActivity(activityType: activityType) userActivity.title = title // Target content identifier is a structured way to represent data in your model. // Set a string that identifies the content of this NSUserActivity. // Here the userActivity's targetContentIdentifier will simply be the product's title. userActivity.targetContentIdentifier = title if let productDataToArchive = activityUserInfoEntry() { userActivity.addUserInfoEntries(from: productDataToArchive) } return userActivity } // Return a Product instance from a user activity, used by "restoreUserActivityState". func productFromUserActivity(_ activity: NSUserActivity) -> Product? { var product: Product! if let userInfo = activity.userInfo { if let productData = (userInfo[DetailViewController.restoredProductKey]) as? Data { let decoder = JSONDecoder() if let savedProduct = try? decoder.decode(Product.self, from: productData) as Product { product = savedProduct } } } return product } } ``` ## MainTableViewController+ResultsUpdate.swift ```swift /* Abstract: MainTableViewController adoption of UISearchResultsUpdating. */ import UIKit extension MainTableViewController: UISearchResultsUpdating { // Called when the search bar's text has changed or when the search bar becomes first responder. func updateSearchResults(for searchController: UISearchController) { // Update the resultsController's filtered items based on the search terms and suggested search token. let searchResults = products // Strip out all the leading and trailing spaces. let whitespaceCharacterSet = CharacterSet.whitespaces let strippedString = searchController.searchBar.text!.trimmingCharacters(in: whitespaceCharacterSet).lowercased() let searchItems = strippedString.components(separatedBy: " ") as [String] // Filter results down by title, yearIntroduced and introPrice. var filtered = searchResults var curTerm = searchItems[0] var idx = 0 while curTerm != "" { filtered = filtered.filter { $0.title.lowercased().contains(curTerm) || $0.yearIntroduced.description.lowercased().contains(curTerm) || $0.introPrice.description.lowercased().contains(curTerm) } idx += 1 curTerm = (idx < searchItems.count) ? searchItems[idx] : "" } // Filter further down for the right colored flowers. if !searchController.searchBar.searchTextField.tokens.isEmpty { // We only support one search token. let searchToken = searchController.searchBar.searchTextField.tokens[0] if let searchTokenValue = searchToken.representedObject as? NSNumber { filtered = filtered.filter { $0.color == searchTokenValue.intValue } } } // Apply the filtered results to the search results table. if let resultsController = searchController.searchResultsController as? ResultsTableController { resultsController.filteredProducts = filtered resultsController.tableView.reloadData() } } } ``` ## MainTableViewController+SuggestedSearch.swift ```swift /* Abstract: MainTableViewController SuggestedSearch protocol. */ import UIKit extension MainTableViewController: SuggestedSearch { // ResultsTableController selected a suggested search, so we need to apply the search token. func didSelectSuggestedSearch(token: UISearchToken) { if let searchField = navigationItem.searchController?.searchBar.searchTextField { searchField.insertToken(token, at: 0) // Hide the suggested searches now that we have a token. resultsTableController.showSuggestedSearches = false // Update the search query with the newly inserted token. updateSearchResults(for: searchController) } } // ResultsTableController selected a product, so navigate to that product. func didSelectProduct(product: Product) { // Set up the detail view controller to show. let detailViewController = DetailViewController.detailViewControllerForProduct(product) navigationController?.pushViewController(detailViewController, animated: true) } } ``` ## MainTableViewController.swift ```swift /* Abstract: The application's primary table view controller showing a list of products. */ import UIKit class MainTableViewController: UITableViewController { // MARK: - Constants // The suffix portion of the user activity type for this view controller. static let activitySuffix = "mainRestored" /// State restoration values. private enum RestorationKeys: String { case searchControllerIsActive case searchBarText case searchBarIsFirstResponder case searchBarToken } // MARK: - Properties /// Search controller to help us with filtering. var searchController: UISearchController! /// The search results table view. var resultsTableController: ResultsTableController! /// Data model for the table view. var products = [Product]() /** Returns the NSUserActivity string for this view controller. The activity string comes from the Info.plist that ends with the "activitySuffix" string for this view controller. */ class func viewControllerActivityType() -> String { var returnActivityType = "" if let definedAppUserActivities = UIApplication.userActivitiyTypes { for activityType in definedAppUserActivities { if activityType.hasSuffix(activitySuffix) { returnActivityType = activityType break } } } return returnActivityType } // MARK: - Data Model struct ProductKind { static let Ginger = "Ginger" static let Gladiolus = "Gladiolus" static let Orchid = "Orchid" static let Poinsettia = "Poinsettia" static let RedRose = "Rose" static let GreenRose = "Rose" static let Tulip = "Tulip" static let RedCarnation = "Carnation" static let GreenCarnation = "Carnation" static let BlueCarnation = "Carnation" static let Sunflower = "Sunflower" static let Gardenia = "Gardenia" static let RedGardenia = "Gardenia" static let BlueGardenia = "Gardenia" } private func setupDataModel() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy" products = [ Product(title: ProductKind.Ginger, yearIntroduced: dateFormatter.date(from: "2007")!, introPrice: 49.98, color: .undedefined), Product(title: ProductKind.Gladiolus, yearIntroduced: dateFormatter.date(from: "2001")!, introPrice: 51.99, color: .undedefined), Product(title: ProductKind.Orchid, yearIntroduced: dateFormatter.date(from: "2007")!, introPrice: 16.99, color: .undedefined), Product(title: ProductKind.Poinsettia, yearIntroduced: dateFormatter.date(from: "2010")!, introPrice: 31.99, color: .undedefined), Product(title: ProductKind.RedRose, yearIntroduced: dateFormatter.date(from: "2010")!, introPrice: 24.99, color: .red), Product(title: ProductKind.GreenRose, yearIntroduced: dateFormatter.date(from: "2013")!, introPrice: 24.99, color: .green), Product(title: ProductKind.Tulip, yearIntroduced: dateFormatter.date(from: "1997")!, introPrice: 39.99, color: .undedefined), Product(title: ProductKind.RedCarnation, yearIntroduced: dateFormatter.date(from: "2006")!, introPrice: 23.99, color: .red), Product(title: ProductKind.GreenCarnation, yearIntroduced: dateFormatter.date(from: "2009")!, introPrice: 23.99, color: .green), Product(title: ProductKind.BlueCarnation, yearIntroduced: dateFormatter.date(from: "2009")!, introPrice: 24.99, color: .blue), Product(title: ProductKind.Sunflower, yearIntroduced: dateFormatter.date(from: "2008")!, introPrice: 25.00, color: .undedefined), Product(title: ProductKind.Gardenia, yearIntroduced: dateFormatter.date(from: "2006")!, introPrice: 25.00, color: .undedefined), Product(title: ProductKind.RedGardenia, yearIntroduced: dateFormatter.date(from: "2008")!, introPrice: 25.00, color: .red), Product(title: ProductKind.BlueGardenia, yearIntroduced: dateFormatter.date(from: "2006")!, introPrice: 25.00, color: .blue) ] } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() setupDataModel() resultsTableController = ResultsTableController() resultsTableController.suggestedSearchDelegate = self // So we can be notified when a suggested search token is selected. searchController = UISearchController(searchResultsController: resultsTableController) searchController.searchResultsUpdater = self searchController.searchBar.autocapitalizationType = .none searchController.searchBar.searchTextField.placeholder = NSLocalizedString("Enter a search term", comment: "") searchController.searchBar.returnKeyType = .done // Place the search bar in the navigation bar. navigationItem.searchController = searchController // Make the search bar always visible. navigationItem.hidesSearchBarWhenScrolling = false // Monitor when the search controller is presented and dismissed. searchController.delegate = self // Monitor when the search button is tapped, and start/end editing. searchController.searchBar.delegate = self /** Specify that this view controller determines how the search controller is presented. The search controller should be presented modally and match the physical size of this view controller. */ definesPresentationContext = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) userActivity = self.view.window?.windowScene?.userActivity if userActivity != nil { // Restore the active state. searchController.isActive = userActivity!.userInfo?[RestorationKeys.searchControllerIsActive.rawValue] as? Bool ?? false // Restore the first responder status. if let wasFirstResponder = userActivity!.userInfo?[RestorationKeys.searchBarIsFirstResponder.rawValue] as? Bool { if wasFirstResponder { searchController.searchBar.becomeFirstResponder() } } // Restore the text in the search field. if let searchBarText = userActivity!.userInfo?[RestorationKeys.searchBarText.rawValue] as? String { searchController.searchBar.text = searchBarText } if let token = userActivity!.userInfo?[RestorationKeys.searchBarToken.rawValue] as? NSNumber { searchController.searchBar.searchTextField.tokens = [ResultsTableController.searchToken(tokenValue: token.intValue)] } resultsTableController.showSuggestedSearches = false } else { // No current acivity, so create one. userActivity = NSUserActivity(activityType: MainTableViewController.viewControllerActivityType()) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // No longer interested in the current activity. view.window?.windowScene?.userActivity = nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationViewController = segue.destination as? DetailViewController { if tableView.indexPathForSelectedRow != nil { destinationViewController.product = products[tableView.indexPathForSelectedRow!.row] } } } } // MARK: - UITableViewDataSource extension MainTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewController.productCellIdentifier, for: indexPath) let product = products[indexPath.row] configureCell(cell, forProduct: product) return cell } func setToSuggestedSearches() { // Show suggested searches only if we don't have a search token in the search field. if searchController.searchBar.searchTextField.tokens.isEmpty { resultsTableController.showSuggestedSearches = true // We are no longer interested in cell navigating, since we are now showing the suggested searches. resultsTableController.tableView.delegate = resultsTableController } } } // MARK: - UISearchBarDelegate extension MainTableViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text!.isEmpty { // Text is empty, show suggested searches again. setToSuggestedSearches() } else { resultsTableController.showSuggestedSearches = false } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // User tapped the Done button in the keyboard. searchController.dismiss(animated: true, completion: nil) searchBar.text = "" } } // MARK: - UISearchControllerDelegate // Use these delegate functions for additional control over the search controller. extension MainTableViewController: UISearchControllerDelegate { // We are being asked to present the search controller, so from the start - show suggested searches. func presentSearchController(_ searchController: UISearchController) { searchController.showsSearchResultsController = true setToSuggestedSearches() } } // MARK: - State Restoration extension MainTableViewController { /** Returns the activity object you can use to restore the previous contents of your scene's interface. Before disconnecting a scene, the system asks your delegate for an NSUserActivity object containing state information for that scene. If you provide that object, the system puts a copy of it in this property. Use the information in the user activity object to restore the scene to its previous state. */ override func updateUserActivityState(_ activity: NSUserActivity) { super.updateUserActivityState(activity) // Update the user activity with the state of the search controller. activity.userInfo = [RestorationKeys.searchControllerIsActive.rawValue: searchController.isActive, RestorationKeys.searchBarIsFirstResponder.rawValue: searchController.searchBar.isFirstResponder, RestorationKeys.searchBarText.rawValue: searchController.searchBar.text!] // Add the search token if it exists in the search field. if !searchController.searchBar.searchTextField.tokens.isEmpty { let searchToken = searchController.searchBar.searchTextField.tokens[0] if let searchTokenRep = searchToken.representedObject as? NSNumber { activity.addUserInfoEntries(from: [RestorationKeys.searchBarToken.rawValue: searchTokenRep]) } } } /** Restores the state needed to continue the given user activity. Subclasses override this method to restore the responder�s state with the given user activity. The override should use the state data contained in the userInfo dictionary of the given user activity to restore the object. */ override func restoreUserActivityState(_ activity: NSUserActivity) { super.restoreUserActivityState(activity) } } // MARK: - Table View extension UITableViewController { static let productCellIdentifier = "cellID" // Used by both MainTableViewController and ResultsTableController to define its table cells. func configureCell(_ cell: UITableViewCell, forProduct product: Product) { let textTitle = NSMutableAttributedString(string: product.title) let textColor = ResultsTableController.suggestedColor(fromIndex: product.color) textTitle.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSRange(location: 0, length: textTitle.length)) cell.textLabel?.attributedText = textTitle // Build the price and year as the detail right string. let priceString = product.formattedPrice() let yearString = product.formattedDate() cell.detailTextLabel?.text = "(priceString!) | (yearString!)" cell.accessoryType = .disclosureIndicator cell.imageView?.image = nil } } ``` ## Product.swift ```swift /* Abstract: The data model object describing the product displayed in both main and results tables. */ import Foundation import UIKit struct Product: Codable { private enum CodingKeys: String, CodingKey { case title case yearIntroduced case introPrice case color } enum ColorKind: Int { case red = 0 case green = 1 case blue = 2 case undedefined = 3 } // MARK: - Properties var title: String var yearIntroduced: Date var introPrice: Double var color: Int private let priceFormatter = NumberFormatter() private let yearFormatter = DateFormatter() // MARK: - Initializers func setup() { priceFormatter.numberStyle = .currency priceFormatter.formatterBehavior = .default yearFormatter.dateFormat = "yyyy" } init(title: String, yearIntroduced: Date, introPrice: Double, color: ColorKind) { self.title = title self.yearIntroduced = yearIntroduced self.introPrice = introPrice self.color = color.rawValue setup() } // MARK: - Formatters func formattedPrice() -> String? { /** Build the price string. Use the priceFormatter to obtain the formatted price of the product. */ return priceFormatter.string(from: NSNumber(value: introPrice)) } func formattedDate() -> String? { /** Build the date string. Use the yearFormatter to obtain the formatted year introduced. */ return yearFormatter.string(from: yearIntroduced) } // MARK: - Codable func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(title, forKey: .title) try container.encode(yearIntroduced, forKey: .yearIntroduced) try container.encode(introPrice, forKey: .introPrice) try container.encode(color, forKey: .color) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) title = try values.decode(String.self, forKey: .title) yearIntroduced = try values.decode(Date.self, forKey: .yearIntroduced) introPrice = try values.decode(Double.self, forKey: .introPrice) color = try values.decode(Int.self, forKey: .color) setup() } } ``` ## ResultsTableController.swift ```swift /* Abstract: The table view controller responsible for displaying the filtered products as the user types in the search field. */ import UIKit // This protocol helps inform MainTableViewController that a suggested search or product was selected. protocol SuggestedSearch: AnyObject { // A suggested search was selected; inform our delegate that the selected search token was selected. func didSelectSuggestedSearch(token: UISearchToken) // A product was selected; inform our delgeate that a product was selected to view. func didSelectProduct(product: Product) } class ResultsTableController: UITableViewController { var filteredProducts = [Product]() // Given the table cell row number, return the UIColor equivalent. class func suggestedColor(fromIndex: Int) -> UIColor { var suggestedColor: UIColor! switch fromIndex { case 0: suggestedColor = UIColor.systemRed case 1: suggestedColor = UIColor.systemGreen case 2: suggestedColor = UIColor.systemBlue case 3: suggestedColor = UIColor.label default: break } return suggestedColor } private func suggestedImage(fromIndex: Int) -> UIImage { let color = ResultsTableController.suggestedColor(fromIndex: fromIndex) return (UIImage(systemName: "magnifyingglass.circle.fill")?.withTintColor(color))! } class func suggestedTitle(fromIndex: Int) -> String { return suggestedSearches[fromIndex] } // Your delegate to receive suggested search tokens. weak var suggestedSearchDelegate: SuggestedSearch? // MARK: - UITableViewDataSource static let suggestedSearches = [ NSLocalizedString("Red Flowers", comment: ""), NSLocalizedString("Green Flowers", comment: ""), NSLocalizedString("Blue Flowers", comment: "") ] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return showSuggestedSearches ? ResultsTableController.suggestedSearches.count : filteredProducts.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return showSuggestedSearches ? NSLocalizedString("Suggested Searches", comment: "") : "" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationViewController = segue.destination as? DetailViewController { destinationViewController.product = filteredProducts[tableView.indexPathForSelectedRow!.row] } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: UITableViewController.productCellIdentifier) if showSuggestedSearches { let suggestedtitle = NSMutableAttributedString(string: ResultsTableController.suggestedSearches[indexPath.row]) suggestedtitle.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.label, range: NSRange(location: 0, length: suggestedtitle.length)) cell.textLabel?.attributedText = suggestedtitle // No detailed text or accessory for suggested searches. cell.detailTextLabel?.text = "" cell.accessoryType = .none // Compute the suggested image when it is the proper color. let image = suggestedImage(fromIndex: indexPath.row) let tintableImage = image.withRenderingMode(.alwaysOriginal) cell.imageView?.image = tintableImage } else { let product = filteredProducts[indexPath.row] configureCell(cell, forProduct: product) } return cell } var showSuggestedSearches: Bool = false { didSet { if oldValue != showSuggestedSearches { tableView.reloadData() } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // We must have a delegate to respond to row selection. guard let suggestedSearchDelegate = suggestedSearchDelegate else { return } tableView.deselectRow(at: indexPath, animated: true) // Make sure we are showing suggested searches before notifying which token was selected. if showSuggestedSearches { // A suggested search was selected; inform our delegate that the selected search token was selected. let tokenToInsert = ResultsTableController.searchToken(tokenValue: indexPath.row) suggestedSearchDelegate.didSelectSuggestedSearch(token: tokenToInsert) } else { // A product was selected; inform our delgeate that a product was selected to view. let selectedProduct = filteredProducts[indexPath.row] suggestedSearchDelegate.didSelectProduct(product: selectedProduct) } } // Given a table cell row number index, return its color number equivalent. class func colorKind(fromIndex: Int) -> Product.ColorKind { var colorKind: Product.ColorKind! switch fromIndex { case 0: colorKind = Product.ColorKind.red case 1: colorKind = Product.ColorKind.green case 2: colorKind = Product.ColorKind.blue default: break } return colorKind } // Search a search token from an input value. class func searchToken(tokenValue: Int) -> UISearchToken { let tokenColor = ResultsTableController.suggestedColor(fromIndex: tokenValue) let image = UIImage(systemName: "circle.fill")?.withTintColor(tokenColor, renderingMode: .alwaysOriginal) let searchToken = UISearchToken(icon: image, text: suggestedTitle(fromIndex: tokenValue)) // Set the color kind number as the token value. let color = ResultsTableController.colorKind(fromIndex: tokenValue).rawValue searchToken.representedObject = NSNumber(value: color) return searchToken } } ``` ## SceneDelegate.swift ```swift /* Abstract: The application's primary scene delegate class. */ import UIKit extension NSUserActivity { func hasRestoreActivity() -> Bool { return userInfo != nil && !userInfo!.isEmpty } } class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { /** Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. If using a storyboard, the `window` property will automatically be initialized and attached to the scene. This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). */ guard let scene = (scene as? UIWindowScene) else { return } scene.userActivity = session.stateRestorationActivity ?? NSUserActivity(activityType: MainTableViewController.viewControllerActivityType()) // Is there something to restore? if scene.userActivity!.hasRestoreActivity() { // Check if we need to restore the MainTableViewController. if scene.userActivity!.activityType.hasSuffix(MainTableViewController.activitySuffix) { if let navigationController = window?.rootViewController as? UINavigationController { if let mainTableViewController = navigationController.topViewController { mainTableViewController.restoreUserActivityState(scene.userActivity!) } } } else // Check if we need to restore the DetailViewController. if scene.userActivity!.activityType.hasSuffix(DetailViewController.activitySuffix) { if let detailViewController = DetailViewController.loadFromStoryboard() { if let navigationController = window?.rootViewController as? UINavigationController { if let mainTableVC = navigationController.topViewController as? MainTableViewController { mainTableVC.navigationController?.pushViewController(detailViewController, animated: false) detailViewController.restoreUserActivityState(scene.userActivity!) } } } } else { // Some other user activity is being restored. } } } // Called when the app is sent to the background to restore state. func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { if let navigationController = window?.rootViewController as? UINavigationController { if let currentViewController = navigationController.topViewController as? DetailViewController { return currentViewController.userActivity } else if let currentViewController = navigationController.topViewController as? MainTableViewController { return currentViewController.userActivity } } return scene.userActivity } } ``` ## AppDelegate.swift ```swift /* Abstract: The app delegate. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } } ``` ## CellDataFlowExample.swift ```swift /* Abstract: The cell data flow example. */ import UIKit import SwiftUI // The list of medical conditions only has a single section. private enum Section: Hashable { case main } // A model object that represents one medical condition. This class conforms to the ObservableObject protocol, // which enables SwiftUI views using this object to automatically update when the property annotated with the // @Published property wrapper changes, and also allows SwiftUI to write back changes to this property as well. @MainActor private class MedicalCondition: Identifiable, ObservableObject { // A stable, unique identifier for the medical condition. This property satisfies the requirements // of the Identifiable protocol. let id: UUID // The text of the medical condition. @Published var text: String init(id: UUID, text: String) { self.id = id self.text = text } } private extension MedicalCondition { // Returns an array of default medical conditions. static func getDefaultConditions() -> [MedicalCondition] { let names = [ "Diabetes", "Hypertension", "Migraines", "Pregnancy", "Osteoporosis", "Arthritis" ] return names.map { MedicalCondition(id: UUID(), text: $0) } } } // A class that stores a collection of medical conditions, and provides methods to access medical conditions from // the collection and mutate the collection of medical conditions. @MainActor private class DataStore { // The stored medical conditions. A tuple is used to store them in two data structures: an array to maintain ordering, // and a dictionary for constant-time lookups of medical conditions by their unique identifiers. private var data: (conditions: [MedicalCondition], conditionsByID: [MedicalCondition.ID: MedicalCondition]) = ([], [:]) { didSet { // Notify observers that the collection of medical conditions changed. Note that this notification is only posted for // changes to the collection of data itself (when medical conditions are inserted, deleted, or reordered), but not // for changes to the properties of each medical condition. NotificationCenter.default.post(name: .medicalConditionsDidChange, object: nil) } } // Returns an array of all stored medical conditions. var allMedicalConditions: [MedicalCondition] { data.conditions } // Returns the medical condition for the specified identifier. func medicalCondition(for id: MedicalCondition.ID) -> MedicalCondition? { data.conditionsByID[id] } // Populates the data store with the default set of medical conditions. func populateDefaultMedicalConditions() { var conditions = [MedicalCondition]() var conditionsByID = [MedicalCondition.ID: MedicalCondition]() for condition in MedicalCondition.getDefaultConditions() { conditions.append(condition) conditionsByID[condition.id] = condition } data = (conditions, conditionsByID) } // Adds a new medical condition to the data store. func addNewMedicalCondition() { var conditions = data.conditions var conditionsByID = data.conditionsByID let condition = MedicalCondition(id: UUID(), text: "") conditions.append(condition) conditionsByID[condition.id] = condition data = (conditions, conditionsByID) } // Deletes the specified medical condition from the data store. func delete(_ condition: MedicalCondition) { var conditions = data.conditions var conditionsByID = data.conditionsByID conditions.removeAll { $0.id == condition.id } conditionsByID[condition.id] = nil data = (conditions, conditionsByID) } // Shuffles the medical conditions in the data store to randomize their order. func shuffleMedicalConditions() { data.conditions.shuffle() } // Sorts the medical conditions in the data store alphabetically. func sortMedicalConditions() { data.conditions.sort { $0.text.localizedCaseInsensitiveCompare($1.text) == .orderedAscending } } } private extension NSNotification.Name { // A notification that is posted when medical conditions are added, reordered, or deleted in the data store. static let medicalConditionsDidChange = Notification.Name("com.example.UseSwiftUIWithUIKit.medicalConditionsDidChange") } // A SwiftUI view used inside each cell that displays a medical condition. private struct MedicalConditionView: View { // Stores the medical condition that is displayed by this view. Using the @ObservedObject // property wrapper here ensures that SwiftUI will automatically refresh the view when any // of the @Published properties of the ObservableObject change, and also allows a binding // to be created to the medical condition's text so that SwiftUI can write back changes to // that property when the user types into the text field. @ObservedObject var condition: MedicalCondition // Whether the medical condition in the cell should be editable. var isEditable: Bool var body: some View { TextField("Condition", text: $condition.text) .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } .disabled(!isEditable) } } // The view controller which manages a collection view of medical conditions. class MedicalConditionsViewController: UIViewController { // The data store that manages the collection of medical conditions displayed by this view controller. private var dataStore = DataStore() // The collection view which will display a list of medical conditions. private var collectionView: UICollectionView! // The diffable data source which is responsible for updating the collection view to insert, delete, and move cells // when the underlying collection of medical conditions in the data store is modified. private var dataSource: UICollectionViewDiffableDataSource<Section, MedicalCondition.ID>! override func loadView() { setUpCollectionView() view = collectionView } override func viewDidLoad() { super.viewDidLoad() title = "Conditions" // Set up the navigation bar and toolbar items. updateBarButtonItems() setUpToolbarItems() let defaultCenter = NotificationCenter.default // Register for notifications when medical conditions are added, reordered, or deleted. defaultCenter.addObserver(self, selector: #selector(medicalConditionsDidChange(_:)), name: .medicalConditionsDidChange, object: nil) // Register for notifications when the keyboard shows or hides, in order to update the collection view insets. defaultCenter.addObserver(self, selector: #selector(updateKeyboardInset(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) defaultCenter.addObserver(self, selector: #selector(updateKeyboardInset(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) // Populate the data store with the default medical conditions. dataStore.populateDefaultMedicalConditions() } private var toolbarCountLabel: UILabel! // Configures the toolbar to display a count label. private func setUpToolbarItems() { toolbarCountLabel = UILabel() toolbarCountLabel.font = .preferredFont(forTextStyle: .caption1) toolbarCountLabel.textColor = .secondaryLabel updateToolbarCountLabel() setToolbarItems([UIBarButtonItem(systemItem: .flexibleSpace), UIBarButtonItem(customView: toolbarCountLabel), UIBarButtonItem(systemItem: .flexibleSpace)], animated: false) navigationController?.isToolbarHidden = false } // Updates the toolbar count label to display the total number of medical conditions. private func updateToolbarCountLabel() { let totalConditions = dataStore.allMedicalConditions.count if totalConditions == 0 { toolbarCountLabel?.text = "No Medical Conditions" } else if totalConditions == 1 { toolbarCountLabel?.text = "(totalConditions.formatted(.number)) Medical Condition" } else { toolbarCountLabel?.text = "(totalConditions.formatted(.number)) Medical Conditions" } toolbarCountLabel.sizeToFit() } // Updates the right bar button items, based on whether the collection view is currently editing. private func updateBarButtonItems() { let editingItem: UIBarButtonItem.SystemItem = collectionView.isEditing ? .done : .edit var barButtonItems = [ UIBarButtonItem(systemItem: editingItem, primaryAction: UIAction { [weak self] _ in self?.toggleEditing() }) ] if collectionView.isEditing { barButtonItems.append(UIBarButtonItem(title: "New", primaryAction: UIAction { [weak self] _ in self?.dataStore.addNewMedicalCondition() })) } else { barButtonItems.append(UIBarButtonItem(title: "Shuffle", primaryAction: UIAction { [weak self] _ in self?.dataStore.shuffleMedicalConditions() })) barButtonItems.append(UIBarButtonItem(title: "Sort", primaryAction: UIAction { [weak self] _ in self?.dataStore.sortMedicalConditions() })) } navigationItem.rightBarButtonItems = barButtonItems } // Toggles the editing state of the collection view. private func toggleEditing() { let wasEditing = collectionView.isEditing collectionView.isEditing = !wasEditing updateBarButtonItems() if wasEditing { dismissKeyboard() } } // This method is called whenever the collection of data changes: when a new medical condition is added, // or an existing medical condition is deleted, or a medical condition is reordered. Note that it is not // called when properties of an individual medical condition change. @objc private func medicalConditionsDidChange(_ notification: NSNotification) { applyUpdatedSnapshot() updateToolbarCountLabel() } // Creates the collection view with a list layout, and a diffable data source wired to the collection view. private func setUpCollectionView() { let listConfig = UICollectionLayoutListConfiguration(appearance: .plain) let layout = UICollectionViewCompositionalLayout.list(using: listConfig) collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.allowsSelection = false // Create a cell registration that configures a list cell to display a medical condition. let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, MedicalCondition> { [unowned self] cell, indexPath, item in configureMedicalConditionCell(cell, for: item) } dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [unowned self] collectionView, indexPath, itemIdentifier in // Fetch the medical condition from the data store, using the identifier passed from the diffable data source. let item = dataStore.medicalCondition(for: itemIdentifier)! return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item) } } // Whether a snapshot has been applied to the diffable data source yet. private var didApplyInitialSnapshot = false // Applies a new snapshot to the diffable data source based on the current medical conditions in the data store. private func applyUpdatedSnapshot() { // Start with an empty snapshot each time. var snapshot = NSDiffableDataSourceSnapshot<Section, MedicalCondition.ID>() // This list only has a single section. snapshot.appendSections([.main]) // Generate an array containing the unique identifiers for each medical condition, and add those identifiers // to the snapshot. It is important to populate the snapshot with stable identifiers for each model object, // and not the model objects themselves, so that the diffable data source can accurately track the identity // of each item and generate the correct updates to the collection view as new snapshots are applied. let itemIdentifiers = dataStore.allMedicalConditions.map { $0.id } snapshot.appendItems(itemIdentifiers, toSection: .main) // Apply the new snapshot to the diffable data source, animating the changes as long // as this is not the initial snapshot being applied to the diffable data source. let shouldAnimate = didApplyInitialSnapshot dataSource.apply(snapshot, animatingDifferences: shouldAnimate) didApplyInitialSnapshot = true } // Configures a list cell to display a medical condition. private func configureMedicalConditionCell(_ cell: UICollectionViewListCell, for item: MedicalCondition) { cell.accessories = [.delete()] // Create a handler to execute when the cell's delete swipe action button is triggered. let deleteHandler: () -> Void = { [weak self] in // Make sure to use the item itself (or its stable identifier) in any escaping closures, such as // this delete handler. Do not capture the index path of the cell, as a cell's index path will // change when other items before it are inserted or deleted, leaving the closure with a stale // index path that will cause the wrong item to be deleted! self?.dataStore.delete(item) } // Configure the cell with a UIHostingConfiguration inside the cell's configurationUpdateHandler so // that the SwiftUI content in the cell can change based on whether the cell is editing. This handler // is executed before the cell first becomes visible, and anytime the cell's state changes. cell.configurationUpdateHandler = { cell, state in cell.contentConfiguration = UIHostingConfiguration { MedicalConditionView(condition: item, isEditable: state.isEditing) .swipeActions(edge: .trailing) { Button(role: .destructive, action: deleteHandler) { Label("Delete", systemImage: "trash") } } } } } // Stores the total amount that the keyboard overlaps the collection view from the bottom edge. private var keyboardOverlap = 0.0 // Updates the insets of the collection view when the keyboard shows or hides, to ensure content // can scroll out from underneath the keyboard. @objc private func updateKeyboardInset(_ notification: NSNotification? = nil) { guard let window = collectionView.window else { return } if let info = notification?.userInfo, let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { let rectInView = window.screen.coordinateSpace.convert(keyboardFrame, to: collectionView) keyboardOverlap = collectionView.bounds.maxY - rectInView.minY } let keyboardInset = max(0, keyboardOverlap - view.safeAreaInsets.bottom) let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardInset, right: 0) collectionView.contentInset = insets collectionView.scrollIndicatorInsets = insets } override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() updateKeyboardInset() } // Dismisses the keyboard by asking the current first responder to resign. private func dismissKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } ``` ## HostingControllerExample.swift ```swift /* Abstract: The hosting controller example. */ import UIKit import SwiftUI // A model object that represents an alert that can be enabled when certain heart conditions are detected. // This class conforms to the ObservableObject protocol, which enables SwiftUI views using this object to // automatically update when properties annotated with the @Published property wrapper change, and also // allows SwiftUI to write back changes to these properties as well. @MainActor private class HeartHealthAlert: ObservableObject { // The name of the symbol displayed for this alert. @Published var systemImageName: String // The title of the alert. @Published var title: String // A description of the alert, shown when the alert is enabled. @Published var description: String // Whether the alert is enabled. @Published var isEnabled: Bool { didSet { if oldValue != isEnabled { // SwiftUI views that use this property are automatically updated whenever it changes. // For UIKit views that depend on this state, this example posts a notification as a // simple mechanism to update them, but a real application may use whatever facility // fits best within the application's architecture to trigger those updates. NotificationCenter.default.post(name: .heartHealthAlertEnabledDidChange, object: self) } } } init(systemImageName: String, title: String, description: String, isEnabled: Bool = false) { self.systemImageName = systemImageName self.title = title self.description = description self.isEnabled = isEnabled } } private extension HeartHealthAlert { // Returns the default heart health alerts. static func getDefaultAlerts() -> [HeartHealthAlert] { [ HeartHealthAlert(systemImageName: "bolt.heart.fill", title: "Irregular Rhythm", description: "You will be notified when an irregular heart rhythm is detected."), HeartHealthAlert(systemImageName: "arrow.up.heart.fill", title: "High Heart Rate", description: "You will be notified when your heart rate rises above normal levels."), HeartHealthAlert(systemImageName: "arrow.down.heart.fill", title: "Low Heart Rate", description: "You will be notified when your heart rate falls below normal levels.") ] } } private extension NSNotification.Name { // A notification that is posted when a heart health alert is enabled or disabled. static let heartHealthAlertEnabledDidChange = Notification.Name("com.example.UseSwiftUIWithUIKit.heartHealthAlertEnabledDidChange") } // A SwiftUI view that allows the user to enable or disable a heart health alert. private struct HeartHealthAlertView: View { // Stores the heart health alert that is displayed by this view. Using the @ObservedObject // property wrapper here ensures that SwiftUI will automatically refresh the view when any // of the @Published properties of the ObservableObject change. @ObservedObject var alert: HeartHealthAlert var body: some View { VStack(alignment: .leading) { HStack { Image(systemName: alert.systemImageName) .imageScale(.large) Text(alert.title) Spacer() // The Toggle (on/off switch) displayed in this view is created with a binding to the // isEnabled property of the alert. When the user toggles the alert on or off, SwiftUI // will directly set the isEnabled property of the model object to the new value. Toggle("Enabled", isOn: $alert.isEnabled) .labelsHidden() } // The extra description text is only added to the view when the alert is enabled. if alert.isEnabled { Text(alert.description) .font(.caption) } } .padding() .background( RoundedRectangle(cornerRadius: 10, style: .continuous) .fill(Color(uiColor: .tertiarySystemFill)) ) } } class HostingControllerViewController: UIViewController { // An array of the heart health alert model objects that are displayed by this view controller. private var alerts = HeartHealthAlert.getDefaultAlerts() // Returns the number of alerts that are currently enabled. private var alertsEnabledCount: Int { var count = 0 for alert in alerts where alert.isEnabled { count += 1 } return count } // Stores the hosting controllers that each display a SwiftUI heart health alert view. private var hostingControllers = [UIHostingController<HeartHealthAlertView>]() override func viewDidLoad() { super.viewDidLoad() title = "Heart Health Alerts" view.backgroundColor = .systemBackground // Create the hosting controllers and set up the stack view. createHostingControllers() setUpStackView() // Update the UIKit views based on the current state of the alerts. updateSummaryLabel() updateBarButtonItem() // Register for notifications when heart health alerts are enabled or disabled, in order to update the UIKit views as necessary. let defaultCenter = NotificationCenter.default defaultCenter.addObserver(self, selector: #selector(heartHealthAlertDidChange(_:)), name: .heartHealthAlertEnabledDidChange, object: nil) } // Creates a hosting controller for each heart health alert. private func createHostingControllers() { for alert in alerts { let alertView = HeartHealthAlertView(alert: alert) let hostingController = UIHostingController(rootView: alertView) // Set the sizing options of the hosting controller so that it automatically updates the // intrinsicContentSize of its view based on the ideal size of the SwiftUI content. hostingController.sizingOptions = .intrinsicContentSize hostingControllers.append(hostingController) } } // Embeds each hosting controller's view in a stack view, and adds the stack view to this view controller's view. private func setUpStackView() { // Collect the view from each hosting controller, as well as the summary label. var views: [UIView] = hostingControllers.map { $0.view } views.append(summaryLabel) // Add each hosting controller as a child view controller. hostingControllers.forEach { addChild($0) } // Create a stack view that contains all the views, and add it as a subview to the view // of this view controller. let spacing = 10.0 let stackView = UIStackView(arrangedSubviews: views) stackView.axis = .vertical stackView.alignment = .fill stackView.distribution = .equalSpacing stackView.spacing = spacing stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor), stackView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: spacing) ]) // Notify each hosting controller that it has now moved to a new parent view controller. hostingControllers.forEach { $0.didMove(toParent: self) } } // This method is called whenever a heart health alert is enabled or disabled. @objc private func heartHealthAlertDidChange(_ notification: NSNotification) { // Update the UIKit parts of this view controller as necessary based on which alerts are now enabled. // There is no need to update any SwiftUI views in the hosting controllers here, as those are // refreshed automatically because the HeartHealthAlert is an ObservableObject. updateBarButtonItem() updateSummaryLabel() } // Updates the right bar button item to enable or disable all alerts, based on whether any are currently enabled. private func updateBarButtonItem() { let title: String let action: UIAction if alertsEnabledCount > 0 { title = "Disable All" action = UIAction { [unowned self] _ in alerts.forEach { $0.isEnabled = false } } } else { title = "Enable All" action = UIAction { [unowned self] _ in alerts.forEach { $0.isEnabled = true } } } navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, primaryAction: action) } // Returns a UILabel that displays the total number of heart health alerts enabled. private lazy var summaryLabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .preferredFont(forTextStyle: .caption1) label.textColor = .secondaryLabel label.textAlignment = .center return label }() // Updates the summary label to display the total number of enabled alerts. private func updateSummaryLabel() { let enabledCount = alertsEnabledCount if enabledCount == 0 { summaryLabel.text = "No Alerts Enabled" } else if enabledCount == 1 { summaryLabel.text = "(enabledCount.formatted(.number)) Alert Enabled" } else { summaryLabel.text = "(enabledCount.formatted(.number)) Alerts Enabled" } } } ``` ## HostingConfigurationExample.swift ```swift /* Abstract: The hosting configuration example. */ import UIKit import SwiftUI // An enum representing the sections of this collection view. private enum HealthSection: Int, CaseIterable { case heartRate case healthCategories case sleep case steps } // A struct that stores the static data used in this example. private struct StaticData { lazy var heartRateItems = HeartRateData.generateRandomData(quantity: 3) lazy var healthCategories = HealthCategory.allCases lazy var sleepItems = SleepData.generateRandomData(quantity: 4) lazy var stepItems = StepData.generateRandomData(days: 7) } class HostingConfigurationViewController: UIViewController, UICollectionViewDataSource { // The static data being displayed by this view controller. private var data = StaticData() // The collection view which will display the custom cells. private var collectionView: UICollectionView! override func loadView() { setUpCollectionView() view = collectionView } override func viewDidLoad() { super.viewDidLoad() title = "SwiftUI in Cells" view.maximumContentSizeCategory = .extraExtraExtraLarge } // Creates the collection view with a compositional layout, which contains multiple sections of different layouts. private func setUpCollectionView() { let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, layoutEnvironment in switch HealthSection(rawValue: sectionIndex)! { case .heartRate: return createOrthogonalScrollingSection() case .healthCategories: return createListSection(layoutEnvironment) case .sleep: return createGridSection() case .steps: return createListSection(layoutEnvironment) } } collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = .systemGroupedBackground collectionView.allowsSelection = false collectionView.dataSource = self } private struct LayoutMetrics { static let horizontalMargin = 16.0 static let sectionSpacing = 10.0 static let cornerRadius = 10.0 } // Returns a compositional layout section for cells that will scroll orthogonally. private func createOrthogonalScrollingSection() -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(100)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.8), heightDimension: .estimated(100)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) group.contentInsets = .zero group.contentInsets.leading = LayoutMetrics.horizontalMargin let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .groupPaging section.contentInsets = .zero section.contentInsets.trailing = LayoutMetrics.horizontalMargin section.contentInsets.bottom = LayoutMetrics.sectionSpacing return section } // Returns a compositional layout section for cells in a grid. private func createGridSection() -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .estimated(120)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(120)) let group = NSCollectionLayoutGroup.horizontalGroup(with: groupSize, repeatingSubitem: item, count: 2) group.interItemSpacing = .fixed(8) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = 8 section.contentInsets = .zero section.contentInsets.leading = LayoutMetrics.horizontalMargin section.contentInsets.trailing = LayoutMetrics.horizontalMargin section.contentInsets.bottom = LayoutMetrics.sectionSpacing return section } // Returns a compositional layout section for cells in a list. private func createListSection(_ layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection { let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped) let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment) section.contentInsets = .zero section.contentInsets.leading = LayoutMetrics.horizontalMargin section.contentInsets.trailing = LayoutMetrics.horizontalMargin section.contentInsets.bottom = LayoutMetrics.sectionSpacing return section } func numberOfSections(in collectionView: UICollectionView) -> Int { HealthSection.allCases.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch HealthSection(rawValue: section)! { case .heartRate: return data.heartRateItems.count case .healthCategories: return data.healthCategories.count case .sleep: return data.sleepItems.count case .steps: return data.stepItems.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch HealthSection(rawValue: indexPath.section)! { case .heartRate: let item = data.heartRateItems[indexPath.item] return collectionView.dequeueConfiguredReusableCell(using: heartRateCellRegistration, for: indexPath, item: item) case .healthCategories: let item = data.healthCategories[indexPath.item] return collectionView.dequeueConfiguredReusableCell(using: healthCategoryCellRegistration, for: indexPath, item: item) case .sleep: let item = data.sleepItems[indexPath.item] return collectionView.dequeueConfiguredReusableCell(using: sleepCellRegistration, for: indexPath, item: item) case .steps: let item = data.stepItems[indexPath.item] return collectionView.dequeueConfiguredReusableCell(using: stepCountCellRegistration, for: indexPath, item: item) } } // A cell registration that configures a custom cell with a SwiftUI heart rate view. private var heartRateCellRegistration: UICollectionView.CellRegistration<UICollectionViewCell, HeartRateData> = { .init { cell, indexPath, item in cell.contentConfiguration = UIHostingConfiguration { HeartRateCellView(data: item) } .margins(.horizontal, LayoutMetrics.horizontalMargin) .background { RoundedRectangle(cornerRadius: LayoutMetrics.cornerRadius, style: .continuous) .fill(Color(uiColor: .secondarySystemGroupedBackground)) } } }() // A cell registration that configures a custom list cell with a SwiftUI health category view. private var healthCategoryCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, HealthCategory> = { .init { cell, indexPath, item in cell.contentConfiguration = UIHostingConfiguration { HealthCategoryCellView(healthCategory: item) } } }() // A cell registration that configures a custom cell with a SwiftUI sleep view. private var sleepCellRegistration: UICollectionView.CellRegistration<UICollectionViewCell, SleepData> = { .init { cell, indexPath, item in cell.contentConfiguration = UIHostingConfiguration { SleepCellView(data: item) } .margins(.horizontal, LayoutMetrics.horizontalMargin) .background { RoundedRectangle(cornerRadius: LayoutMetrics.cornerRadius, style: .continuous) .fill(Color(uiColor: .secondarySystemGroupedBackground)) } } }() // A cell registration that configures a custom list cell with a SwiftUI step count view. private var stepCountCellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, StepData> = { .init { cell, indexPath, item in cell.contentConfiguration = UIHostingConfiguration { StepCountCellView(data: item) } } }() } ``` ## HealthCategoryCellView.swift ```swift /* Abstract: The SwiftUI view for the health category cell. */ import SwiftUI struct HealthCategoryProperties { var name: String var systemImageName: String var color: Color } enum HealthCategory: CaseIterable { case activity case bodyMeasurement case hearing case heart var properties: HealthCategoryProperties { switch self { case .activity: return .init(name: "Activity", systemImageName: "flame.fill", color: .orange) case .bodyMeasurement: return .init(name: "Body Measurements", systemImageName: "figure.stand", color: .purple) case .hearing: return .init(name: "Hearing", systemImageName: "ear", color: .blue) case .heart: return .init(name: "Heart", systemImageName: "heart.fill", color: .pink) } } } struct HealthCategoryCellView: View { var healthCategory: HealthCategory private var properties: HealthCategoryProperties { healthCategory.properties } var body: some View { HStack { Label(properties.name, systemImage: properties.systemImageName) .foregroundStyle(properties.color) .font(.system(.headline, weight: .bold)) Spacer() } } } struct HealthCategoryCellView_Previews: PreviewProvider { static var previews: some View { List { HealthCategoryCellView(healthCategory: .activity) HealthCategoryCellView(healthCategory: .bodyMeasurement) HealthCategoryCellView(healthCategory: .hearing) HealthCategoryCellView(healthCategory: .heart) } } } ``` ## HeartRateCellView.swift ```swift /* Abstract: The SwiftUI view for the heart rate cell. */ import SwiftUI import Charts struct HeartRateSample: Identifiable { let id: UUID var time: Date var beatsPerMinute: Int } struct HeartRateData { var samples = [HeartRateSample]() var latestSample: HeartRateSample { samples.first! } } struct HeartRateCellView: View { var data: HeartRateData var body: some View { VStack(alignment: .leading) { HeartRateTitleView(time: data.latestSample.time) HStack(alignment: .bottom) { HeartRateBPMView(latestSample: data.latestSample) Spacer(minLength: 60) HeartRateChartView(heartRateSamples: data.samples) } } .padding(.vertical, 8) } } struct HeartRateTitleView: View { var time: Date var body: some View { HStack(alignment: .firstTextBaseline) { Label("Heart Rate", systemImage: "heart.fill") .foregroundStyle(.pink) .font(.system(.subheadline, weight: .bold)) .layoutPriority(1) Spacer() Text(time, style: .time) .foregroundStyle(.secondary) .font(.footnote) } } } struct HeartRateBPMView: View { var latestSample: HeartRateSample var body: some View { HStack(alignment: .firstTextBaseline, spacing: 2) { Text(latestSample.beatsPerMinute, format: .number) .foregroundStyle(.primary) .font(.system(.title, weight: .semibold)) Text("BPM") .foregroundStyle(.secondary) .font(.system(.subheadline, weight: .bold)) } } } struct HeartRateChartView: View { var heartRateSamples: [HeartRateSample] var body: some View { Chart(heartRateSamples) { sample in LineMark(x: .value("Time", sample.time), y: .value("Beats Per Minute", sample.beatsPerMinute)) .symbol(Circle().strokeBorder(lineWidth: 2)) .symbolSize(CGSize(width: 6, height: 6)) .foregroundStyle(.pink) } .chartXAxis(.hidden) .chartYAxis(.hidden) .chartYScale(domain: .automatic(includesZero: false)) .padding(.vertical, 8) } } extension HeartRateData { static func generateRandomData(quantity: Int) -> [HeartRateData] { var data = [HeartRateData]() for _ in 0..<quantity { var heartRateData = HeartRateData() let now = Date() let bpmRange = 60...120 var currentBPM = Int.random(in: bpmRange) for index in 0...6 { let time = Calendar.current.date(byAdding: .minute, value: -index, to: now)! let sample = HeartRateSample(id: UUID(), time: time, beatsPerMinute: currentBPM) heartRateData.samples.append(sample) let delta = Int.random(in: -10...10) currentBPM = max(bpmRange.lowerBound, min(bpmRange.upperBound, currentBPM + delta)) } data.append(heartRateData) } return data } } struct HeartRateCellView_Previews: PreviewProvider { static var previews: some View { List { HeartRateCellView(data: HeartRateData()) } } } ``` ## SleepCellView.swift ```swift /* Abstract: The SwiftUI view for the sleep cell. */ import SwiftUI import Charts struct SleepSample: Identifiable { let id: UUID var date: Date var startMinute: Int var totalMinutes: Int var durationHours: Int { totalMinutes / 60 } var durationMinutes: Int { totalMinutes % 60 } } struct SleepData { var samples = [SleepSample]() var latestSample: SleepSample { samples.first! } } struct SleepCellView: View { var data: SleepData var body: some View { VStack(alignment: .leading) { SleepChartView(sleepSamples: data.samples) SleepTimeInBedView(latestSample: data.latestSample) } } } struct SleepChartView: View { var sleepSamples: [SleepSample] var body: some View { Chart(sleepSamples) { sample in RuleMark(x: .value("date", sample.date), yStart: .value("Start", sample.startMinute), yEnd: .value("End", sample.startMinute + sample.totalMinutes)) .foregroundStyle(.teal) .lineStyle(.init(lineWidth: 10, lineCap: .round)) } .chartXAxis(.hidden) .chartYAxis(.hidden) .chartYScale(domain: .automatic(includesZero: false)) .padding(.horizontal, 6) .padding(.top) .padding(.bottom, 4) .frame(height: 60) } } struct SleepTimeInBedView: View { var latestSample: SleepSample var body: some View { VStack(alignment: .leading) { Text("Time in Bed") .foregroundStyle(.secondary) .font(.system(.footnote, weight: .bold)) HStack(alignment: .firstTextBaseline, spacing: 2) { HourMinuteView(value: latestSample.durationHours, unit: "h") HourMinuteView(value: latestSample.durationMinutes, unit: "m") } } } } struct HourMinuteView: View { var value: Int var unit: String var body: some View { Text(value, format: .number) .foregroundStyle(.primary) .font(.system(.title2, weight: .semibold)) Text(unit) .foregroundStyle(.secondary) .font(.system(.footnote, weight: .bold)) } } extension SleepData { static func generateRandomData(quantity: Int) -> [SleepData] { var data = [SleepData]() for _ in 0..<quantity { var sleepData = SleepData() let today = Date() for index in 0...8 { let date = Calendar.current.date(byAdding: .day, value: -index, to: today)! let start = Int.random(in: 20...23) * 60 + Int.random(in: 0...59) let duration = Int.random(in: 6...9) * 60 + Int.random(in: 0...59) let sample = SleepSample(id: UUID(), date: date, startMinute: start, totalMinutes: duration) sleepData.samples.append(sample) } data.append(sleepData) } return data } } struct SleepCellView_Previews: PreviewProvider { static var previews: some View { List { SleepCellView(data: SleepData()) } } } ``` ## StepCountCellView.swift ```swift /* Abstract: The SwiftUI view for the step count cell. */ import SwiftUI struct StepData: Identifiable { let id: UUID var date: Date var stepCount: Int } struct StepCountCellView: View { var data: StepData var body: some View { HStack(alignment: .firstTextBaseline) { Text(data.date, format: .dateTime.weekday()) .textCase(.uppercase) .foregroundStyle(.secondary) .font(.system(.title3, weight: .bold).uppercaseSmallCaps()) .frame(minWidth: 50) HStack(alignment: .firstTextBaseline, spacing: 2) { Text(data.stepCount, format: .number) .foregroundStyle(.primary) .font(.system(.title, weight: .semibold)) .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } Text("steps") .foregroundStyle(.orange) .font(.system(.subheadline, weight: .bold)) } Spacer() } } } extension StepData { static func generateRandomData(days: Int) -> [StepData] { var data = [StepData]() let today = Date() for index in 0..<days { let date = Calendar.current.date(byAdding: .day, value: -index, to: today)! let stepCount = Int.random(in: 500...25_000) data.append(StepData(id: UUID(), date: date, stepCount: stepCount)) } return data } } struct StepCountCellView_Previews: PreviewProvider { static var previews: some View { List { ForEach(StepData.generateRandomData(days: 7)) { data in StepCountCellView(data: data) } } } } ``` ## MainMenuViewController.swift ```swift /* Abstract: The main menu for selecting different examples. */ import UIKit import SwiftUI private struct MenuItem { var title: String var subtitle: String var viewControllerProvider: () -> UIViewController static let allExamples = [ MenuItem(title: "SwiftUI View Controllers", subtitle: "Using UIHostingController", viewControllerProvider: { HostingControllerViewController() }), MenuItem(title: "SwiftUI in Cells", subtitle: "Using UIHostingConfiguration", viewControllerProvider: { HostingConfigurationViewController() }), MenuItem(title: "Data Flow with SwiftUI Cells", subtitle: "Using ObservableObject", viewControllerProvider: { MedicalConditionsViewController() }) ] } class MainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { private var collectionView: UICollectionView! override func loadView() { setUpCollectionView() view = collectionView } override func viewDidLoad() { super.viewDidLoad() title = "Examples" navigationController?.navigationBar.prefersLargeTitles = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) deselectSelectedItem(animated) } private func deselectSelectedItem(_ animated: Bool) { guard let indexPath = collectionView.indexPathsForSelectedItems?.first else { return } if let coordinator = transitionCoordinator { coordinator.animate(alongsideTransition: { _ in self.collectionView.deselectItem(at: indexPath, animated: true) }, completion: { context in if context.isCancelled { self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) } }) } else { collectionView.deselectItem(at: indexPath, animated: animated) } } private func setUpCollectionView() { let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in let listConfig = UICollectionLayoutListConfiguration(appearance: .plain) let layoutSection = NSCollectionLayoutSection.list(using: listConfig, layoutEnvironment: layoutEnvironment) return layoutSection } collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self } private var cellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, MenuItem> = { .init { cell, indexPath, item in cell.accessories = [.disclosureIndicator()] var content = cell.defaultContentConfiguration() content.text = item.title content.secondaryText = item.subtitle content.secondaryTextProperties.color = .secondaryLabel cell.contentConfiguration = content } }() func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { MenuItem.allExamples.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = MenuItem.allExamples[indexPath.item] return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item) } func collectionView(_ collectionView: UICollectionView, performPrimaryActionForItemAt indexPath: IndexPath) { let item = MenuItem.allExamples[indexPath.item] let viewController = item.viewControllerProvider() navigationController?.pushViewController(viewController, animated: true) } } ``` ## SceneDelegate.swift ```swift /* Abstract: The scene delegate. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { } } ``` ## BubbleLayoutFragment.swift ```swift /* Abstract: NSTextLayoutFragment subclass to draw the comment bubble. */ #if os(iOS) import UIKit #else import Cocoa #endif import CoreGraphics class BubbleLayoutFragment: NSTextLayoutFragment { var commentDepth: UInt = 0 override var leadingPadding: CGFloat { return 20.0 * CGFloat(commentDepth) } override var trailingPadding: CGFloat { return 50 } override var topMargin: CGFloat { return 6 } override var bottomMargin: CGFloat { return 6 } private var tightTextBounds: CGRect { var fragmentTextBounds = CGRect.null for lineFragment in textLineFragments { let lineFragmentBounds = lineFragment.typographicBounds if fragmentTextBounds.isNull { fragmentTextBounds = lineFragmentBounds } else { fragmentTextBounds = fragmentTextBounds.union(lineFragmentBounds) } } return fragmentTextBounds } // Return the bounding rect of the chat bubble, in the space of the first line fragment. private var bubbleRect: CGRect { return tightTextBounds.insetBy(dx: -3, dy: -3) } private var bubbleCornerRadius: CGFloat { return 20 } private var bubbleColor: Color { return .systemIndigo } private func createBubblePath(with ctx: CGContext) -> CGPath { let bubbleRect = self.bubbleRect let rect = min(bubbleCornerRadius, bubbleRect.size.height / 2, bubbleRect.size.width / 2) return CGPath(roundedRect: bubbleRect, cornerWidth: rect, cornerHeight: rect, transform: nil) } override var renderingSurfaceBounds: CGRect { return bubbleRect.union(super.renderingSurfaceBounds) } override func draw(at renderingOrigin: CGPoint, in ctx: CGContext) { // Draw the bubble and debug outline. ctx.saveGState() let bubblePath = createBubblePath(with: ctx) ctx.addPath(bubblePath) ctx.setFillColor(bubbleColor.cgColor) ctx.fillPath() ctx.restoreGState() // Draw the text on top. super.draw(at: renderingOrigin, in: ctx) } } ``` ## CommentUtils.swift ```swift /* Abstract: Reaction button symbol names and accessibility labels. */ import Foundation extension NSAttributedString.Key { public static var commentDepth: NSAttributedString.Key { return NSAttributedString.Key("TK2DemoCommentDepth") } } enum Reaction: Int, CaseIterable { case none = 0, thumbsUp, smilingFace, questionMark, thumbsDown var symbolName: String { switch self { case .thumbsUp: return "hand.thumbsup.fill" case .smilingFace: return "face.smiling.fill" case .questionMark: return "questionmark.circle.fill" case .thumbsDown: return "hand.thumbsdown.fill" default: return "" } } var accessibilityLabel: String { switch self { case .thumbsUp: return "Thumbs Up Reaction" case .smilingFace: return "Smiling Face Reaction" case .questionMark: return "Question Mark Reaction" case .thumbsDown: return "Thumbs Down Reaction" default: return "" } } } ``` ## TextLayoutFragmentLayer.swift ```swift /* Abstract: CALayer subclass to draw the outline of each text layout fragment. */ #if os(iOS) import UIKit typealias Color = UIColor #else import Cocoa typealias Color = NSColor #endif import CoreGraphics class TextLayoutFragmentLayer: CALayer { var layoutFragment: NSTextLayoutFragment! var padding: CGFloat var showLayerFrames: Bool let strokeWidth: CGFloat = 2 override class func defaultAction(forKey: String) -> CAAction? { // Suppress default opacity animations. return NSNull() } func updateGeometry() { bounds = layoutFragment.renderingSurfaceBounds if showLayerFrames { var typographicBounds = layoutFragment.layoutFragmentFrame typographicBounds.origin = .zero bounds = bounds.union(typographicBounds) } // The (0, 0) point in layer space should be the anchor point. anchorPoint = CGPoint(x: -bounds.origin.x / bounds.size.width, y: -bounds.origin.y / bounds.size.height) position = layoutFragment.layoutFragmentFrame.origin var newBounds = bounds // On macOS 14 and iOS 17, NSTextLayoutFragment.renderingSurfaceBounds is properly relative to the NSTextLayoutFragment's // interior coordinate system, and so this sample no longer needs the inconsistent x origin adjustment. if #unavailable(iOS 17, macOS 14) { newBounds.origin.x += position.x } bounds = newBounds position.x += padding } init(layoutFragment: NSTextLayoutFragment, padding: CGFloat) { self.layoutFragment = layoutFragment self.padding = padding showLayerFrames = false super.init() contentsScale = 2 updateGeometry() setNeedsDisplay() } override init(layer: Any) { guard let tlfLayer = layer as? TextLayoutFragmentLayer else { fatalError("The type of `layer` needs to be TextLayoutFragmentLayer.") } layoutFragment = tlfLayer.layoutFragment padding = tlfLayer.padding showLayerFrames = tlfLayer.showLayerFrames super.init(layer: layer) updateGeometry() setNeedsDisplay() } required init?(coder: NSCoder) { layoutFragment = nil padding = 0 showLayerFrames = false super.init(coder: coder) } override func draw(in ctx: CGContext) { layoutFragment.draw(at: .zero, in: ctx) if showLayerFrames { let inset = 0.5 * strokeWidth // Draw rendering surface bounds. ctx.setLineWidth(strokeWidth) ctx.setStrokeColor(renderingSurfaceBoundsStrokeColor.cgColor) ctx.setLineDash(phase: 0, lengths: []) // Solid line. ctx.stroke(layoutFragment.renderingSurfaceBounds.insetBy(dx: inset, dy: inset)) // Draw typographic bounds. ctx.setStrokeColor(typographicBoundsStrokeColor.cgColor) ctx.setLineDash(phase: 0, lengths: [strokeWidth, strokeWidth]) // Square dashes. var typographicBounds = layoutFragment.layoutFragmentFrame typographicBounds.origin = .zero ctx.stroke(typographicBounds.insetBy(dx: inset, dy: inset)) } } var renderingSurfaceBoundsStrokeColor: Color { return .systemOrange } var typographicBoundsStrokeColor: Color { return .systemPurple } } ``` ## AppDelegate.swift ```swift /* Abstract: The application-specific delegate class. */ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called by iOS when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called by iOS when the user discards a scene session. // If any sessions were discarded while the application was not running, // this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } } ``` ## CommentPopoverViewController.swift ```swift /* Abstract: UIViewController subclass that contains the content for the comment popover. */ import UIKit class CommentPopoverViewController: UIViewController, UITextFieldDelegate { private var selectedReaction: Reaction = .thumbsUp var viewController: TextDocumentViewController! = nil @IBOutlet private var commentField: UITextField! override func viewDidLoad() { super.viewDidLoad() overrideUserInterfaceStyle = .light commentField.delegate = self commentField.becomeFirstResponder() // This is called when a reaction button needs an update. let buttonUpdateHandler: (UIButton) -> Void = { button in button.configuration?.baseBackgroundColor = button.isSelected ? UIColor.systemIndigo : UIColor.gray } // Add a configuration update handler to each reaction button. for reaction in Reaction.allCases { if let button = buttonForReaction(reaction) { button.configurationUpdateHandler = buttonUpdateHandler } } if let selectedReactionButton = buttonForReaction(selectedReaction) { selectedReactionButton.isSelected = true } } private let reactionAttachmentColor = UIColor.systemYellow private func imageForAttachment(with reaction: Reaction) -> UIImage { let reactionConfig = UIImage.SymbolConfiguration(textStyle: .title3, scale: .large) var symbolImageForReaction = UIImage(systemName: reaction.symbolName, withConfiguration: reactionConfig) symbolImageForReaction = symbolImageForReaction!.withRenderingMode(.alwaysTemplate) return symbolImageForReaction! } func attributedString(for reaction: Reaction) -> NSAttributedString { let reactionAttachment = NSTextAttachment() reactionAttachment.image = imageForAttachment(with: reaction) let reactionAttachmentString = NSMutableAttributedString(attachment: reactionAttachment) // Add the foreground color attribute so the symbol icon renders with the reactionAttachmentColor (yellow). reactionAttachmentString.addAttribute(.foregroundColor, value: reactionAttachmentColor, range: NSRange(location: 0, length: reactionAttachmentString.length)) return reactionAttachmentString } // Creating the comment. func attributedComment(_ comment: String, with reaction: Reaction) -> NSAttributedString { let reactionAttachmentString = attributedString(for: reaction) let commentWithReaction = NSMutableAttributedString(string: comment + " ") commentWithReaction.append(reactionAttachmentString) return commentWithReaction } @IBAction func reactionChanged(_ sender: UIButton) { let newReaction = Reaction(rawValue: sender.tag) let oldReaction = selectedReaction let newReactionButton = sender if newReaction != oldReaction { newReactionButton.isSelected = true if let oldReactionButton = buttonForReaction(oldReaction) { // Toggle the old reaction button state. oldReactionButton.isSelected = false } selectedReaction = newReaction! } else { // User toggled the current reaction button to off. selectedReaction = .none } } func buttonForReaction(_ reaction: Reaction) -> UIButton? { if let button = view.viewWithTag(reaction.rawValue) as? UIButton { return button } else { return nil } } var selectedReactionButtonColor: UIColor { return UIColor.systemIndigo } var unselectedReactionButtonColor: UIColor { return UIColor.systemGray } // MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if !textField.text!.isEmpty && selectedReaction != .none { textField.resignFirstResponder() dismiss(animated: true, completion: { [self] in let attributedCommentWithReaction = attributedComment(textField.text!, with: selectedReaction) viewController.addComment(comment: attributedCommentWithReaction) }) return true } else { return false } } } ``` ## SceneDelegate.swift ```swift /* Abstract: The application's UIWindowScene subclass for managing its window. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { //.. } } ``` ## TextDocumentView.swift ```swift /* Abstract: The application's primary view for managing text. */ import UIKit class TextDocumentLayer: CALayer { override class func defaultAction(forKey event: String) -> CAAction? { // Suppress default animation of opacity when adding comment bubbles. return NSNull() } } class TextDocumentView: UIScrollView, NSTextViewportLayoutControllerDelegate, NSTextLayoutManagerDelegate, UIGestureRecognizerDelegate { let selectionColor = UIColor.systemBlue let caretColor = UIColor.tintColor // MARK: - NSTextViewportLayoutControllerDelegate func viewportBounds(for textViewportLayoutController: NSTextViewportLayoutController) -> CGRect { var rect = CGRect() rect.size = contentSize rect.origin = contentOffset return rect } func viewportAnchor() -> CGPoint { return CGPoint() } func textViewportLayoutControllerWillLayout(_ controller: NSTextViewportLayoutController) { contentLayer.sublayers = nil CATransaction.begin() } private func animate(_ layer: CALayer, from source: CGPoint, to destination: CGPoint) { let animation = CABasicAnimation(keyPath: "position") animation.fromValue = source animation.toValue = destination animation.duration = slowAnimations ? 2.0 : 0.3 layer.add(animation, forKey: nil) } private func findOrCreateLayer(_ textLayoutFragment: NSTextLayoutFragment) -> (TextLayoutFragmentLayer, Bool) { if let layer = fragmentLayerMap.object(forKey: textLayoutFragment) as? TextLayoutFragmentLayer { return (layer, false) } else { let layer = TextLayoutFragmentLayer(layoutFragment: textLayoutFragment, padding: padding) fragmentLayerMap.setObject(layer, forKey: textLayoutFragment) return (layer, true) } } func textViewportLayoutController(_ textViewportLayoutController: NSTextViewportLayoutController, configureRenderingSurfaceFor textLayoutFragment: NSTextLayoutFragment) { let (textLayoutFragmentLayer, didCreate) = findOrCreateLayer(textLayoutFragment) if !didCreate { let oldPosition = textLayoutFragmentLayer.position let oldBounds = textLayoutFragmentLayer.bounds textLayoutFragmentLayer.updateGeometry() if oldBounds != textLayoutFragmentLayer.bounds { textLayoutFragmentLayer.setNeedsDisplay() } if oldPosition != layer.position { animate(textLayoutFragmentLayer, from: oldPosition, to: textLayoutFragmentLayer.position) } } contentLayer.addSublayer(textLayoutFragmentLayer) } func textViewportLayoutControllerDidLayout(_ controller: NSTextViewportLayoutController) { CATransaction.commit() updateSelectionHighlights() updateContentSizeIfNeeded() adjustViewportOffsetIfNeeded() } private func adjustViewportOffsetIfNeeded() { let viewportLayoutController = textLayoutManager!.textViewportLayoutController let contentOffset = bounds.minY if contentOffset < bounds.height && viewportLayoutController.viewportRange!.location.compare(textLayoutManager!.documentRange.location) == .orderedDescending { // Nearing top, see if we need to adjust and make room above. adjustViewportOffset() } else if viewportLayoutController.viewportRange!.location.compare(textLayoutManager!.documentRange.location) == .orderedSame { // At top, see if we need to adjust and reduce space above. adjustViewportOffset() } } private func adjustViewportOffset() { let viewportLayoutController = textLayoutManager!.textViewportLayoutController var layoutYPoint: CGFloat = 0 textLayoutManager!.enumerateTextLayoutFragments(from: viewportLayoutController.viewportRange!.location, options: [.reverse, .ensuresLayout]) { layoutFragment in layoutYPoint = layoutFragment.layoutFragmentFrame.origin.y return true } if layoutYPoint != 0 { let adjustmentDelta = bounds.minY - layoutYPoint viewportLayoutController.adjustViewport(byVerticalOffset: adjustmentDelta) let point = CGPoint(x: self.contentOffset.x, y: self.contentOffset.y + adjustmentDelta) setContentOffset(point, animated: true) } } private func updateSelectionHighlights() { if !textLayoutManager!.textSelections.isEmpty { selectionLayer.sublayers = nil for textSelection in textLayoutManager!.textSelections { for textRange in textSelection.textRanges { textLayoutManager!.enumerateTextSegments(in: textRange, type: .highlight, options: []) {(textSegmentRange, textSegmentFrame, baselinePosition, textContainer) in var highlightFrame = textSegmentFrame highlightFrame.origin.x += padding let highlight = TextDocumentLayer() if highlightFrame.size.width > 0 { highlight.backgroundColor = selectionColor.cgColor } else { highlightFrame.size.width = 1 // Fatten up the cursor. highlight.backgroundColor = caretColor.cgColor } highlight.frame = highlightFrame selectionLayer.addSublayer(highlight) return true // Keep going. } } } } } private var contentLayer: CALayer! = nil private var selectionLayer: CALayer! = nil private var fragmentLayerMap: NSMapTable<NSTextLayoutFragment, CALayer> private var padding: CGFloat = 5.0 var textLayoutManager: NSTextLayoutManager? { willSet { if let tlm = textLayoutManager { tlm.delegate = nil tlm.textViewportLayoutController.delegate = nil } } didSet { if let tlm = textLayoutManager { tlm.delegate = self tlm.textViewportLayoutController.delegate = self } updateContentSizeIfNeeded() updateTextContainerSize() layer.setNeedsLayout() } } var textContentStorage: NSTextContentStorage! override func layoutSublayers(of layer: CALayer) { assert(layer == self.layer) textLayoutManager?.textViewportLayoutController.layoutViewport() updateContentSizeIfNeeded() } @IBOutlet var viewController: TextDocumentViewController! var showLayerFrames: Bool = false var slowAnimations: Bool = false private func updateTextContainerSize() { let textContainer = textLayoutManager!.textContainer if textContainer != nil && textContainer!.size.width != bounds.width { textContainer!.size = CGSize(width: bounds.size.width, height: 0) layer.setNeedsLayout() } } override init(frame: CGRect) { fragmentLayerMap = .weakToWeakObjects() super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { fragmentLayerMap = .weakToWeakObjects() super.init(coder: coder) commonInit() } private func commonInit() { layer.backgroundColor = UIColor.white.cgColor selectionLayer = TextDocumentLayer() contentLayer = TextDocumentLayer() layer.addSublayer(selectionLayer) layer.addSublayer(contentLayer) fragmentLayerMap = NSMapTable.weakToWeakObjects() padding = 5.0 translatesAutoresizingMaskIntoConstraints = false addLongPressGestureRecognizer() } func updateContentSizeIfNeeded() { let currentHeight = bounds.height var height: CGFloat = 0 textLayoutManager!.enumerateTextLayoutFragments(from: textLayoutManager!.documentRange.endLocation, options: [.reverse, .ensuresLayout]) { layoutFragment in height = layoutFragment.layoutFragmentFrame.maxY return false // stop } height = max(height, contentSize.height) if abs(currentHeight - height) > 1e-10 { let contentSize = CGSize(width: self.bounds.width, height: height) self.contentSize = contentSize } } func addComment(_ comment: NSAttributedString, below parentFragment: NSTextLayoutFragment) { guard let fragmentParagraph = parentFragment.textElement as? NSTextParagraph else { return } if let fragmentDepthValue = fragmentParagraph.attributedString.attribute(.commentDepth, at: 0, effectiveRange: nil) as? NSNumber? { let fragmentDepth = fragmentDepthValue?.uintValue ?? 0 let commentWithNewline = NSMutableAttributedString(attributedString: comment) commentWithNewline.append(NSAttributedString(string: "\n")) // Apply our comment attribute to the entire range. commentWithNewline.addAttribute(.commentDepth, value: NSNumber(value: fragmentDepth + 1), range: NSRange(location: 0, length: commentWithNewline.length)) let insertLocation = parentFragment.rangeInElement.endLocation let insertIndex = textLayoutManager!.offset(from: textLayoutManager!.documentRange.location, to: insertLocation) textContentStorage!.performEditingTransaction { textContentStorage!.textStorage?.insert(commentWithNewline, at: insertIndex) } layer.setNeedsLayout() } } // MARK: - NSTextLayoutManagerDelegate func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement) -> NSTextLayoutFragment { let index = textLayoutManager.offset(from: textLayoutManager.documentRange.location, to: location) let commentDepthValue = textContentStorage!.textStorage!.attribute(.commentDepth, at: index, effectiveRange: nil) as! NSNumber? if commentDepthValue != nil { let layoutFragment = BubbleLayoutFragment(textElement: textElement, range: textElement.elementRange) layoutFragment.commentDepth = commentDepthValue!.uintValue return layoutFragment } else { return NSTextLayoutFragment(textElement: textElement, range: textElement.elementRange) } } // MARK: - Long Press Gesture Recognizer func addLongPressGestureRecognizer() { let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:))) addGestureRecognizer(longPressGestureRecognizer) } @objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { guard gestureRecognizer.state == .began else { return } var longPressPoint = gestureRecognizer.location(in: self) longPressPoint.x -= padding if let layoutFragment = textLayoutManager!.textLayoutFragment(for: longPressPoint) { viewController.showCommentPopoverForLayoutFragment(layoutFragment) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } ``` ## TextDocumentViewController.swift ```swift /* Abstract: The application's primary view controller. */ import UIKit class TextDocumentViewController: UIViewController, NSTextContentManagerDelegate, NSTextContentStorageDelegate, UIPopoverPresentationControllerDelegate { private var textContentStorage: NSTextContentStorage private var textLayoutManager: NSTextLayoutManager private var fragmentForCurrentComment: NSTextLayoutFragment? private var showComments = true var commentColor: UIColor { return .white } @IBOutlet var toggleComments: UIButton! var textDocumentView: TextDocumentView { get { return (view as? TextDocumentView)! } } required init?(coder: NSCoder) { textLayoutManager = NSTextLayoutManager() textContentStorage = NSTextContentStorage() super.init(coder: coder) textContentStorage.delegate = self textContentStorage.addTextLayoutManager(textLayoutManager) let textContainer = NSTextContainer(size: CGSize(width: 200, height: 0)) textLayoutManager.textContainer = textContainer } override func viewDidLoad() { super.viewDidLoad() if let docURL = Bundle.main.url(forResource: "menu", withExtension: "rtf") { do { try textContentStorage.textStorage?.read(from: docURL, documentAttributes: nil) } catch { // Could not read menu content. } } // This is called when the toggle comment button needs an update. let toggleUpdateHandler: (UIButton) -> Void = { [self] button in button.configuration?.image = button.isSelected ? UIImage(systemName: "text.bubble.fill") : UIImage(systemName: "text.bubble") self.showComments = button.isSelected textDocumentView.layer.setNeedsLayout() } toggleComments.configurationUpdateHandler = toggleUpdateHandler textDocumentView.textContentStorage = textContentStorage textDocumentView.textLayoutManager = textLayoutManager textDocumentView.updateContentSizeIfNeeded() textDocumentView.viewController = self } // Commenting var commentFont: UIFont { var commentFont = UIFont.preferredFont(forTextStyle: .title3) let commentFontDescriptor = commentFont.fontDescriptor.withSymbolicTraits(.traitItalic) commentFont = UIFont(descriptor: commentFontDescriptor!, size: commentFont.pointSize) return commentFont } func addComment(comment: NSAttributedString) { textDocumentView.addComment(comment, below: fragmentForCurrentComment!) fragmentForCurrentComment = nil } // MARK: - NSTextContentManagerDelegate func textContentManager(_ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions) -> Bool { // The text content manager calls this method to determine whether each text element should be enumerated for layout. // To hide comments, tell the text content manager not to enumerate this element if it's a comment. if !showComments { if let paragraph = textElement as? NSTextParagraph { let commentDepthValue = paragraph.attributedString.attribute(.commentDepth, at: 0, effectiveRange: nil) if commentDepthValue != nil { return false } } } return true } // MARK: - NSTextContentStorageDelegate func textContentStorage(_ textContentStorage: NSTextContentStorage, textParagraphWith range: NSRange) -> NSTextParagraph? { // In this method, we'll inject some attributes for display, without modifying the text storage directly. var paragraphWithDisplayAttributes: NSTextParagraph? = nil // First, get a copy of the paragraph from the original text storage. let originalText = textContentStorage.textStorage!.attributedSubstring(from: range) if originalText.attribute(.commentDepth, at: 0, effectiveRange: nil) != nil { // Use white colored text to make our comments visible against the bright background. let displayAttributes: [NSAttributedString.Key: AnyObject] = [.font: commentFont, .foregroundColor: commentColor] let textWithDisplayAttributes = NSMutableAttributedString(attributedString: originalText) // Use the display attributes for the text of the comment itself, without the reaction. // The last character is the newline, second to last is the attachment character for the reaction. let rangeForDisplayAttributes = NSRange(location: 0, length: textWithDisplayAttributes.length - 2) textWithDisplayAttributes.addAttributes(displayAttributes, range: rangeForDisplayAttributes) // Create our new paragraph with our display attributes. paragraphWithDisplayAttributes = NSTextParagraph(attributedString: textWithDisplayAttributes) } else { return nil } // If the original paragraph wasn't a comment, this return value will be nil. // The text content storage will use the original paragraph in this case. return paragraphWithDisplayAttributes } // MARK: - Popover Management func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none // This makes the comment popover view controller present as a popover on iPhone. } func showCommentPopoverForLayoutFragment(_ layoutFragment: NSTextLayoutFragment) { fragmentForCurrentComment = layoutFragment let storyboard = UIStoryboard(name: "Main", bundle: nil) if let popoverVC = storyboard.instantiateViewController(withIdentifier: "CommentPopoverViewController") as? CommentPopoverViewController { popoverVC.viewController = self popoverVC.modalPresentationStyle = .popover popoverVC.preferredContentSize = CGSize(width: 420.0, height: 100.0) popoverVC.popoverPresentationController!.sourceView = self.textDocumentView popoverVC.popoverPresentationController!.sourceRect = layoutFragment.layoutFragmentFrame popoverVC.popoverPresentationController!.permittedArrowDirections = .any popoverVC.popoverPresentationController!.delegate = self present(popoverVC, animated: true, completion: { //.. }) } } } ``` ## AppDelegate.swift ```swift /* Abstract: The application-specific delegate class. */ import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { //.. } func applicationWillTerminate(_ notification: Notification) { //.. } } ``` ## CommentPopoverViewController.swift ```swift /* Abstract: NSViewController subclass that contains the content for the comment popover. */ import Cocoa class CommentPopoverViewController: NSViewController, NSPopoverDelegate { var documentViewController: TextDocumentViewController! = nil @IBOutlet private var commentField: NSTextField! private var selectedReaction: Reaction = .thumbsUp private let reactionAttachmentColor = NSColor.systemYellow private func imageForAttachment(with reaction: Reaction) -> NSImage { let symbolImageForReaction = NSImage(systemSymbolName: reaction.symbolName, accessibilityDescription: reaction.accessibilityLabel)! let reactionConfig = NSImage.SymbolConfiguration(textStyle: .title3, scale: .large) return symbolImageForReaction.withSymbolConfiguration(reactionConfig)! } func attributedString(for reaction: Reaction) -> NSAttributedString { let reactionAttachment = NSTextAttachment() reactionAttachment.image = imageForAttachment(with: reaction) let reactionAttachmentString = NSMutableAttributedString(attachment: reactionAttachment) // Add the foreground color attribute so the symbol icon renders with the reactionAttachmentColor (yellow). reactionAttachmentString.addAttribute(.foregroundColor, value: reactionAttachmentColor, range: NSRange(location: 0, length: reactionAttachmentString.length)) return reactionAttachmentString } // Creating the comment. func attributedComment(_ comment: String, with reaction: Reaction) -> NSAttributedString { let reactionAttachmentString = attributedString(for: reaction) let commentWithReaction = NSMutableAttributedString(string: comment + " ") commentWithReaction.append(reactionAttachmentString) return commentWithReaction } // Text field handling, the user typed return or enter. @IBAction func returnPressed(_ sender: Any) { if !commentField.stringValue.isEmpty && selectedReaction != .none { let attributedCommentWithReaction = attributedComment(commentField.stringValue, with: selectedReaction) documentViewController.addComment(attributedCommentWithReaction) commentField.resignFirstResponder() dismiss(self) } else { // The comment data is not fully determined. } } func buttonForReaction(_ reaction: Reaction) -> NSButton? { if let button = view.viewWithTag(reaction.rawValue) as? NSButton { return button } else { return nil } } // Reaction button handling. @IBAction func reactionChanged(_ sender: NSButton) { let newReaction = Reaction(rawValue: sender.tag) let oldReaction = selectedReaction if newReaction != oldReaction { if let oldReactionButton = buttonForReaction(oldReaction) { // Toggle the old reaction button state. oldReactionButton.state = .off } selectedReaction = newReaction! } else { // User toggled the current reaction button to off. selectedReaction = .none } } } ``` ## Document.swift ```swift /* Abstract: NSDocument subclass for this sample. */ import Cocoa class Document: NSDocument { override class var autosavesInPlace: Bool { return true } override func makeWindowControllers() { let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) if let windowController = storyboard.instantiateController( withIdentifier: NSStoryboard.SceneIdentifier("DocumentWindowController")) as? NSWindowController { addWindowController(windowController) } } } ``` ## ReactionButton.swift ```swift /* Abstract: NSButton subclass used in the comment popover for selecting a reaction. */ import Cocoa class ReactionButton: NSButton { private let selectedReactionColor = NSColor.systemIndigo private let unselectedReactionColor = NSColor.systemGray override func awakeFromNib() { super.awakeFromNib() // The button's image should retain its tint color even in off state. if let reactionButtonCell = cell as? NSButtonCell { reactionButtonCell.showsStateBy = [] reactionButtonCell.highlightsBy = [] } } override func draw(_ dirtyRect: NSRect) { if let reactionButtonCell = cell as? NSButtonCell { super.draw(dirtyRect) let cornerRadius = frame.height / 2.0 let roundedPath = NSBezierPath(roundedRect: bounds, xRadius: cornerRadius, yRadius: cornerRadius) let fillColor = (state == .on) ? selectedReactionColor : unselectedReactionColor fillColor.set() roundedPath.fill() reactionButtonCell.drawImage(image!, withFrame: bounds, in: self) } } } ``` ## TextDocumentView.swift ```swift /* Abstract: NSView subclass for managing text in the app's document. */ import Cocoa class TextDocumentLayer: CALayer { override class func defaultAction(forKey event: String) -> CAAction? { // Suppress default animation of opacity when adding comment bubbles. return NSNull() } } class TextDocumentView: NSView, CALayerDelegate, NSTextViewportLayoutControllerDelegate, NSTextLayoutManagerDelegate { var textLayoutManager: NSTextLayoutManager? { willSet { if let tlm = textLayoutManager { tlm.delegate = nil tlm.textViewportLayoutController.delegate = nil } } didSet { if let tlm = textLayoutManager { tlm.delegate = self tlm.textViewportLayoutController.delegate = self } updateContentSizeIfNeeded() updateTextContainerSize() layer!.setNeedsLayout() } } var textContentStorage: NSTextContentStorage? @IBOutlet var documentViewController: TextDocumentViewController! var showLayerFrames: Bool = false var slowAnimations: Bool = false private var boundsDidChangeObserver: Any? = nil private var contentLayer: CALayer! = nil private var selectionLayer: CALayer! = nil private var fragmentLayerMap: NSMapTable<NSTextLayoutFragment, CALayer> private var padding: CGFloat = 5.0 override init(frame: CGRect) { fragmentLayerMap = .weakToWeakObjects() super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { fragmentLayerMap = .weakToWeakObjects() super.init(coder: coder) commonInit() } private func commonInit() { wantsLayer = true layer?.backgroundColor = .white selectionLayer = TextDocumentLayer() contentLayer = TextDocumentLayer() layer?.addSublayer(selectionLayer) layer?.addSublayer(contentLayer) fragmentLayerMap = NSMapTable.weakToWeakObjects() padding = 5.0 translatesAutoresizingMaskIntoConstraints = false } deinit { if let observer = boundsDidChangeObserver { NotificationCenter.default.removeObserver(observer) } } override var isFlipped: Bool { return true } func layoutSublayers(of layer: CALayer) { assert(layer == self.layer) textLayoutManager?.textViewportLayoutController.layoutViewport() updateContentSizeIfNeeded() } // NSResponder override var acceptsFirstResponder: Bool { return true } // Responsive scrolling. override class var isCompatibleWithResponsiveScrolling: Bool { return true } override func prepareContent(in rect: NSRect) { layer!.setNeedsLayout() super.prepareContent(in: rect) } // MARK: - NSTextViewportLayoutControllerDelegate func viewportBounds(for textViewportLayoutController: NSTextViewportLayoutController) -> CGRect { let overdrawRect = preparedContentRect let visibleRect = self.visibleRect var minY: CGFloat = 0 var maxY: CGFloat = 0 if overdrawRect.intersects(visibleRect) { // Use preparedContentRect for vertical overdraw and ensure visibleRect is included at the minimum, // the width is always bounds width for proper line wrapping. minY = min(overdrawRect.minY, max(visibleRect.minY, 0)) maxY = max(overdrawRect.maxY, visibleRect.maxY) } else { // We use visible rect directly if preparedContentRect does not intersect. // This can happen if overdraw has not caught up with scrolling yet, such as before the first layout. minY = visibleRect.minY maxY = visibleRect.maxY } return CGRect(x: bounds.minX, y: minY, width: bounds.width, height: maxY - minY) } func textViewportLayoutControllerWillLayout(_ controller: NSTextViewportLayoutController) { contentLayer.sublayers = nil CATransaction.begin() } private func animate(_ layer: CALayer, from source: CGPoint, to destination: CGPoint) { let animation = CABasicAnimation(keyPath: "position") animation.fromValue = source animation.toValue = destination animation.duration = slowAnimations ? 2.0 : 0.3 layer.add(animation, forKey: nil) } private func findOrCreateLayer(_ textLayoutFragment: NSTextLayoutFragment) -> (TextLayoutFragmentLayer, Bool) { if let layer = fragmentLayerMap.object(forKey: textLayoutFragment) as? TextLayoutFragmentLayer { return (layer, false) } else { let layer = TextLayoutFragmentLayer(layoutFragment: textLayoutFragment, padding: padding) fragmentLayerMap.setObject(layer, forKey: textLayoutFragment) return (layer, true) } } func textViewportLayoutController(_ controller: NSTextViewportLayoutController, configureRenderingSurfaceFor textLayoutFragment: NSTextLayoutFragment) { let (layer, layerIsNew) = findOrCreateLayer(textLayoutFragment) if !layerIsNew { let oldPosition = layer.position let oldBounds = layer.bounds layer.updateGeometry() if oldBounds != layer.bounds { layer.setNeedsDisplay() } if oldPosition != layer.position { animate(layer, from: oldPosition, to: layer.position) } } if layer.showLayerFrames != showLayerFrames { layer.showLayerFrames = showLayerFrames layer.setNeedsDisplay() } contentLayer.addSublayer(layer) } func textViewportLayoutControllerDidLayout(_ controller: NSTextViewportLayoutController) { CATransaction.commit() updateSelectionHighlights() updateContentSizeIfNeeded() adjustViewportOffsetIfNeeded() } private func updateSelectionHighlights() { if !textLayoutManager!.textSelections.isEmpty { selectionLayer.sublayers = nil for textSelection in textLayoutManager!.textSelections { for textRange in textSelection.textRanges { textLayoutManager!.enumerateTextSegments(in: textRange, type: .highlight, options: []) {(textSegmentRange, textSegmentFrame, baselinePosition, textContainer) in var highlightFrame = textSegmentFrame highlightFrame.origin.x += padding let highlight = TextDocumentLayer() if highlightFrame.size.width > 0 { highlight.backgroundColor = selectionColor.cgColor } else { highlightFrame.size.width = 1 // fatten up the cursor highlight.backgroundColor = caretColor.cgColor } highlight.frame = highlightFrame selectionLayer.addSublayer(highlight) return true // keep going } } } } } // Colors support. var selectionColor: NSColor { return .selectedTextBackgroundColor } var caretColor: NSColor { return .black } // Live resize. override func viewDidEndLiveResize() { super.viewDidEndLiveResize() adjustViewportOffsetIfNeeded() updateContentSizeIfNeeded() } // Scroll view support. private var scrollView: NSScrollView? { guard let result = enclosingScrollView else { return nil } if result.documentView == self { return result } else { return nil } } func updateContentSizeIfNeeded() { let currentHeight = bounds.height var height: CGFloat = 0 textLayoutManager!.enumerateTextLayoutFragments(from: textLayoutManager!.documentRange.endLocation, options: [.reverse, .ensuresLayout]) { layoutFragment in height = layoutFragment.layoutFragmentFrame.maxY return false // stop } height = max(height, enclosingScrollView?.contentSize.height ?? 0) if abs(currentHeight - height) > 1e-10 { let contentSize = NSSize(width: self.bounds.width, height: height) setFrameSize(contentSize) } } private func adjustViewportOffsetIfNeeded() { let viewportLayoutController = textLayoutManager!.textViewportLayoutController let contentOffset = scrollView!.contentView.bounds.minY if contentOffset < scrollView!.contentView.bounds.height && viewportLayoutController.viewportRange!.location.compare(textLayoutManager!.documentRange.location) == .orderedDescending { // Nearing top, see if we need to adjust and make room above. adjustViewportOffset() } else if viewportLayoutController.viewportRange!.location.compare(textLayoutManager!.documentRange.location) == .orderedSame { // At top, see if we need to adjust and reduce space above. adjustViewportOffset() } } private func adjustViewportOffset() { let viewportLayoutController = textLayoutManager!.textViewportLayoutController var layoutYPoint: CGFloat = 0 textLayoutManager!.enumerateTextLayoutFragments(from: viewportLayoutController.viewportRange!.location, options: [.reverse, .ensuresLayout]) { layoutFragment in layoutYPoint = layoutFragment.layoutFragmentFrame.origin.y return true } if layoutYPoint != 0 { let adjustmentDelta = bounds.minY - layoutYPoint viewportLayoutController.adjustViewport(byVerticalOffset: adjustmentDelta) scroll(CGPoint(x: scrollView!.contentView.bounds.minX, y: scrollView!.contentView.bounds.minY + adjustmentDelta)) } } override func viewWillMove(toSuperview newSuperview: NSView?) { let clipView = scrollView?.contentView if clipView != nil { NotificationCenter.default.removeObserver(self, name: NSView.boundsDidChangeNotification, object: clipView) } super.viewWillMove(toSuperview: newSuperview) } override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() let clipView = scrollView?.contentView if clipView != nil { boundsDidChangeObserver = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: clipView, queue: nil) { [weak self] notification in self!.layer?.setNeedsLayout() } } } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) updateTextContainerSize() } private func updateTextContainerSize() { let textContainer = textLayoutManager!.textContainer if textContainer != nil && textContainer!.size.width != bounds.width { textContainer!.size = NSSize(width: bounds.size.width, height: 0) layer?.setNeedsLayout() } } override func mouseDown(with event: NSEvent) { var point = convert(event.locationInWindow, from: nil) point.x -= padding let nav = textLayoutManager!.textSelectionNavigation textLayoutManager!.textSelections = nav.textSelections(interactingAt: point, inContainerAt: textLayoutManager!.documentRange.location, anchors: [], modifiers: [], selecting: true, bounds: .zero) layer?.setNeedsLayout() } override func mouseDragged(with event: NSEvent) { var point = convert(event.locationInWindow, from: nil) point.x -= padding let nav = textLayoutManager!.textSelectionNavigation textLayoutManager!.textSelections = nav.textSelections(interactingAt: point, inContainerAt: textLayoutManager!.documentRange.location, anchors: textLayoutManager!.textSelections, modifiers: .extend, selecting: true, bounds: .zero) layer?.setNeedsLayout() } func addComment(_ comment: NSAttributedString, below parentFragment: NSTextLayoutFragment) { guard let fragmentParagraph = parentFragment.textElement as? NSTextParagraph else { return } if let fragmentDepthValue = fragmentParagraph.attributedString.attribute(.commentDepth, at: 0, effectiveRange: nil) as? NSNumber? { let fragmentDepth = fragmentDepthValue?.uintValue ?? 0 let commentWithNewline = NSMutableAttributedString(attributedString: comment) commentWithNewline.append(NSAttributedString(string: "\n")) // Apply our comment attribute to the entire range. commentWithNewline.addAttribute(.commentDepth, value: NSNumber(value: fragmentDepth + 1), range: NSRange(location: 0, length: commentWithNewline.length)) let insertLocation = parentFragment.rangeInElement.endLocation let insertIndex = textLayoutManager!.offset(from: textLayoutManager!.documentRange.location, to: insertLocation) textContentStorage!.performEditingTransaction { textContentStorage!.textStorage?.insert(commentWithNewline, at: insertIndex) } layer?.setNeedsLayout() } } override func mouseUp(with event: NSEvent) { guard let textLayoutManager = textLayoutManager else { fatalError("textLayoutManager must not be nil") } if event.clickCount == 2 && !textLayoutManager.textSelections.isEmpty { // Double-click in the text element. let clickedLocation = textLayoutManager.textSelections[0].textRanges[0].location if let clickedFragment = textLayoutManager.textLayoutFragment(for: clickedLocation) { documentViewController.showCommentPopover(for: clickedFragment) } } } // Center Selection override func centerSelectionInVisibleArea(_ sender: Any?) { if !textLayoutManager!.textSelections.isEmpty { let viewportOffset = textLayoutManager!.textViewportLayoutController.relocateViewport(to: textLayoutManager!.textSelections[0].textRanges[0].location) scroll(CGPoint(x: 0, y: viewportOffset)) } } // MARK: - NSTextLayoutManagerDelegate func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement) -> NSTextLayoutFragment { let index = textLayoutManager.offset(from: textLayoutManager.documentRange.location, to: location) let commentDepthValue = textContentStorage!.textStorage!.attribute(.commentDepth, at: index, effectiveRange: nil) as! NSNumber? if commentDepthValue != nil { let layoutFragment = BubbleLayoutFragment(textElement: textElement, range: textElement.elementRange) layoutFragment.commentDepth = commentDepthValue!.uintValue return layoutFragment } else { return NSTextLayoutFragment(textElement: textElement, range: textElement.elementRange) } } } ``` ## TextDocumentViewController.swift ```swift /* Abstract: Primary NSViewController subclass for the sample's Document. */ import Cocoa class TextDocumentViewController: NSViewController, NSTextContentManagerDelegate, NSTextContentStorageDelegate { private var textContentStorage: NSTextContentStorage private var textLayoutManager: NSTextLayoutManager private var fragmentForCurrentComment: NSTextLayoutFragment? private var showComments = true var commentColor: NSColor { return .white } @IBOutlet private weak var textDocumentView: TextDocumentView! required init?(coder: NSCoder) { textLayoutManager = NSTextLayoutManager() textContentStorage = NSTextContentStorage() super.init(coder: coder) textContentStorage.delegate = self textContentStorage.addTextLayoutManager(textLayoutManager) let textContainer = NSTextContainer(size: NSSize(width: 200, height: 0)) textLayoutManager.textContainer = textContainer } override func viewDidLoad() { super.viewDidLoad() if textContentStorage.textStorage!.length == 0 { if let docURL = Bundle.main.url(forResource: "menu", withExtension: "rtf") { do { try textContentStorage.textStorage?.read(from: docURL, documentAttributes: nil, error: ()) } catch { // Could not read menu content. } } } textDocumentView.textContentStorage = textContentStorage textDocumentView.textLayoutManager = textLayoutManager textDocumentView.updateContentSizeIfNeeded() textDocumentView.documentViewController = self } // Commenting. @IBAction func toggleComments(_ sender: NSButton) { showComments = (sender.state == .on) textDocumentView.layer?.setNeedsLayout() } func addComment(_ comment: NSAttributedString) { textDocumentView.addComment(comment, below: fragmentForCurrentComment!) fragmentForCurrentComment = nil } var commentFont: NSFont { var commentFont = NSFont.preferredFont(forTextStyle: .title3, options: [:]) let commentFontDescriptor = commentFont.fontDescriptor.withSymbolicTraits(.italic) commentFont = NSFont(descriptor: commentFontDescriptor, size: commentFont.pointSize)! return commentFont } // Debug UI. @IBAction func toggleLayerFrames(_ sender: NSButton) { // Turn on/off viewing layer frames. textDocumentView.showLayerFrames = (sender.state == .on) textDocumentView.layer?.setNeedsLayout() } @IBAction func toggleSlowAnimation(_ sender: NSButton) { // Turn on/off slow animation of each layer. textDocumentView.slowAnimations = (sender.state == .on) } // Popover management. func showCommentPopover(for layoutFragment: NSTextLayoutFragment) { fragmentForCurrentComment = layoutFragment let storyboard = NSStoryboard(name: "Main", bundle: nil) if let popoverVC = storyboard.instantiateController(withIdentifier: "CommentPopoverViewController") as? CommentPopoverViewController { popoverVC.documentViewController = self present(popoverVC, asPopoverRelativeTo: layoutFragment.layoutFragmentFrame, of: textDocumentView, preferredEdge: .maxY, behavior: .transient) } } // MARK: - NSTextContentManagerDelegate func textContentManager(_ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions) -> Bool { // The text content manager calls this method to determine whether each text element should be enumerated for layout. // To hide comments, tell the text content manager not to enumerate this element if it's a comment. if !showComments { if let paragraph = textElement as? NSTextParagraph { let commentDepthValue = paragraph.attributedString.attribute(.commentDepth, at: 0, effectiveRange: nil) if commentDepthValue != nil { return false } } } return true } // MARK: - NSTextContentStorageDelegate func textContentStorage(_ textContentStorage: NSTextContentStorage, textParagraphWith range: NSRange) -> NSTextParagraph? { // In this method, we'll inject some attributes for display, without modifying the text storage directly. var paragraphWithDisplayAttributes: NSTextParagraph? = nil // First, get a copy of the paragraph from the original text storage. let originalText = textContentStorage.textStorage!.attributedSubstring(from: range) if originalText.attribute(.commentDepth, at: 0, effectiveRange: nil) != nil { // Use white colored text to make our comments visible against the bright background. let displayAttributes: [NSAttributedString.Key: AnyObject] = [.font: commentFont, .foregroundColor: commentColor] let textWithDisplayAttributes = NSMutableAttributedString(attributedString: originalText) // Use the display attributes for the text of the comment itself, without the reaction. // The last character is the newline, second to last is the attachment character for the reaction. let rangeForDisplayAttributes = NSRange(location: 0, length: textWithDisplayAttributes.length - 2) textWithDisplayAttributes.addAttributes(displayAttributes, range: rangeForDisplayAttributes) // Create our new paragraph with our display attributes. paragraphWithDisplayAttributes = NSTextParagraph(attributedString: textWithDisplayAttributes) } else { return nil } // If the original paragraph wasn't a comment, this return value will be nil. // The text content storage will use the original paragraph in this case. return paragraphWithDisplayAttributes } } ``` ## WindowController.swift ```swift /* Abstract: The main window controller for this sample. */ import Cocoa class WindowController: NSWindowController, NSWindowDelegate { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // NSWindows loaded from the storyboard will be cascaded based on the original frame of the window in the storyboard. shouldCascadeWindows = true } override func windowTitle(forDocumentDisplayName displayName: String) -> String { return "Layout Text with TextKit 2" } } ```
swift-master/Maps/Maps/CitiesViewController.swift
// // CitiesViewController.swift // Maps // // Created by Horacio Garza on 27/08/16. // import Foundation import UIKit import KVNProgress import Alamofire import SwiftyJSON class CitiesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let paises = ["Mexico", "Australia", "Germany", "Peru", "Venezuela", "Spain", "Argentina", "China", "Japan", "North Korea"] var cellTitle: String! override func viewDidLoad() { super.viewDidLoad() KVNProgress.showErrorWithStatus("Listo prro") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segue_to_map" { let vc = segue.destinationViewController as? MapViewController vc?.latitude = Double(arc4random_uniform(100) + 10) vc?.longitude = Double(arc4random_uniform(100) + 10) vc?.annotationTitle = self.cellTitle } } // MARK: Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Ciudades Nacionales" : "Ciudades Internacionales" } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 10 : 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell: UITableViewCell = UITableViewCell() cell.textLabel?.text = "\(indexPath.section.description) - \(indexPath.row.description)" //paises[indexPath.row] return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("Custom") (cell?.viewWithTag(100) as? UILabel)?.text = "\(indexPath.section.description) - \(indexPath.row.description)" //paises[indexPath.row] return cell! } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return 48 } else { return 300 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) self.cellTitle = (cell?.viewWithTag(100) as? UILabel)?.text self.performSegueWithIdentifier("segue_to_map", sender: nil) } }
swift-master/Maps/Maps/ViewController.swift
// // ViewController.swift // Maps // // Created by Horacio Garza on 20/08/16. // import UIKit import Alamofire import SwiftyJSON import KVNProgress import Squeal class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtBirthday: UITextField! @IBOutlet weak var viewBirthday: UIView! @IBOutlet weak var datePicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.txtEmail.delegate = self //Abre la vista self.viewBirthday.removeFromSuperview() self.txtBirthday.inputView = self.viewBirthday let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let currentDate = NSDate() let dateComponents = NSDateComponents() dateComponents.year = -13 let minDate = calendar!.dateByAddingComponents(dateComponents, toDate: currentDate, options: NSCalendarOptions(rawValue: 0)) self.datePicker.minimumDate = minDate KVNProgress.showWithStatus("Loading") Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .responseJSON { response in /*print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization*/ if response.result.isSuccess { KVNProgress.showWithStatus("Creating DB") do { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let path = paths[0] let db = try Database(path: "\(path)contacts.db") try db.createTable("requests", definitions: [ "id INTEGER PRIMARY KEY", "parameter TEXT", "VALUE TEXT"], ifNotExists: true) let json = JSON(response.result.value!) print(json) for index in 0 ..< json["args"].count { _ = try db.insertInto("requests", values: [ "id": index, "parameter": String(json["args"]["foo"]) ]) } print(try db.countFrom("requests").description) let results = try db.prepareSelectFrom("requests", whereExpr: "id = ?", parameters: ["0"]) while try results.next() { print(results.stringValue("parameter")!) } } catch let error as NSError { print(error.localizedDescription) } KVNProgress.dismiss() } else { KVNProgress.showErrorWithStatus(response.result.error?.localizedDescription) } } } @IBAction func datePickerValueChanged(sender: UIDatePicker) { let date: NSDateFormatter = NSDateFormatter() date.dateStyle = NSDateFormatterStyle.ShortStyle date.timeStyle = NSDateFormatterStyle.NoStyle let dateString = date.stringFromDate(sender.date) self.txtBirthday.text = dateString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func closeBirthdayPicker(sender: AnyObject) { self.txtBirthday.resignFirstResponder() } func textFieldDidBeginEditing(textField: UITextField) { if textField == self.txtEmail { print("Empezando a editar email") } else { let txtP: UITextField = self.view.viewWithTag(10) as! UITextField if textField == txtP { print("Empezando a editar email") } } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == txtEmail { (self.view.viewWithTag(10) as! UITextField).becomeFirstResponder() } else { self.view.endEditing(true) } return true } // MARK: @IBAction func onOutsideTap(sender: AnyObject) { self.view.endEditing(true) } }
swift-master/Maps/Maps/MapViewController.swift
// // MapViewController.swift // Maps // // Created by Horacio Garza on 27/08/16. // import UIKit import Foundation import MapKit class MapViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! var latitude: Double! var longitude: Double! var annotationTitle: String! var locationManager: CLLocationManager! @IBOutlet weak var lblLocation: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.requestWhenInUseAuthorization() if (CLLocationManager.locationServicesEnabled()) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } let location = CLLocationCoordinate2D( latitude: self.latitude, longitude: self.longitude ) let span = MKCoordinateSpanMake(0.5, 0.5) let region = MKCoordinateRegion(center: location, span: span) self.mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = self.annotationTitle annotation.subtitle = "Subtitle" self.mapView.addAnnotation(annotation) // Do any additional setup after loading the view. } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let actualCoordinates = (x: locations.last?.coordinate.latitude.description, y: locations.last?.coordinate.longitude.description) self.lblLocation.text = "\(actualCoordinates.x!) \(actualCoordinates.y!)" let location = locations.last! as CLLocation let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.mapView.setRegion(region, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
swift-master/Maps/Maps/AppDelegate.swift
// // AppDelegate.swift // Maps // // Created by Horacio Garza on 20/08/16. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/Maps/Pods/SwiftyJSON/Source/SwiftyJSON.swift
// SwiftyJSON.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type: Int { case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data: NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { error.memory = aError } self.init(NSNull()) } } /** Create a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(string: String) -> JSON { return string.dataUsingEncoding(NSUTF8StringEncoding) .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray: [JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary: [String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var rawArray: [AnyObject] = [] private var rawDictionary: [String: AnyObject] = [:] private var rawString: String = "" private var rawNumber: NSNumber = 0 private var rawNull: NSNull = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { switch self.type { case .Array: return self.rawArray case .Dictionary: return self.rawDictionary case .String: return self.rawString case .Number: return self.rawNumber case .Bool: return self.rawNumber default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } self.rawNumber = number case let string as String: _type = .String self.rawString = string case _ as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array self.rawArray = array case let dictionary as [String: AnyObject]: _type = .Dictionary self.rawDictionary = dictionary default: _type = .Unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed="null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } // MARK: - CollectionType, SequenceType, Indexable extension JSON: Swift.CollectionType, Swift.SequenceType, Swift.Indexable { public typealias Generator = JSONGenerator public typealias Index = JSONIndex public var startIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.startIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) default: return JSONIndex() } } public var endIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.endIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) default: return JSONIndex() } } public subscript (position: JSON.Index) -> JSON.Generator.Element { switch self.type { case .Array: return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) case .Dictionary: let (key, value) = self.rawDictionary[position.dictionaryIndex!] return (key, JSON(value)) default: return ("", JSON.null) } } /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `true`. public var isEmpty: Bool { get { switch self.type { case .Array: return self.rawArray.isEmpty case .Dictionary: return self.rawDictionary.isEmpty default: return true } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { switch self.type { case .Array: return self.rawArray.count case .Dictionary: return self.rawDictionary.count default: return 0 } } public func underestimateCount() -> Int { switch self.type { case .Array: return self.rawArray.underestimateCount() case .Dictionary: return self.rawDictionary.underestimateCount() default: return 0 } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of JSON. */ public func generate() -> JSON.Generator { return JSON.Generator(self) } } public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable { let arrayIndex: Int? let dictionaryIndex: DictionaryIndex<String, AnyObject>? let type: Type init() { self.arrayIndex = nil self.dictionaryIndex = nil self.type = .Unknown } init(arrayIndex: Int) { self.arrayIndex = arrayIndex self.dictionaryIndex = nil self.type = .Array } init(dictionaryIndex: DictionaryIndex<String, AnyObject>) { self.arrayIndex = nil self.dictionaryIndex = dictionaryIndex self.type = .Dictionary } public func successor() -> JSONIndex { switch self.type { case .Array: return JSONIndex(arrayIndex: self.arrayIndex!.successor()) case .Dictionary: return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor()) default: return JSONIndex() } } } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex == rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex == rhs.dictionaryIndex default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex < rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex < rhs.dictionaryIndex default: return false } } public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex <= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex <= rhs.dictionaryIndex default: return false } } public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex >= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex >= rhs.dictionaryIndex default: return false } } public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex > rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex > rhs.dictionaryIndex default: return false } } public struct JSONGenerator: GeneratorType { public typealias Element = (String, JSON) private let type: Type private var dictionayGenerate: DictionaryGenerator<String, AnyObject>? private var arrayGenerate: IndexingGenerator<[AnyObject]>? private var arrayIndex: Int = 0 init(_ json: JSON) { self.type = json.type if type == .Array { self.arrayGenerate = json.rawArray.generate() } else { self.dictionayGenerate = json.rawDictionary.generate() } } public mutating func next() -> JSONGenerator.Element? { switch self.type { case .Array: if let o = self.arrayGenerate?.next() { return (String(self.arrayIndex++), JSON(o)) } else { return nil } case .Dictionary: if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() { return (k, JSON(v)) } else { return nil } default: return nil } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case Index(Int) case Key(String) } public protocol JSONSubscriptType { var jsonKey: JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.Index(self) } } extension String: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.Key(self) } } extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code: ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .Array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .Dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .Dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .Index(let index): return self[index: index] case .Key(let key): return self[key: key] } } set { switch sub.jsonKey { case .Index(let index): self[index: index] = newValue case .Key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.removeAtIndex(0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { self.init(elements.reduce([String: AnyObject]()) {(dictionary: [String: AnyObject], element: (String, AnyObject)) -> [String: AnyObject] in var d = dictionary d[element.0] = element.1 return d }) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { guard NSJSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return self.rawString case .Number: return self.rawNumber.stringValue case .Bool: return self.rawNumber.boolValue.description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options: .PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return self.rawArray.map { JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String: JSON]? { if self.type == .Dictionary { return self.rawDictionary.reduce([String: JSON]()) { (dictionary: [String: JSON], element: (String, AnyObject)) -> [String: JSON] in var d = dictionary d[element.0] = JSON(element.1) return d } } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String: JSON] { return self.dictionary ?? [:] } //Optional [String : AnyObject] public var dictionaryObject: [String: AnyObject]? { get { switch self.type { case .Dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.rawNumber.boolValue default: return nil } } set { if let newValue = newValue { self.object = NSNumber(bool: newValue) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string: newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as? String ?? "" case .Number: return self.object.stringValue case .Bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string: newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.rawNumber default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber() { // indicates parse error return NSDecimalNumber.zero() } return decimal case .Number, .Bool: return self.object as? NSNumber ?? NSNumber(int: 0) default: return NSNumber(double: 0.0) } } set { self.object = newValue } } } // MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func isExists() -> Bool { if let errorValue = error where errorValue.code == ErrorNotExist { return false } return true } } // MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(double: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(float: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if let newValue = newValue { self.object = NSNumber(integer: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if let newValue = newValue { self.object = NSNumber(unsignedLong: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if let newValue = newValue { self.object = NSNumber(char: newValue) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if let newValue = newValue { self.object = NSNumber(unsignedChar: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if let newValue = newValue { self.object = NSNumber(short: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if let newValue = newValue { self.object = NSNumber(unsignedShort: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(int: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if let newValue = newValue { self.object = NSNumber(unsignedInt: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if let newValue = newValue { self.object = NSNumber(longLong: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if let newValue = newValue { self.object = NSNumber(unsignedLongLong: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } // MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber == rhs.rawNumber case (.String, .String): return lhs.rawString == rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber <= rhs.rawNumber case (.String, .String): return lhs.rawString <= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber >= rhs.rawNumber case (.String, .String): return lhs.rawString >= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber > rhs.rawNumber case (.String, .String): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber < rhs.rawNumber case (.String, .String): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool: Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType) { return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } }
swift-master/Maps/Pods/Alamofire/Source/MultipartFormData.swift
// // MultipartFormData.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif /** Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well and the w3 form documentation. - https://www.ietf.org/rfc/rfc2388.txt - https://www.ietf.org/rfc/rfc2045.txt - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 */ public class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let CRLF = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case Initial, Encapsulated, Final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { let boundaryText: String switch boundaryType { case .Initial: boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" case .Encapsulated: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" case .Final: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" } return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } class BodyPart { let headers: [String: String] let bodyStream: NSInputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: NSError? private let streamBufferSize: Int // MARK: - Lifecycle /** Creates a multipart form data object. - returns: The multipart form data object. */ public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /** * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more * information, please refer to the following article: * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html */ self.streamBufferSize = 1024 } // MARK: - Body Parts /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. */ public func appendBodyPart(data data: NSData, name: String) { let headers = contentHeaders(name: name) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, mimeType: String) { let headers = contentHeaders(name: name, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary The filename in the `Content-Disposition` HTTP header is generated from the last path component of the `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the system associated MIME type. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String) { if let fileName = fileURL.lastPathComponent, pathExtension = fileURL.pathExtension { let mimeType = mimeTypeForPathExtension(pathExtension) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) } } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - Content-Type: #{mimeType} (HTTP Header) - Encoded file data - Multipart form boundary - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ var isReachable = true if #available(OSX 10.10, *) { isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) } guard isReachable else { setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false guard let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ var bodyContentLength: UInt64? do { if let path = fileURL.path, fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber { bodyContentLength = fileSize.unsignedLongLongValue } } catch { // No-op } guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) return } appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the stream and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. */ public func appendBodyPart( stream stream: NSInputStream, length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part with the headers, stream and length and appends it to the multipart form data object. The body part data will be encoded using the following format: - HTTP headers - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter headers: The HTTP headers for the body part. */ public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /** Encodes all the appended body parts into a single `NSData` object. It is important to note that this method will load all the appended body parts into memory all at the same time. This method should only be used when the encoded data will have a small memory footprint. For large data cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - throws: An `NSError` if encoding encounters an error. - returns: The encoded `NSData` if encoding is successful. */ public func encode() throws -> NSData { if let bodyPartError = bodyPartError { throw bodyPartError } let encoded = NSMutableData() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encodeBodyPart(bodyPart) encoded.appendData(encodedData) } return encoded } /** Writes the appended body parts into the given file URL. This process is facilitated by reading and writing with input and output streams, respectively. Thus, this approach is very memory efficient and should be used for large body part data. - parameter fileURL: The file URL to write the multipart form data into. - throws: An `NSError` if encoding encounters an error. */ public func writeEncodedDataToDisk(fileURL: NSURL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) } outputStream.open() self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try writeBodyPart(bodyPart, toOutputStream: outputStream) } outputStream.close() } // MARK: - Private - Body Part Encoding private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { let encoded = NSMutableData() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.appendData(initialData) let headerData = encodeHeaderDataForBodyPart(bodyPart) encoded.appendData(headerData) let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) encoded.appendData(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.appendData(finalBoundaryData()) } return encoded } private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" } headerText += EncodingCharacters.CRLF return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream inputStream.open() var error: NSError? let encoded = NSMutableData() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if inputStream.streamError != nil { error = inputStream.streamError break } if bytesRead > 0 { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) break } else { break } } inputStream.close() if let error = error { throw error } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) } private func writeInitialBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try writeData(initialData, toOutputStream: outputStream) } private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let headerData = encodeHeaderDataForBodyPart(bodyPart) return try writeData(headerData, toOutputStream: outputStream) } private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.open() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw streamError } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() } private func writeFinalBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { if bodyPart.hasFinalBoundary { return try writeData(finalBoundaryData(), toOutputStream: outputStream) } } // MARK: - Private - Writing Buffered Data to Output Stream private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws { var buffer = [UInt8](count: data.length, repeatedValue: 0) data.getBytes(&buffer, length: data.length) return try writeBuffer(&buffer, toOutputStream: outputStream) } private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws { var bytesToWrite = buffer.count while bytesToWrite > 0 { if outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let streamError = outputStream.streamError { throw streamError } if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } else if let streamError = outputStream.streamError { throw streamError } } } // MARK: - Private - Mime Type private func mimeTypeForPathExtension(pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(name name: String) -> [String: String] { return ["Content-Disposition": "form-data; name=\"\(name)\""] } private func contentHeaders(name name: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"", "Content-Type": "\(mimeType)" ] } private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", "Content-Type": "\(mimeType)" ] } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) } private func encapsulatedBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) } private func finalBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(code code: Int, failureReason: String) { guard bodyPartError == nil else { return } bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) } }
swift-master/Maps/Pods/Alamofire/Source/NetworkReachabilityManager.swift
// // NetworkReachabilityManager.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) import Foundation import SystemConfiguration /** The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. Reachability can be used to determine background information about why a network operation failed, or to retry network requests when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. */ public class NetworkReachabilityManager { /** Defines the various states of network reachability. - Unknown: It is unknown whether the network is reachable. - NotReachable: The network is not reachable. - ReachableOnWWAN: The network is reachable over the WWAN connection. - ReachableOnWiFi: The network is reachable over the WiFi connection. */ public enum NetworkReachabilityStatus { case Unknown case NotReachable case Reachable(ConnectionType) } /** Defines the various connection types detected by reachability flags. - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. - WWAN: The connection type is a WWAN connection. */ public enum ConnectionType { case EthernetOrWiFi case WWAN } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = NetworkReachabilityStatus -> Void // MARK: - Properties /// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } /// Whether the network is currently reachable over Ethernet or WiFi interface. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } /// The current network reachability status. public var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .Unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() /// A closure executed when the network reachability status changes. public var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability private var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /** Creates a `NetworkReachabilityManager` instance with the specified host. - parameter host: The host used to evaluate network reachability. - returns: The new `NetworkReachabilityManager` instance. */ public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /** Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing status of the device, both IPv4 and IPv6. - returns: The new `NetworkReachabilityManager` instance. */ public convenience init?() { var address = sockaddr_in() address.sin_len = UInt8(sizeofValue(address)) address.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(&address, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability self.previousFlags = SCNetworkReachabilityFlags() } deinit { stopListening() } // MARK: - Listening /** Starts listening for changes in network reachability status. - returns: `true` if listening was started successfully, `false` otherwise. */ public func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) dispatch_async(listenerQueue) { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } return callbackEnabled && queueEnabled } /** Stops listening for changes in network reachability status. */ public func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard flags.contains(.Reachable) else { return .NotReachable } var networkStatus: NetworkReachabilityStatus = .NotReachable if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } } #if os(iOS) if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } #endif return networkStatus } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /** Returns whether the two network reachability status values are equal. - parameter lhs: The left-hand side value to compare. - parameter rhs: The right-hand side value to compare. - returns: `true` if the two values are equal, `false` otherwise. */ public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.Unknown, .Unknown): return true case (.NotReachable, .NotReachable): return true case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif
swift-master/Maps/Pods/Alamofire/Source/Manager.swift
// // Manager.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. */ public class Manager { // MARK: - Properties /** A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ public static let sharedInstance: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joinWithSeparator(", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let versionString: String if #available(OSX 10.10, *) { let version = NSProcessInfo.processInfo().operatingSystemVersion versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" } else { versionString = "10.9" } let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(OSX) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() return "\(executable)/\(bundle) (\(version); \(osNameVersion))" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) /// The underlying session. public let session: NSURLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. public var startRequestsImmediately: Bool = true /** The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default. */ public var backgroundCompletionHandler: (() -> Void)? // MARK: - Lifecycle /** Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - parameter configuration: The configuration used to construct the managed session. `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by default. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance. */ public init( configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /** Initializes the `Manager` instance with the specified session, delegate and server trust policy. - parameter session: The URL session. - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. */ public init?( session: NSURLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Request /** Creates a request for the specified method, URL string, parameters, parameter encoding and headers. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return request(encodedURLRequest) } /** Creates a request for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { var dataTask: NSURLSessionDataTask! dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } let request = Request(session: session, task: dataTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: - SessionDelegate /** Responsible for handling all delegate callbacks for the underlying session. */ public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) /// Access the task delegate for the specified task in a thread-safe manner. public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } } /** Initializes the `SessionDelegate` instance. - returns: The new `SessionDelegate` instance. */ public override init() { super.init() } // MARK: - NSURLSessionDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { sessionDidBecomeInvalidWithError?(session, error) } /** Requests credentials from the delegate in response to a session-level authentication request from the remote server. - parameter session: The session containing the task that requested authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func URLSession( session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } completionHandler(disposition, credential) } /** Tells the delegate that all messages enqueued for a session have been delivered. - parameter session: The session that no longer has any outstanding requests. */ public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and /// requires the caller to call the `completionHandler`. public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the remote server requested an HTTP redirect. - parameter session: The session containing the task whose request resulted in a redirect. - parameter task: The task whose request resulted in a redirect. - parameter response: An object containing the server’s response to the original request. - parameter request: A URL request object filled out with the new location. - parameter completionHandler: A closure that your handler should call with either the value of the request parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: NSURLRequest? -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /** Requests credentials from the delegate in response to an authentication request from the remote server. - parameter session: The session containing the task whose request requires authentication. - parameter task: The task whose request requires authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler ) } else { URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) } } /** Tells the delegate when a task requires a new request body stream to send to the remote server. - parameter session: The session containing the task that needs a new body stream. - parameter task: The task that needs a new body stream. - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: NSInputStream? -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) } } /** Periodically informs the delegate of the progress of sending body content to the server. - parameter session: The session containing the data task. - parameter task: The data task. - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - parameter totalBytesSent: The total number of bytes sent so far. - parameter totalBytesExpectedToSend: The expected length of the body data. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task] as? Request.UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } /** Tells the delegate that the task finished transferring data. - parameter session: The session containing the task whose request finished transferring data. - parameter task: The task whose request finished transferring data. - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. */ public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didCompleteWithError: error) } NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) self[task] = nil } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the data task received the initial reply (headers) from the server. - parameter session: The session containing the data task that received an initial reply. - parameter dataTask: The data task that received an initial reply. - parameter response: A URL response object populated with headers. - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a constant to indicate whether the transfer should continue as a data task or should become a download task. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: NSURLSessionResponseDisposition -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /** Tells the delegate that the data task was changed to a download task. - parameter session: The session containing the task that was replaced by a download task. - parameter dataTask: The data task that was replaced by a download task. - parameter downloadTask: The new download task that replaced the data task. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) self[downloadTask] = downloadDelegate } } /** Tells the delegate that the data task has received some of the expected data. - parameter session: The session containing the data task that provided data. - parameter dataTask: The data task that provided data. - parameter data: A data object containing the transferred data. */ public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) } } /** Asks the delegate whether the data (or upload) task should store the response in the cache. - parameter session: The session containing the data (or upload) task. - parameter dataTask: The data (or upload) task. - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. - parameter completionHandler: A block that your handler must call, providing either the original proposed response, a modified version of that response, or NULL to prevent caching the response. If your delegate implements this method, it must call this completion handler; otherwise, your app leaks memory. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: NSCachedURLResponse? -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods /** Tells the delegate that a download task has finished downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that finished. - parameter location: A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) } } /** Periodically informs the delegate about the download’s progress. - parameter session: The session containing the download task. - parameter downloadTask: The download task. - parameter bytesWritten: The number of bytes transferred since the last time this delegate method was called. - parameter totalBytesWritten: The total number of bytes transferred so far. - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is `NSURLSessionTransferSizeUnknown`. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /** Tells the delegate that the download task has resumed downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that resumed. See explanation in the discussion. - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the existing content, then this value is zero. Otherwise, this value is an integer representing the number of bytes on disk that do not need to be retrieved again. - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is NSURLSessionTransferSizeUnknown. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } // MARK: - NSURLSessionStreamDelegate var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { #if !os(OSX) if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif switch selector { case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } } } }
swift-master/Maps/Pods/Alamofire/Source/Stream.swift
// // Stream.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if !os(watchOS) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager { private enum Streamable { case Stream(String, Int) case NetService(NSNetService) } private func stream(streamable: Streamable) -> Request { var streamTask: NSURLSessionStreamTask! switch streamable { case .Stream(let hostName, let port): dispatch_sync(queue) { streamTask = self.session.streamTaskWithHostName(hostName, port: port) } case .NetService(let netService): dispatch_sync(queue) { streamTask = self.session.streamTaskWithNetService(netService) } } let request = Request(session: session, task: streamTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } /** Creates a request for bidirectional streaming with the given hostname and port. - parameter hostName: The hostname of the server to connect to. - parameter port: The port of the server to connect to. :returns: The created stream request. */ public func stream(hostName hostName: String, port: Int) -> Request { return stream(.Stream(hostName, port)) } /** Creates a request for bidirectional streaming with the given `NSNetService`. - parameter netService: The net service used to identify the endpoint. - returns: The created stream request. */ public func stream(netService netService: NSNetService) -> Request { return stream(.NetService(netService)) } } // MARK: - @available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } // MARK: Delegate Methods /** Tells the delegate that the read side of the connection has been closed. - parameter session: The session. - parameter streamTask: The stream task. */ public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /** Tells the delegate that the write side of the connection has been closed. - parameter session: The session. - parameter streamTask: The stream task. */ public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /** Tells the delegate that the system has determined that a better route to the host is available. - parameter session: The session. - parameter streamTask: The stream task. */ public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /** Tells the delegate that the stream task has been completed and provides the unopened stream objects. - parameter session: The session. - parameter streamTask: The stream task. - parameter inputStream: The new input stream. - parameter outputStream: The new output stream. */ public func URLSession( session: NSURLSession, streamTask: NSURLSessionStreamTask, didBecomeInputStream inputStream: NSInputStream, outputStream: NSOutputStream) { streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) } } #endif
swift-master/Maps/Pods/Alamofire/Source/Error.swift
// // Error.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. public struct Error { /// The domain used for creating all Alamofire errors. public static let Domain = "com.alamofire.error" /// The custom error codes generated by Alamofire. public enum Code: Int { case InputStreamReadFailed = -6000 case OutputStreamWriteFailed = -6001 case ContentTypeValidationFailed = -6002 case StatusCodeValidationFailed = -6003 case DataSerializationFailed = -6004 case StringSerializationFailed = -6005 case JSONSerializationFailed = -6006 case PropertyListSerializationFailed = -6007 } /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. public struct UserInfoKeys { /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. public static let ContentType = "ContentType" /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. public static let StatusCode = "StatusCode" } /** Creates an `NSError` with the given error code and failure reason. - parameter code: The error code. - parameter failureReason: The failure reason. - returns: An `NSError` with the given error code and failure reason. */ @available(*, deprecated=3.4.0) public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } /** Creates an `NSError` with the given error code and failure reason. - parameter code: The error code. - parameter failureReason: The failure reason. - returns: An `NSError` with the given error code and failure reason. */ @available(*, deprecated=3.4.0) public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { return error(domain: domain, code: code.rawValue, failureReason: failureReason) } static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: domain, code: code, userInfo: userInfo) } }
swift-master/Maps/Pods/Alamofire/Source/Timeline.swift
// // Timeline.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: NSTimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: NSTimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: NSTimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: NSTimeInterval /** Creates a new `Timeline` instance with the specified request times. - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. - parameter initialResponseTime: The time the first bytes were received from or sent to the server. Defaults to `0.0`. - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults to `0.0`. - returns: The new `Timeline` instance. */ public init( requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime self.latency = initialResponseTime - requestStartTime self.requestDuration = requestCompletedTime - requestStartTime self.serializationDuration = serializationCompletedTime - requestCompletedTime self.totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joinWithSeparator(", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joinWithSeparator(", ") + " }" } }
swift-master/Maps/Pods/Alamofire/Source/Result.swift
// // Result.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** Used to represent whether a request was successful or encountered an error. - Success: The request and all post processing operations were successful resulting in the serialization of the provided associated value. - Failure: The request encountered an error resulting in a failure. The associated values are the original data provided by the server as well as the error that caused the failure. */ public enum Result<Value, Error: ErrorType> { case Success(Value) case Failure(Error) /// Returns `true` if the result is a success, `false` otherwise. public var isSuccess: Bool { switch self { case .Success: return true case .Failure: return false } } /// Returns `true` if the result is a failure, `false` otherwise. public var isFailure: Bool { return !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { case .Success(let value): return value case .Failure: return nil } } /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { case .Success: return nil case .Failure(let error): return error } } } // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { case .Success: return "SUCCESS" case .Failure: return "FAILURE" } } } // MARK: - CustomDebugStringConvertible extension Result: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes whether the result was a /// success or failure in addition to the value or error. public var debugDescription: String { switch self { case .Success(let value): return "SUCCESS: \(value)" case .Failure(let error): return "FAILURE: \(error)" } } }
swift-master/Maps/Pods/Alamofire/Source/ParameterEncoding.swift
// // ParameterEncoding.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied. - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) where !parameters.isEmpty { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ) } case .JSON: do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try NSPropertyListSerialization.dataWithPropertyList( parameters, format: format, options: options ) if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let range = startIndex..<endIndex let substring = string.substringWithRange(range) escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring index = endIndex } } return escaped } }
swift-master/Maps/Pods/Alamofire/Source/Download.swift
// // Download.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Manager { private enum Downloadable { case Request(NSURLRequest) case ResumeData(NSData) } private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { var downloadTask: NSURLSessionDownloadTask! switch downloadable { case .Request(let request): dispatch_sync(queue) { downloadTask = self.session.downloadTaskWithRequest(request) } case .ResumeData(let resumeData): dispatch_sync(queue) { downloadTask = self.session.downloadTaskWithResumeData(resumeData) } } let request = Request(session: session, task: downloadTask) if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in return destination(URL, downloadTask.response as! NSHTTPURLResponse) } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: Request /** Creates a download request for the specified method, URL string, parameters, parameter encoding, headers and destination. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return download(encodedURLRequest, destination: destination) } /** Creates a request for downloading from the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return download(.Request(URLRequest.URLRequest), destination: destination) } // MARK: Resume Data /** Creates a request for downloading from the resume data produced from a previous request cancellation. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { return download(.ResumeData(resumeData), destination: destination) } } // MARK: - extension Request { /** A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved. */ public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL /** Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask. - parameter directory: The search path directory. `.DocumentDirectory` by default. - parameter domain: The search path domain mask. `.UserDomainMask` by default. - returns: A download file destination closure. */ public class func suggestedDownloadDestination( directory directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination { return { temporaryURL, response -> NSURL in let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) if !directoryURLs.isEmpty { return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) } return temporaryURL } } /// The resume data of the underlying download task if available after a failure. public var resumeData: NSData? { var data: NSData? if let delegate = delegate as? DownloadTaskDelegate { data = delegate.resumeData } return data } // MARK: - DownloadTaskDelegate class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } var downloadProgress: ((Int64, Int64, Int64) -> Void)? var resumeData: NSData? override var data: NSData? { return resumeData } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { do { let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) } catch { self.error = error as NSError } } } func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite ) } else { progress.totalUnitCount = totalBytesExpectedToWrite progress.completedUnitCount = totalBytesWritten downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } } func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else { progress.totalUnitCount = expectedTotalBytes progress.completedUnitCount = fileOffset } } } }
swift-master/Maps/Pods/Alamofire/Source/Validation.swift
// // Validation.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Request { /** Used to represent whether validation was successful or encountered an error resulting in a failure. - Success: The validation was successful. - Failure: The validation failed encountering the provided error. */ public enum ValidationResult { case Success case Failure(NSError) } /** A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid. */ public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult /** Validates the request, using the specified closure. If validation fails, subsequent calls to response handlers will have an associated error. - parameter validation: A closure to validate the request. - returns: The request. */ public func validate(validation: Validation) -> Self { delegate.queue.addOperationWithBlock { if let response = self.response where self.delegate.error == nil, case let .Failure(error) = validation(self.request, response) { self.delegate.error = error } } return self } // MARK: - Status Code /** Validates that the response has a status code in the specified range. If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self { return validate { _, response in if acceptableStatusCode.contains(response.statusCode) { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" let error = NSError( domain: Error.Domain, code: Error.Code.StatusCodeValidationFailed.rawValue, userInfo: [ NSLocalizedFailureReasonErrorKey: failureReason, Error.UserInfoKeys.StatusCode: response.statusCode ] ) return .Failure(error) } } } // MARK: - Content-Type private struct MIMEType { let type: String let subtype: String init?(_ string: String) { let components: [String] = { let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) return split.componentsSeparatedByString("/") }() if let type = components.first, subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(MIME: MIMEType) -> Bool { switch (type, subtype) { case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): return true default: return false } } } /** Validates that the response has a content type in the specified array. If validation fails, subsequent calls to response handlers will have an associated error. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self { return validate { _, response in guard let validData = self.delegate.data where validData.length > 0 else { return .Success } if let responseContentType = response.MIMEType, responseMIMEType = MIMEType(responseContentType) { for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { return .Success } } } else { for contentType in acceptableContentTypes { if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { return .Success } } } let contentType: String let failureReason: String if let responseContentType = response.MIMEType { contentType = responseContentType failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { contentType = "" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } let error = NSError( domain: Error.Domain, code: Error.Code.ContentTypeValidationFailed.rawValue, userInfo: [ NSLocalizedFailureReasonErrorKey: failureReason, Error.UserInfoKeys.ContentType: contentType ] ) return .Failure(error) } } // MARK: - Automatic /** Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field. If validation fails, subsequent calls to response handlers will have an associated error. - returns: The request. */ public func validate() -> Self { let acceptableStatusCodes: Range<Int> = 200..<300 let acceptableContentTypes: [String] = { if let accept = request?.valueForHTTPHeaderField("Accept") { return accept.componentsSeparatedByString(",") } return ["*/*"] }() return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) } }
swift-master/Maps/Pods/Alamofire/Source/Notifications.swift
// // Notifications.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. public struct Notifications { /// Used as a namespace for all `NSURLSessionTask` related notifications. public struct Task { /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed /// `NSURLSessionTask`. public static let DidResume = "com.alamofire.notifications.task.didResume" /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the /// suspended `NSURLSessionTask`. public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the /// cancelled `NSURLSessionTask`. public static let DidCancel = "com.alamofire.notifications.task.didCancel" /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the /// completed `NSURLSessionTask`. public static let DidComplete = "com.alamofire.notifications.task.didComplete" } }
swift-master/Maps/Pods/Alamofire/Source/Response.swift
// // Response.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all response data returned from a completed `Request`. public struct Response<Value, Error: ErrorType> { /// The URL request sent to the server. public let request: NSURLRequest? /// The server's response to the URL request. public let response: NSHTTPURLResponse? /// The data returned by the server. public let data: NSData? /// The result of response serialization. public let result: Result<Value, Error> /// The timeline of the complete lifecycle of the `Request`. public let timeline: Timeline /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. - parameter request: The URL request sent to the server. - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - returns: the new `Response` instance. */ public init( request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - CustomStringConvertible extension Response: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } } // MARK: - CustomDebugStringConvertible extension Response: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data and the response serialization result. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } }
swift-master/Maps/Pods/Alamofire/Source/Alamofire.swift
// // Alamofire.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download( method, URLString, parameters: parameters, encoding: encoding, headers: headers, destination: destination ) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
swift-master/Maps/Pods/Alamofire/Source/Request.swift
// // Request.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`. */ public class Request { // MARK: - Properties /// The delegate for the underlying task. public let delegate: TaskDelegate /// The underlying task. public var task: NSURLSessionTask { return delegate.task } /// The session belonging to the underlying task. public let session: NSURLSession /// The request sent or to be sent to the server. public var request: NSURLRequest? { return task.originalRequest } /// The response received from the server, if any. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } /// The progress of the request lifecycle. public var progress: NSProgress { return delegate.progress } var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? // MARK: - Lifecycle init(session: NSURLSession, task: NSURLSessionTask) { self.session = session switch task { case is NSURLSessionUploadTask: delegate = UploadTaskDelegate(task: task) case is NSURLSessionDataTask: delegate = DataTaskDelegate(task: task) case is NSURLSessionDownloadTask: delegate = DownloadTaskDelegate(task: task) default: delegate = TaskDelegate(task: task) } delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: - Authentication /** Associates an HTTP Basic credential with the request. - parameter user: The user. - parameter password: The password. - parameter persistence: The URL credential persistence. `.ForSession` by default. - returns: The request. */ public func authenticate( user user: String, password: String, persistence: NSURLCredentialPersistence = .ForSession) -> Self { let credential = NSURLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /** Associates a specified credential with the request. - parameter credential: The credential. - returns: The request. */ public func authenticate(usingCredential credential: NSURLCredential) -> Self { delegate.credential = credential return self } /** Returns a base64 encoded basic authentication credential as an authorization header dictionary. - parameter user: The user. - parameter password: The password. - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails. */ public static func authorizationHeader(user user: String, password: String) -> [String: String] { guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } let credential = data.base64EncodedStringWithOptions([]) return ["Authorization": "Basic \(credential)"] } // MARK: - Progress /** Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write. - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read. - parameter closure: The code to be executed periodically during the lifecycle of the request. - returns: The request. */ public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { if let uploadDelegate = delegate as? UploadTaskDelegate { uploadDelegate.uploadProgress = closure } else if let dataDelegate = delegate as? DataTaskDelegate { dataDelegate.dataProgress = closure } else if let downloadDelegate = delegate as? DownloadTaskDelegate { downloadDelegate.downloadProgress = closure } return self } /** Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. This closure returns the bytes most recently received from the server, not including data from previous calls. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`. - parameter closure: The code to be executed periodically during the lifecycle of the request. - returns: The request. */ public func stream(closure: (NSData -> Void)? = nil) -> Self { if let dataDelegate = delegate as? DataTaskDelegate { dataDelegate.dataStream = closure } return self } // MARK: - State /** Resumes the request. */ public func resume() { if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** Suspends the request. */ public func suspend() { task.suspend() NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** Cancels the request. */ public func cancel() { if let downloadDelegate = delegate as? DownloadTaskDelegate, downloadTask = downloadDelegate.downloadTask { downloadTask.cancelByProducingResumeData { data in downloadDelegate.resumeData = data } } else { task.cancel() } NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate /** The task delegate is responsible for handling all delegate callbacks for the underlying task as well as executing all operations attached to the serial operation queue upon task completion. */ public class TaskDelegate: NSObject { /// The serial operation queue used to execute all operations after the task completes. public let queue: NSOperationQueue let task: NSURLSessionTask let progress: NSProgress var data: NSData? { return nil } var error: NSError? var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { self.task = task self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true if #available(OSX 10.10, *) { operationQueue.qualityOfService = NSQualityOfService.Utility } return operationQueue }() } deinit { queue.cancelAllOperations() queue.suspended = false } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest?) -> Void)) { var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } else { if challenge.previousFailureCount > 0 { disposition = .RejectProtectionSpace } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) if credential != nil { disposition = .UseCredential } } } completionHandler(disposition, credential) } func URLSession( session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) { var bodyStream: NSInputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { self.error = error if let downloadDelegate = self as? DownloadTaskDelegate, userInfo = error.userInfo as? [String: AnyObject], resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData { downloadDelegate.resumeData = resumeData } } queue.suspended = false } } } // MARK: - DataTaskDelegate class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } private var totalBytesReceived: Int64 = 0 private var mutableData: NSMutableData override var data: NSData? { if dataStream != nil { return nil } else { return mutableData } } private var expectedContentLength: Int64? private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? private var dataStream: ((data: NSData) -> Void)? override init(task: NSURLSessionTask) { mutableData = NSMutableData() super.init(task: task) } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? // MARK: Delegate Methods func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data: data) } else { mutableData.appendData(data) } totalBytesReceived += data.length let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived dataProgress?( bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpected ) } } func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse?) -> Void)) { var cachedResponse: NSCachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /** The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received. */ public var description: String { var components: [String] = [] if let HTTPMethod = request?.HTTPMethod { components.append(HTTPMethod) } if let URLString = request?.URL?.absoluteString { components.append(URLString) } if let response = response { components.append("(\(response.statusCode))") } return components.joinWithSeparator(" ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, URL = request.URL, host = URL.host else { return "$ curl command could not be created" } if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { components.append("-X \(HTTPMethod)") } if let credentialStorage = self.session.configuration.URLCredentialStorage { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, protocol: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.HTTPShouldSetCookies { if let cookieStorage = session.configuration.HTTPCookieStorage, cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") } } var headers: [NSObject: AnyObject] = [:] if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { for (field, value) in additionalHeaders where field != "Cookie" { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(URL.absoluteString)\"") return components.joinWithSeparator(" \\\n\t") } /// The textual representation used when written to an output stream, in the form of a cURL command. public var debugDescription: String { return cURLRepresentation() } }
swift-master/Maps/Pods/Alamofire/Source/Upload.swift
// // Upload.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Manager { private enum Uploadable { case Data(NSURLRequest, NSData) case File(NSURLRequest, NSURL) case Stream(NSURLRequest, NSInputStream) } private func upload(uploadable: Uploadable) -> Request { var uploadTask: NSURLSessionUploadTask! var HTTPBodyStream: NSInputStream? switch uploadable { case .Data(let request, let data): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) } case .File(let request, let fileURL): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) } case .Stream(let request, let stream): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithStreamedRequest(request) } HTTPBodyStream = stream } let request = Request(session: session, task: uploadTask) if HTTPBodyStream != nil { request.delegate.taskNeedNewBodyStream = { _, _ in return HTTPBodyStream } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: File /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter file: The file to upload - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return upload(.File(URLRequest.URLRequest, file)) } /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, file: file) } // MARK: Data /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return upload(.Data(URLRequest.URLRequest, data)) } /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, data: data) } // MARK: Stream /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return upload(.Stream(URLRequest.URLRequest, stream)) } /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, stream: stream) } // MARK: MultipartFormData /// Default memory threshold used when encoding `MultipartFormData`. public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 /** Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as associated values. - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with streaming information. - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding error. */ public enum MultipartFormDataEncodingResult { case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) case Failure(ErrorType) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload( mutableURLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let formData = MultipartFormData() multipartFormData(formData) let URLRequestWithContentType = URLRequest.URLRequest URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { do { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, data: data), streamingFromDisk: false, streamFileURL: nil ) dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } else { let fileManager = NSFileManager.defaultManager() let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") let fileName = NSUUID().UUIDString let fileURL = directoryURL.URLByAppendingPathComponent(fileName) do { try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) try formData.writeEncodedDataToDisk(fileURL) dispatch_async(dispatch_get_main_queue()) { let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, file: fileURL), streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } } } } // MARK: - extension Request { // MARK: - UploadTaskDelegate class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
swift-master/Maps/Pods/Alamofire/Source/ResponseSerialization.swift
// // ResponseSerialization.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: ResponseSerializer /** The type in which all response serializers must conform to in order to serialize a response. */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. associatedtype SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. associatedtype ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get } } // MARK: - /** A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. */ public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializer`. public typealias SerializedObject = Value /// The type of error to be created by this `ResponseSerializer` if serialization fails. public typealias ErrorObject = Error /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error> /** Initializes the `ResponseSerializer` instance with the given serialize response closure. - parameter serializeResponse: The closure used to serialize the response. - returns: The new generic response serializer instance. */ public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) { self.serializeResponse = serializeResponse } } // MARK: - Default extension Request { /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response( queue queue: dispatch_queue_t? = nil, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self { delegate.queue.addOperationWithBlock { dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) } } return self } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter responseSerializer: The response serializer responsible for serializing the request, response, and data. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response<T: ResponseSerializerType>( queue queue: dispatch_queue_t? = nil, responseSerializer: T, completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void) -> Self { delegate.queue.addOperationWithBlock { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime let timeline = Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) let response = Response<T.SerializedObject, T.ErrorObject>( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: timeline ) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self } } // MARK: - Data extension Request { /** Creates a response serializer that returns the associated data as-is. - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSData()) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) return .Failure(error) } return .Success(validData) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func responseData( queue queue: dispatch_queue_t? = nil, completionHandler: Response<NSData, NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } // MARK: - String extension Request { /** Creates a response serializer that returns a string initialized from the response data with the specified string encoding. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - returns: A string response serializer. */ public static func stringResponseSerializer( encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer<String, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success("") } guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName where convertedEncoding == nil { convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } } /** Adds a handler to be called once the request has finished. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseString( queue queue: dispatch_queue_t? = nil, encoding: NSStringEncoding? = nil, completionHandler: Response<String, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /** Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - returns: A JSON object response serializer. */ public static func JSONResponseSerializer( options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) return .Success(JSON) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseJSON( queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /** Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. - returns: A property list object response serializer. */ public static func propertyListResponseSerializer( options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) return .Success(plist) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The property list reading options. `0` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 arguments: the URL request, the URL response, the server data and the result produced while creating the property list. - returns: The request. */ public func responsePropertyList( queue queue: dispatch_queue_t? = nil, options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } }
swift-master/Maps/Pods/Alamofire/Source/ServerTrustPolicy.swift
// // ServerTrustPolicy.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. - parameter policies: A dictionary of all policies mapped to a particular host. - returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. By default, this method will return the policy that perfectly matches the given host. Subclasses could override this method and implement more complex mapping implementations such as wildcards. - parameter host: The host to use when searching for a matching policy. - returns: The server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. Applications are encouraged to always validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. By validating both the certificate chain and host, certificate pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. By validating both the certificate chain and host, public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `.cer` files. - returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) }.flatten()) for path in paths { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `*.cer` files. - returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. - parameter serverTrust: The server trust to evaluate. - parameter host: The host of the challenge protection space. - returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType(kSecTrustResultInvalid) let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType(kSecTrustResultUnspecified) let proceed = SecTrustResultType(kSecTrustResultProceed) isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0) as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
swift-master/AVProgramming/AVProgramming/AssetViewController.swift
// // AssetViewController.swift // AVProgramming // // Created by larryhou on 4/3/15. // import MapKit import Foundation import AssetsLibrary import UIKit class MapPinAnnotation: NSObject, MKAnnotation { dynamic var coordinate: CLLocationCoordinate2D dynamic var title: String dynamic var subtitle: String init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate self.title = "" self.subtitle = String(format: "纬:%.4f° 经:%.4f°", coordinate.latitude, coordinate.latitude) } } class AssetViewController: UIViewController, UIScrollViewDelegate, MKMapViewDelegate, UIGestureRecognizerDelegate { var url: NSURL! var index: Int! @IBOutlet weak var container: UIView! private let BAR_HEIGHT: CGFloat = 64 private let MAP_REGION_SPAN: CLLocationDistance = 500 private var _map: MKMapView! private var _photo: UIImageView! private var _tap: UILongPressGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() let bounds = UIScreen.mainScreen().bounds let view: UIScrollView = self.view as! UIScrollView _map = MKMapView(frame: CGRect(x: 0, y: bounds.height, width: bounds.width, height: bounds.width)) _map.userInteractionEnabled = true _map.delegate = self view.addSubview(_map) _photo = UIImageView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - BAR_HEIGHT)) view.addSubview(_photo) ALAssetsLibrary().groupForURL(url, resultBlock: { (group: ALAssetsGroup!) -> Void in group.enumerateAssetsAtIndexes(NSIndexSet(index: self.index), options: NSEnumerationOptions.Concurrent, usingBlock: { (asset: ALAsset!, _: Int, _: UnsafeMutablePointer<ObjCBool>) -> Void in if asset == nil { return } let repr = asset.defaultRepresentation() let data = repr.fullScreenImage().takeUnretainedValue() let type = asset.valueForProperty(ALAssetPropertyType) as! String let bounds = UIScreen.mainScreen().bounds let scale = max(CGFloat(CGImageGetWidth(data)) / bounds.width, CGFloat(CGImageGetHeight(data)) / bounds.height) let image = UIImage(CGImage: data, scale: scale, orientation: UIImageOrientation.Up)! let location = asset.valueForProperty(ALAssetPropertyLocation) as? CLLocation dispatch_async(dispatch_get_main_queue()) { if location != nil && location!.coordinate.latitude != -180 && location!.coordinate.longitude != -80 { self._map.centerCoordinate = location!.coordinate self._map.setRegion(MKCoordinateRegionMakeWithDistance(location!.coordinate, self.MAP_REGION_SPAN, self.MAP_REGION_SPAN), animated: true) let annotation = MapPinAnnotation(coordinate: location!.coordinate) self._map.addAnnotation(annotation) } var frame = CGRect.zero if type == ALAssetTypePhoto { frame = self._photo.frame frame.size = image.size self._photo.image = image } self._photo.frame = frame frame = self._map.frame frame.origin.y = self._photo.frame.origin.y + self._photo.frame.height + 5 self._map.frame = frame var size = view.contentSize size.height = frame.origin.y + frame.height view.contentSize = size } self.trace(repr) }) }) { (error: NSError!) -> Void in println(error) } _tap = UILongPressGestureRecognizer() _tap.minimumPressDuration = 0.5 _tap.addTarget(self, action: "moveAnnotationInView:") view.addGestureRecognizer(_tap) } func trace(representation: ALAssetRepresentation) { println("------------------------------") println(representation.url().absoluteString) println(representation.UTI()) for (key, value) in representation.metadata() { println((key, value)) } } func moveAnnotationInView(guesture: UILongPressGestureRecognizer) { let annotation = _map.annotations.first as! MapPinAnnotation _map.setRegion(MKCoordinateRegionMakeWithDistance(annotation.coordinate, MAP_REGION_SPAN, MAP_REGION_SPAN), animated: true) _map.selectAnnotation(annotation, animated: true) _map.userInteractionEnabled = false } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return nil } func scrollViewDidScroll(scrollView: UIScrollView) { _map.userInteractionEnabled = true } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { println(size) var frame = _photo.frame if _photo.image != nil { var scale = size.width / frame.width frame.size.height *= scale frame.size.width *= scale _photo.frame = frame } frame = _map.frame frame.size = CGSize(width: size.width, height: size.width) frame.origin.y = _photo.frame.height + 5 _map.frame = frame (view as! UIScrollView).contentSize = CGSize(width: size.width, height: frame.origin.y + frame.height) } // MARK: Map Annotation func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation.isKindOfClass(MapPinAnnotation) { let REUSE_IDENTIFIER = "AlbumAssetAnnotation" var view = mapView.dequeueReusableAnnotationViewWithIdentifier(REUSE_IDENTIFIER) as? MKPinAnnotationView if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: REUSE_IDENTIFIER) view!.canShowCallout = true view!.animatesDrop = true } view!.annotation = annotation view!.selected = true return view! } return nil } func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) { var view = views.first as! MKPinAnnotationView let coordinate = view.annotation.coordinate _map.selectAnnotation(view.annotation, animated: true) CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)) { (result: [AnyObject]!, _: NSError!) in if result != nil && result.count > 0 { let placemark = result.first as! CLPlacemark let title = (placemark.addressDictionary["FormattedAddressLines"] as! [String])[0] dispatch_async(dispatch_get_main_queue()) { (view.annotation as! MapPinAnnotation).title = title } } } } deinit { _tap.removeTarget(self, action: "moveAnnotationInView:") } }
swift-master/AVProgramming/AVProgramming/PhotoAlbumViewController.swift
// // ViewController.swift // AVProgramming // // Created by larryhou on 4/3/15. // import UIKit import AssetsLibrary import CoreGraphics let SEPARATOR_COLOR_WHITE: CGFloat = 0.9 class PhotoAlbumCell: UITableViewCell { @IBOutlet weak var posterImage: UIImageView! @IBOutlet weak var albumName: UILabel! @IBOutlet weak var albumAssetsCount: UILabel! @IBOutlet weak var albumID: UILabel! } class NavigationViewController: UINavigationController { override func shouldAutorotate() -> Bool { return topViewController.shouldAutorotate() } override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { return topViewController.preferredInterfaceOrientationForPresentation() } } class PhotoAlubmViewController: UITableViewController, UITableViewDataSource { private var _groups: [NSURL]! private var _library: ALAssetsLibrary! override func viewDidLoad() { super.viewDidLoad() tableView.separatorColor = UIColor(white: SEPARATOR_COLOR_WHITE, alpha: 1.0) _groups = [] _library = ALAssetsLibrary() _library.enumerateGroupsWithTypes(ALAssetsGroupAlbum | ALAssetsGroupSavedPhotos, usingBlock: { (group:ALAssetsGroup!, _:UnsafeMutablePointer<ObjCBool>) in if group != nil { self._groups.append(group.valueForProperty(ALAssetsGroupPropertyURL) as! NSURL) dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } }, failureBlock: { (error: NSError!) in println(error) }) } // MARK: table view override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _groups.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let url = _groups[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("PhotoAlbumCell") as! PhotoAlbumCell _library.groupForURL(url, resultBlock: { (group:ALAssetsGroup!) in cell.albumName.text = (group.valueForProperty(ALAssetsGroupPropertyName) as! String) cell.albumID.text = (group.valueForProperty(ALAssetsGroupPropertyPersistentID) as! String) cell.albumAssetsCount.text = "\(group.numberOfAssets())" cell.posterImage.image = UIImage(CGImage: group.posterImage().takeUnretainedValue(), scale: UIScreen.mainScreen().scale, orientation: UIImageOrientation.Up) }, failureBlock: { (error: NSError!) in println((error, url.absoluteString)) }) return cell } // MARK: segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showAlbumPhotos" { let indexPath = tableView.indexPathForSelectedRow()! var dst = segue.destinationViewController as! PhotoViewController dst.url = _groups[indexPath.row] tableView.deselectRowAtIndexPath(indexPath, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
swift-master/AVProgramming/AVProgramming/AppDelegate.swift
// // AppDelegate.swift // AVProgramming // // Created by larryhou on 4/3/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/AVProgramming/AVProgramming/PhotoViewController.swift
// // PhotoViewController.swift // AVProgramming // // Created by larryhou on 4/3/15. // import UIKit import Foundation import AssetsLibrary import CoreLocation class PhotoCell: UITableViewCell { @IBOutlet weak var thumbnail: UIImageView! @IBOutlet weak var location: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var detail: UILabel! var representation: ALAssetRepresentation! } class PhotoViewController: UITableViewController, UITableViewDataSource { var url: NSURL! private var _numOfAssets: Int = 0 private var _library: ALAssetsLibrary! private var _dateFormatter: NSDateFormatter! override func viewDidLoad() { super.viewDidLoad() tableView.separatorColor = UIColor(white: SEPARATOR_COLOR_WHITE, alpha: 1.0) _dateFormatter = NSDateFormatter() _dateFormatter.dateFormat = "YYYY/mm/dd HH:MM:ss" _library = ALAssetsLibrary() _library.groupForURL(url, resultBlock: { (group: ALAssetsGroup!) -> Void in self._numOfAssets = group.numberOfAssets() dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } }) { (error: NSError!) -> Void in println(error) } } // MARK: table view override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _numOfAssets } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell") as! PhotoCell let row = (_numOfAssets - 1) - indexPath.row _library.groupForURL(url, resultBlock: { (group: ALAssetsGroup!) -> Void in group.enumerateAssetsAtIndexes(NSIndexSet(index: row), options: NSEnumerationOptions.Concurrent, usingBlock: { (asset: ALAsset!, _: Int, _: UnsafeMutablePointer<ObjCBool>) -> Void in if asset == nil { return } let image = UIImage(CGImage: asset.thumbnail().takeUnretainedValue()) let repr = asset.defaultRepresentation() let date = asset.valueForProperty(ALAssetPropertyDate) as! NSDate let location = asset.valueForProperty(ALAssetPropertyLocation) as? CLLocation let dimensions = repr.dimensions() var desc = "\(Int(dimensions.width))×\(Int(dimensions.height))" let type = asset.valueForProperty(ALAssetPropertyType) as! String if type == ALAssetTypeVideo { let duration = asset.valueForProperty(ALAssetPropertyDuration) as! Double let minutes = floor(duration / 60) let seconds = duration % 60 desc += String(format: " %02d:%06.3f", Int(minutes), seconds) } dispatch_async(dispatch_get_main_queue()) { cell.thumbnail.image = image cell.date.text = self._dateFormatter.stringFromDate(date) if location != nil { cell.location.text = String(format: "%.4f°/%.4f°", location!.coordinate.latitude, location!.coordinate.longitude) self.geocode(location!, label: cell.location) } else { cell.location.text = "Unknown Placemark" } cell.detail.text = desc } }) }) { (error: NSError!) -> Void in println(error) } return cell } func geocode(location: CLLocation, label: UILabel) { var query = CLGeocoder() query.reverseGeocodeLocation(location, completionHandler: { (result: [AnyObject]!, error: NSError!) -> Void in if error == nil && result.count > 0 { let placemark = result.first as! CLPlacemark let text = (placemark.addressDictionary["FormattedAddressLines"] as! [String])[0] if text != "" { dispatch_async(dispatch_get_main_queue()) { label.text = text } } } }) } // MARK: segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showAsset" { let indexPath = tableView.indexPathForSelectedRow()! let row = (_numOfAssets - 1) - indexPath.row var dst = segue.destinationViewController as! AssetViewController dst.index = row dst.url = url tableView.deselectRowAtIndexPath(indexPath, animated: false) } } }
swift-master/AVProgramming/AVProgrammingTests/AVProgrammingTests.swift
// // AVProgrammingTests.swift // AVProgrammingTests // // Created by larryhou on 4/3/15. // import UIKit import XCTest class AVProgrammingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/UIScrollView/UIScrollView/ViewController.swift
// // ViewController.swift // UIScrollView // // Created by larryhou on 3/16/15. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { private let MAXIMUM_SCALE: CGFloat = 0.5 private var zoomView: UIImageView! override func viewDidLoad() { super.viewDidLoad() var view = self.view as UIScrollView view.contentSize = CGSize(width: 320, height: 568) view.minimumZoomScale = 0.01 view.maximumZoomScale = 2.00 view.delegate = self view.pinchGestureRecognizer.addTarget(self, action: "pinchUpdated:") zoomView = UIImageView(image: UIImage(named: "4.jpg")) zoomView.userInteractionEnabled = false view.addSubview(zoomView) view.zoomScale = view.minimumZoomScale repairImageZoom() UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: nil) var tap = UITapGestureRecognizer() tap.numberOfTapsRequired = 2 tap.addTarget(self, action: "smartZoomImage:") view.addGestureRecognizer(tap) } func orientationChanged(notification: NSNotification) { alignImageAtCenter() repairImageZoom() } func smartZoomImage(gesture: UITapGestureRecognizer) { let view = self.view as UIScrollView let MINIMUM_SCALE: CGFloat = view.frame.width / (zoomView.frame.width / view.zoomScale) var scale: CGFloat! if view.zoomScale > MINIMUM_SCALE + 0.0001 { scale = MINIMUM_SCALE } else { scale = MAXIMUM_SCALE } if scale != nil { view.setZoomScale(scale, animated: true) } } func pinchUpdated(gesture: UIPinchGestureRecognizer) { let view = self.view as UIScrollView switch gesture.state { case .Began: view.panGestureRecognizer.enabled = false break case .Ended: view.panGestureRecognizer.enabled = true repairImageZoom() break default:break } } func repairImageZoom() { let view = self.view as UIScrollView let MINIMUM_SCALE: CGFloat = view.frame.width / (zoomView.frame.width / view.zoomScale) var scale: CGFloat! if view.zoomScale < MINIMUM_SCALE { scale = MINIMUM_SCALE } else if view.zoomScale > MAXIMUM_SCALE { scale = MAXIMUM_SCALE } if scale != nil { view.setZoomScale(scale, animated: true) } } func alignImageAtCenter() { var view = self.view as UIScrollView var inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) var frame = zoomView.frame if frame.width < view.frame.width { inset.left = (view.frame.width - frame.width) / 2.0 } else { inset.left = 0.0 } if frame.height < view.frame.height { inset.top = (view.frame.height - frame.height) / 2.0 } else { inset.top = 0.0 } view.contentInset = inset } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return zoomView } func scrollViewDidZoom(scrollView: UIScrollView) { alignImageAtCenter() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/UIScrollView/UIScrollView/AppDelegate.swift
// // AppDelegate.swift // UIScrollView // // Created by larryhou on 3/16/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/UIScrollView/UIScrollViewTests/UIScrollViewTests.swift
// // UIScrollViewTests.swift // UIScrollViewTests // // Created by larryhou on 3/16/15. // import UIKit import XCTest class UIScrollViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/AutoLayout/AutoLayout/ViewController.swift
// // ViewController.swift // AutoLayout // // Created by larryhou on 3/21/15. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() updateConstraints() } func updateConstraints() { var label = view.viewWithTag(1)! as UILabel label.font = UIFont.systemFontOfSize(16) label.text = "Created By Visual Format Language" label.removeFromSuperview() label.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(label) var map: [NSObject: AnyObject] = [:] map.updateValue(label, forKey: "label") view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[label(30)]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) var pad1 = UIView() pad1.setTranslatesAutoresizingMaskIntoConstraints(false) pad1.backgroundColor = UIColor.blueColor() map.updateValue(pad1, forKey: "pad1") view.addSubview(pad1) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[pad1(1)]", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) var pad2 = UIView() pad2.setTranslatesAutoresizingMaskIntoConstraints(false) map.updateValue(pad2, forKey: "pad2") view.addSubview(pad2) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[pad2(1)]", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) var name = UILabel() name.text = "LARRY HOU" name.font = UIFont.systemFontOfSize(30) name.textAlignment = NSTextAlignment.Center name.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(name) map.updateValue(name, forKey: "name") view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[name]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[pad1]-[name(30)]-[pad2(==pad1)]|", options: NSLayoutFormatOptions(0), metrics: nil, views: map)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
swift-master/AutoLayout/AutoLayout/AppDelegate.swift
// // AppDelegate.swift // AutoLayout // // Created by larryhou on 3/21/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/AutoLayout/AutoLayoutTests/AutoLayoutTests.swift
// // AutoLayoutTests.swift // AutoLayoutTests // // Created by larryhou on 3/21/15. // import UIKit import XCTest class AutoLayoutTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/TableViewBadPerformanceSample/TableViewBadPerformanceSample/ViewController.swift
// // ViewController.swift // TableViewBadPerformanceSample // // Created by larryhou on 13/3/2016. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
swift-master/TableViewBadPerformanceSample/TableViewBadPerformanceSample/TableViewController.swift
// // TableViewController.swift // TableViewBadPerformanceSample // // Created by larryhou on 13/3/2016. // import Foundation import UIKit class TableViewController: UITableViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1_000_000 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PatternCell")! cell.textLabel?.text = String(format: "%07d", indexPath.row) return cell } }
swift-master/TableViewBadPerformanceSample/TableViewBadPerformanceSample/AppDelegate.swift
// // AppDelegate.swift // TableViewBadPerformanceSample // // Created by larryhou on 13/3/2016. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/TableViewBadPerformanceSample/TableViewBadPerformanceSampleTests/TableViewBadPerformanceSampleTests.swift
// // TableViewBadPerformanceSampleTests.swift // TableViewBadPerformanceSampleTests // // Created by larryhou on 13/3/2016. // import XCTest @testable import TableViewBadPerformanceSample class TableViewBadPerformanceSampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/TableViewBadPerformanceSample/TableViewBadPerformanceSampleUITests/TableViewBadPerformanceSampleUITests.swift
// // TableViewBadPerformanceSampleUITests.swift // TableViewBadPerformanceSampleUITests // // Created by larryhou on 13/3/2016. // import XCTest class TableViewBadPerformanceSampleUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
swift-master/CarolCamera/CarolCamera/LivePreviewView.swift
// // LivePreviewView.swift // CarolCamera // // Created by larryhou on 29/11/2015. // import Foundation import UIKit import AVFoundation class LivePreivewView: UIView { override class func layerClass() -> AnyClass { return AVCaptureVideoPreviewLayer.self } var session: AVCaptureSession { get { return (self.layer as! AVCaptureVideoPreviewLayer).session } set { (self.layer as! AVCaptureVideoPreviewLayer).session = newValue } } }
swift-master/CarolCamera/CarolCamera/AppDelegate.swift
// // AppDelegate.swift // CarolCamera // // Created by larryhou on 29/11/2015. // import UIKit import CoreData import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume) // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. let captureController = window?.rootViewController as! CaptureViewController captureController.restoreVolume() } func applicationDidEnterBackground(application: UIApplication) { print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume) // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume) } func applicationDidBecomeActive(application: UIApplication) { print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume) // 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 applicationWillTerminate(application: UIApplication) { print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume) let captureController = window?.rootViewController as! CaptureViewController captureController.restoreVolume() // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.larryhou.samples.CarolCamera" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CarolCamera", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
swift-master/CarolCamera/CarolCamera/CaptureViewController.swift
// // ViewController.swift // CarolCamera // // Created by larryhou on 29/11/2015. // import UIKit import AVFoundation import MediaPlayer import Photos class CaptureViewController: UIViewController, AVCaptureFileOutputRecordingDelegate { var CONTEXT_LENS_LENGTH: Int = 0 var CONTEXT_ISO: Int = 0 var CONTEXT_EXPOSURE_DURATION: Int = 0 var CONTEXT_OUTPUT_VOLUME: Int = 0 var CONTEXT_MOVIE_RECORDING: Int = 0 var CONTEXT_SESSION_RUNNING: Int = 0 var CONTEXT_LIGHT_BOOST: Int = 0 var CONTEXT_ADJUSTING_FOCUS: Int = 0 @IBOutlet var previewView: LivePreivewView! @IBOutlet var flashView: UIView! @IBOutlet weak var recordingView: UIView! @IBOutlet weak var recordingMeter: UILabel! @IBOutlet weak var recordingIndicator: UIImageView! @IBOutlet weak var isoMeter: UILabel! @IBOutlet weak var focusIndicator: UIImageView! private var session: AVCaptureSession! private var sessionQueue: dispatch_queue_t! private var camera: AVCaptureDevice! private var photoOutput: AVCaptureStillImageOutput! private var movieOutput: AVCaptureMovieFileOutput! private var backgroundRecordingID: UIBackgroundTaskIdentifier! private var originVolume: Float = 1.0 private var restoring = false private var timestamp: NSDate! private var timer: NSTimer! private var changeVolume: Float->Void = {volume in} dynamic var recording = false class func deviceWithMediaType(mediaType: String, position: AVCaptureDevicePosition) -> AVCaptureDevice { let devices = AVCaptureDevice.devicesWithMediaType(mediaType) as! [AVCaptureDevice] var target = devices.first for item in devices { if item.position == position { target = item break } } return target! } func restoreVolume() { if originVolume != AVAudioSession.sharedInstance().outputVolume { restoring = true changeVolume(originVolume) } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() focusIndicator.hidden = true isoMeter.hidden = true recordingView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) recordingView.alpha = 0.0 let volumeView = MPVolumeView(frame: CGRect(x: -100, y: 0, width: 10, height: 0)) volumeView.sizeToFit() view.addSubview(volumeView) for view in volumeView.subviews { if view.dynamicType.description() == "MPVolumeSlider" { let slider = view as! UISlider changeVolume = { value in dispatch_async(dispatch_get_main_queue()) { slider.setValue(value, animated: true) slider.sendActionsForControlEvents(.TouchUpInside) } } break } } addObserver(self, forKeyPath: "recording", options: .New, context: &CONTEXT_MOVIE_RECORDING) AVAudioSession.sharedInstance().addObserver(self, forKeyPath: "outputVolume", options: [.New, .Old], context: &CONTEXT_OUTPUT_VOLUME) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) originVolume = AVAudioSession.sharedInstance().outputVolume session = AVCaptureSession() session.addObserver(self, forKeyPath: "running", options: .New, context: &CONTEXT_SESSION_RUNNING) session.sessionPreset = AVCaptureSessionPresetPhoto previewView.session = session sessionQueue = dispatch_queue_create("CaptureSessionQueue", DISPATCH_QUEUE_SERIAL) var authorized = true let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch status { case .NotDetermined, .Denied: dispatch_suspend(self.sessionQueue) AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { (granted: Bool) in if !granted { authorized = false } dispatch_resume(self.sessionQueue) } default: print(status, status.rawValue) } dispatch_async(self.sessionQueue) { if !authorized { return } self.backgroundRecordingID = UIBackgroundTaskInvalid // MARK: camera input let cameraDevice = CaptureViewController.deviceWithMediaType(AVMediaTypeVideo, position: .Back) var cameraInput: AVCaptureDeviceInput! = nil do { cameraInput = try AVCaptureDeviceInput(device: cameraDevice) } catch { self.showAlertMessage(String(error)) return } self.camera = cameraDevice self.session.beginConfiguration() if self.session.canAddInput(cameraInput) { self.session.addInput(cameraInput) dispatch_async(dispatch_get_main_queue()) { var vedioOrientation = AVCaptureVideoOrientation.Portrait let deviceOrientation = UIApplication.sharedApplication().statusBarOrientation if deviceOrientation != .Unknown { vedioOrientation = AVCaptureVideoOrientation(rawValue: deviceOrientation.rawValue)! } (self.previewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation = vedioOrientation } } else { self.showAlertMessage("Could not add camera input") return } // MARK: microphone input let audio = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio) var audioInput: AVCaptureDeviceInput! = nil do { audioInput = try AVCaptureDeviceInput(device: audio) } catch {} if audioInput != nil && self.session.canAddInput(audioInput) { self.session.addInput(audioInput) } else { self.showAlertMessage("Could not add microphone input") } // MARK: photo output let photoOutput = AVCaptureStillImageOutput() if self.session.canAddOutput(photoOutput) { self.session.addOutput(photoOutput) self.photoOutput = photoOutput photoOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] photoOutput.highResolutionStillImageOutputEnabled = true } else { self.showAlertMessage("Could not add photo output") } // MARK: movie output let movieOutput = AVCaptureMovieFileOutput() if self.session.canAddOutput(movieOutput) { self.session.addOutput(movieOutput) self.movieOutput = movieOutput let movieConnnection = movieOutput.connectionWithMediaType(AVMediaTypeVideo) if movieConnnection.supportsVideoStabilization { movieConnnection.preferredVideoStabilizationMode = .Auto } } else { self.showAlertMessage("Could not add movie output") } self.session.commitConfiguration() self.camera.addObserver(self, forKeyPath: "lensPosition", options: .New, context: &self.CONTEXT_LENS_LENGTH) self.camera.addObserver(self, forKeyPath: "ISO", options: .New, context: &self.CONTEXT_ISO) self.camera.addObserver(self, forKeyPath: "exposureDuration", options: .New, context: &self.CONTEXT_EXPOSURE_DURATION) self.camera.addObserver(self, forKeyPath: "lowLightBoostEnabled", options: .New, context: &self.CONTEXT_LIGHT_BOOST) self.camera.addObserver(self, forKeyPath: "adjustingFocus", options: .New, context: &self.CONTEXT_ADJUSTING_FOCUS) self.session.startRunning() } } func setupCamera(device: AVCaptureDevice) { do { try device.lockForConfiguration() } catch { return } if device.smoothAutoFocusSupported { device.smoothAutoFocusEnabled = true } if device.lowLightBoostSupported { device.automaticallyEnablesLowLightBoostWhenAvailable = true } device.unlockForConfiguration() focusWithMode(.ContinuousAutoFocus, exposureMode: .ContinuousAutoExposure, pointOfInterest: CGPoint(x: 0.5, y: 0.5)) } @IBAction func screenTapped(sender: UITapGestureRecognizer) { print("tap") var point = sender.locationInView(sender.view) point = (previewView.layer as! AVCaptureVideoPreviewLayer).captureDevicePointOfInterestForPoint(point) focusWithMode(.ContinuousAutoFocus, exposureMode: .ContinuousAutoExposure, pointOfInterest: point) } func focusWithMode(focusMode: AVCaptureFocusMode, exposureMode: AVCaptureExposureMode, pointOfInterest: CGPoint) { let camera = self.camera dispatch_async(self.sessionQueue) { do { try camera.lockForConfiguration() } catch { return } if camera.focusPointOfInterestSupported { camera.focusPointOfInterest = pointOfInterest } if camera.isFocusModeSupported(focusMode) { camera.focusMode = focusMode } if camera.exposurePointOfInterestSupported { camera.exposurePointOfInterest = pointOfInterest } if camera.isExposureModeSupported(exposureMode) { camera.exposureMode = exposureMode } camera.subjectAreaChangeMonitoringEnabled = true camera.unlockForConfiguration() } } var snapIndex = 0 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &CONTEXT_LENS_LENGTH { // print("lensPosition", camera.lensPosition) } else if context == &CONTEXT_EXPOSURE_DURATION { // print("exposureDuration", camera.exposureDuration) } else if context == &CONTEXT_ISO { isoMeter.text = String(format: "ISO:%04d", Int(camera.ISO)) } else if context == &CONTEXT_OUTPUT_VOLUME { let newVolume = change?[NSKeyValueChangeNewKey] as! Float let oldVolume = change?[NSKeyValueChangeOldKey] as! Float if abs(newVolume - oldVolume) == 0.5 || !session.running { return } if restoring { restoring = false return } ++snapIndex print("snap", String(format: "%03d %@ %.3f %.3f", snapIndex, newVolume > oldVolume ? "+" : "-", newVolume, oldVolume)) if newVolume > oldVolume { snapCamera() } else { recording = !recording } checkVolumeButton() } else if context == &CONTEXT_MOVIE_RECORDING { toggleRecording() } else if context == &CONTEXT_SESSION_RUNNING { print("running", session.running) if session.running { setupCamera(camera) checkVolumeButton() } } else if context == &CONTEXT_LIGHT_BOOST { print("lowLightBoostEnabled", camera.lowLightBoostEnabled) } else if context == &CONTEXT_ADJUSTING_FOCUS { focusIndicator.hidden = !camera.adjustingFocus if camera.adjustingFocus { focusIndex = 0 NSTimer.scheduledTimerWithTimeInterval(0.15, target: self, selector: "twinkleFocusBox:", userInfo: nil, repeats: true) } } } var focusIndex = 0 func twinkleFocusBox(timer: NSTimer) { if !camera.adjustingFocus { timer.invalidate() return } focusIndex++ let alpha: CGFloat if focusIndex % 2 == 1 { alpha = 1.0 } else { alpha = 0.5 } focusIndicator.layer.removeAllAnimations() UIView.animateWithDuration(0.1) { self.focusIndicator.alpha = alpha } } func updateRecordingMeter(interval: NSTimeInterval) { let time = Int(interval) let sec = time % 60 let min = (time / 60) % 60 let hur = (time / 60) / 60 recordingMeter.text = String(format: "%02d:%02d:%02d", hur, min, sec) } func timerUpdate(timer: NSTimer) { updateRecordingMeter(timer.fireDate.timeIntervalSinceDate(timestamp)) recordingIndicator.hidden = !recordingIndicator.hidden } func toggleRecording() { dispatch_async(sessionQueue) { if !self.movieOutput.recording { print("recording", true) self.session.sessionPreset = AVCaptureSessionPresetHigh if UIDevice.currentDevice().multitaskingSupported { self.backgroundRecordingID = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil) } let movieConnection = self.movieOutput.connectionWithMediaType(AVMediaTypeVideo) movieConnection.videoOrientation = (self.view.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation let movieFileName = NSString(string: NSProcessInfo.processInfo().globallyUniqueString).stringByAppendingPathExtension("mov")! let movieFilePath = NSString(string: NSTemporaryDirectory()).stringByAppendingPathComponent(movieFileName) self.movieOutput.startRecordingToOutputFileURL(NSURL.fileURLWithPath(movieFilePath), recordingDelegate: self) } else { print("recording", false) self.movieOutput.stopRecording() } } } func twenkleScreen() { flashView.layer.removeAllAnimations() flashView.hidden = false flashView.alpha = 1.0 let animations = { self.flashView.alpha = 0.0 } UIView.animateWithDuration(0.2, animations: animations) { _ in self.flashView.hidden = true } } // MARK: take still image func snapCamera() { twenkleScreen() dispatch_async(self.sessionQueue) { let imageConnection = self.photoOutput.connectionWithMediaType(AVMediaTypeVideo) imageConnection.videoOrientation = (self.previewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation self.photoOutput.captureStillImageAsynchronouslyFromConnection(imageConnection) { (buffer: CMSampleBuffer!, error: NSError!) in if error != nil { self.showAlertMessage(String(format: "Error capture still image %@", error)) } else if buffer != nil { let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) in if status == PHAuthorizationStatus.Authorized { let photoWriting = { PHAssetCreationRequest.creationRequestForAsset().addResourceWithType(.Photo, data: data, options: nil) } PHPhotoLibrary.sharedPhotoLibrary().performChanges(photoWriting) { (success, _: NSError?) in if !success { self.showAlertMessage("Error occured while saving image to photo library") } } } } } } } } // MARK: check volume button func checkVolumeButton() { do { try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation) } catch {} let volume = AVAudioSession.sharedInstance().outputVolume if volume == 1.0 || volume == 0.0 { changeVolume(0.5) } } // MARK: record delegate func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) { print(__FUNCTION__) dispatch_async(dispatch_get_main_queue()) { self.recordingView.layer.removeAllAnimations() self.recordingView.alpha = 0.5 UIView.animateWithDuration(0.2) { self.recordingView.alpha = 1.0 } self.timestamp = NSDate() self.updateRecordingMeter(0) self.timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerUpdate:", userInfo: nil, repeats: true) } } func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { print(__FUNCTION__) timer.invalidate() dispatch_async(dispatch_get_main_queue()) { self.recordingView.layer.removeAllAnimations() UIView.animateWithDuration(0.5) { self.recordingView.alpha = 0.0 } } session.sessionPreset = AVCaptureSessionPresetPhoto checkVolumeButton() // MARK: write movie file let backgroundTaskID = self.backgroundRecordingID self.backgroundRecordingID = UIBackgroundTaskInvalid let cleanup = { do { try NSFileManager.defaultManager().removeItemAtURL(outputFileURL) } catch {} if backgroundTaskID != UIBackgroundTaskInvalid { UIApplication.sharedApplication().endBackgroundTask(backgroundTaskID) } } var success = true if error != nil { success = error.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as! Bool } if success { PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) in if status == PHAuthorizationStatus.Authorized { let movieWriting = { let options = PHAssetResourceCreationOptions() options.shouldMoveFile = true let request = PHAssetCreationRequest.creationRequestForAsset() request.addResourceWithType(.Video, fileURL: outputFileURL, options: options) } PHPhotoLibrary.sharedPhotoLibrary().performChanges(movieWriting) { (success: Bool, error: NSError?) in if !success { self.showAlertMessage(String(format: "Could not save movie to photo library: %@", error!)) } cleanup() } } else { cleanup() } } } else { cleanup() } } // MARK: alert func showAlertMessage(message: String) { let alert = UIAlertController(title: "ERROR", message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "I've got it!", style: .Default, handler: nil)) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alert, animated: true, completion: nil) } } // MARK: orientation override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let deviceOrientation = UIDevice.currentDevice().orientation if deviceOrientation.isPortrait || deviceOrientation.isLandscape { (previewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation = AVCaptureVideoOrientation(rawValue: deviceOrientation.rawValue)! } } override func prefersStatusBarHidden() -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/CarolCamera/CarolCameraUITests/CarolCameraUITests.swift
// // CarolCameraUITests.swift // CarolCameraUITests // // Created by larryhou on 29/11/2015. // import XCTest class CarolCameraUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
swift-master/CarolCamera/CarolCameraTests/CarolCameraTests.swift
// // CarolCameraTests.swift // CarolCameraTests // // Created by larryhou on 29/11/2015. // import XCTest @testable import CarolCamera class CarolCameraTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/Regions/Regions/PlacemarkViewController.swift
// // LocationViewController.swift // Regions // // Created by doudou on 9/5/14. // import Foundation import CoreLocation import UIKit class PlacemarkViewController: UITableViewController { let CELL_IDENTIFIER: String = "PlacemarkCell" var placemark: CLPlacemark! private var list: [NSObject]! override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "PlacemarkCell", bundle: nil), forCellReuseIdentifier: CELL_IDENTIFIER) list = [] for (key, value) in placemark.addressDictionary { list.append(key) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0:return "Attributes" case 1:return "Address Dictionary" default:return "Geographic" } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(CELL_IDENTIFIER) as UITableViewCell! if indexPath.section == 0 { switch indexPath.row { case 0: cell.textLabel?.text = "name" cell.detailTextLabel?.text = placemark.name case 1: cell.textLabel?.text = "country" cell.detailTextLabel?.text = placemark.country case 2: cell.textLabel?.text = "administrativeArea" cell.detailTextLabel?.text = placemark.administrativeArea case 3: cell.textLabel?.text = "subAdministrativeArea" cell.detailTextLabel?.text = placemark.subAdministrativeArea case 4: cell.textLabel?.text = "locality" cell.detailTextLabel?.text = placemark.locality case 5: cell.textLabel?.text = "subLocality" cell.detailTextLabel?.text = placemark.subLocality case 6: cell.textLabel?.text = "thoroughfare" cell.detailTextLabel?.text = placemark.thoroughfare case 7: cell.textLabel?.text = "subThoroughfare" cell.detailTextLabel?.text = placemark.subThoroughfare case 8: cell.textLabel?.text = "ISOcountryCode" cell.detailTextLabel?.text = placemark.ISOcountryCode default: cell.textLabel?.text = "postalCode" cell.detailTextLabel?.text = placemark.postalCode } } else if indexPath.section == 1 { var key = list[indexPath.row] var value: AnyObject = placemark.addressDictionary[key]! cell.textLabel?.text = key.description if value is [String] { cell.detailTextLabel?.text = (value as [String]).first } else { cell.detailTextLabel?.text = (value as String) } } else { if indexPath.row == 0 { cell.textLabel?.text = "inlandWater" cell.detailTextLabel?.text = placemark.inlandWater } else { cell.textLabel?.text = "ocean" cell.detailTextLabel?.text = placemark.ocean } } return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0:return 10 case 1:return placemark.addressDictionary.count default:return 2 } } }
swift-master/Regions/Regions/MapAnnotation.swift
// // MapAnnotation.swift // Regions // // Created by larryhou on 8/28/14. // import Foundation import MapKit class RegionAnnotation: NSObject, MKAnnotation { dynamic var coordinate: CLLocationCoordinate2D var region: CLCircularRegion dynamic var title: String! dynamic var subtitle: String! init(coordinate: CLLocationCoordinate2D, region: CLCircularRegion) { self.coordinate = coordinate self.region = region self.title = String(format: "纬度: %.4f° 经度: %.4f°", coordinate.latitude, coordinate.longitude) } func update(#location:CLLocation!) { if location != nil { self.coordinate = location.coordinate self.title = String(format: "纬度:%.4f° 经度%.4f°", location.coordinate.latitude, location.coordinate.longitude) self.subtitle = String(format: "精度:%.2f米", location.horizontalAccuracy) } else { self.title = nil self.subtitle = nil } } } class DeviceAnnotation: NSObject, MKAnnotation { dynamic var coordinate: CLLocationCoordinate2D dynamic var location: CLLocation! dynamic var title: String! dynamic var subtitle: String! init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate super.init() update(coordinate: coordinate) } func update(#location:CLLocation) { self.location = location update(coordinate: location.coordinate) } func update(#coordinate:CLLocationCoordinate2D) { self.title = String(format: "纬:%.6f° 经:%.6f°", coordinate.latitude, coordinate.longitude) } func update(#placemark:CLPlacemark) { self.subtitle = placemark.name.componentsSeparatedByString(placemark.administrativeArea).last } }
swift-master/Regions/Regions/AppDelegate.swift
// // AppDelegate.swift // Regions // // Created by doudou on 8/26/14. // import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication!) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // 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 applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/Regions/Regions/ChinaGPS.swift
// // ChinaGPS.swift // Regions // // Created by doudou on 8/30/14. // 参考资料:https://breeswish.org/blog/2013/10/17/google-map-offset-transform/ // import Foundation import CoreLocation class ChinaGPS { class private func transformLon(x: Double, _ y: Double) -> Double { var lon = 300.0 + x + 2.0 * y + 0.1 * x * x lon += 0.1 * x * y + 0.1 * sqrt(fabs(x)) //FIXME: swift暂时不支持复杂的混合元算 lon += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0 lon += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0 lon += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0 return lon } class private func transformLat(x: Double, _ y: Double) -> Double { var lat = -100.0 + 2.0 * x + 3.0 * y lat += 0.2 * y * y + 0.1 * x * y lat += 0.2 * sqrt(fabs(x)) //FIXME: swift暂时不支持复杂的混合元算 lat += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0 lat += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0 lat += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0 return lat } class func encrypt(latitude lat: Double, longitude lon: Double)->(latitude: Double, longitude: Double) { let A = 6378245.0 let EE = 0.00669342162296594323 var offset = (lat:0.0, lon:0.0) offset.lat = transformLat(lon - 105.0, lat - 35.0) offset.lon = transformLon(lon - 105.0, lat - 35.0) var radian = lat / 180.0 * M_PI var magic = sin(radian) magic = 1 - EE * magic * magic let MAGIC_SQRT = sqrt(magic) offset.lat = (offset.lat * 180.0) / ((A * (1 - EE)) / (magic * MAGIC_SQRT) * M_PI) offset.lon = (offset.lon * 180.0) / (A / MAGIC_SQRT * cos(radian) * M_PI) return (lat + offset.lat, lon + offset.lon) } class func encrypt(location: CLLocation) -> CLLocation { var gps = encrypt(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) var ret = CLLocation(coordinate: CLLocationCoordinate2D(latitude: gps.latitude, longitude: gps.longitude), altitude: location.altitude, horizontalAccuracy: location.horizontalAccuracy, verticalAccuracy: location.verticalAccuracy, timestamp: location.timestamp) return ret } }
swift-master/Regions/Regions/ChinaGPSTools.swift
// // ChinaGPSTools.swift // Regions // // Created by larryhou on 8/29/14. // import Foundation
swift-master/Regions/Regions/RegionViewController.swift
// // ViewController.swift // Regions // // Created by doudou on 8/26/14. // import UIKit import CoreLocation import MapKit class RegionViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource { enum EventState { case Enter case Exit } struct RegionMonitorEvent { let region: CLCircularRegion let timestamp: NSDate let state: EventState } let LAT_SPAN: CLLocationDistance = 500.0 let LON_SPAN: CLLocationDistance = 500.0 let MONITOR_RADIUS: CLLocationDistance = 50.0 @IBOutlet weak var map: MKMapView! @IBOutlet weak var tableView: UITableView! @IBOutlet var insertButton: UIBarButtonItem! @IBOutlet var searchButton: UIBarButtonItem! private var locationManager: CLLocationManager! private var location: CLLocation! private var deviceAnnotation: DeviceAnnotation! private var isUpdated: Bool! private var placemark: CLPlacemark! private var heading: CLHeading! private var monitorEvents: [RegionMonitorEvent]! private var dateFormatter: NSDateFormatter! private var geocoder: CLGeocoder! private var geotime: NSDate! override func viewDidLoad() { super.viewDidLoad() monitorEvents = [] dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" geocoder = CLGeocoder() tableView.alpha = 0.0 tableView.hidden = true map.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: 22.55, longitude: 113.94), LAT_SPAN, LON_SPAN) locationManager = CLLocationManager() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.delegate = self locationManager.startUpdatingLocation() if CLLocationManager.headingAvailable() { locationManager.headingFilter = 1.0 locationManager.startUpdatingHeading() } for region in locationManager.monitoredRegions { locationManager.stopMonitoringForRegion(region as CLRegion) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { isUpdated = false } // MARK: 滚动列表展示 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("RegionEventCell") as UITableViewCell! var text = "" var event = monitorEvents[indexPath.row] switch event.state { case .Enter: text += "进入" case .Exit: text += "走出" } text += " \(dateFormatter.stringFromDate(event.timestamp))" cell.textLabel?.text = text return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return monitorEvents.count } // MARK: 页签组件切换 @IBAction func segementChanged(sender: UISegmentedControl) { let duration: NSTimeInterval = 0.4 if sender.selectedSegmentIndex == 0 { navigationItem.setLeftBarButtonItem(searchButton, animated: true) navigationItem.setRightBarButtonItem(insertButton, animated: true) map.hidden = false UIView.animateWithDuration(duration, animations: { self.map.alpha = 1.0 self.tableView.alpha = 0.0 }, completion: { (_) in self.tableView.hidden = true }) } else { navigationItem.setLeftBarButtonItem(nil, animated: true) navigationItem.setRightBarButtonItem(nil, animated: true) tableView.reloadData() tableView.hidden = false UIView.animateWithDuration(duration / 2.0, animations: { self.map.alpha = 0.0 self.tableView.alpha = 1.0 }, completion: { (_) in self.map.hidden = true }) } UIView.commitAnimations() } // MARK: 按钮交互 @IBAction func showDeviceLocation(sender: UIBarButtonItem) { if map.userLocation != nil { map.setRegion(MKCoordinateRegionMakeWithDistance(map.userLocation.coordinate, LAT_SPAN, LON_SPAN), animated: true) } } @IBAction func inertMonitorRegion(sender: UIBarButtonItem) { if (location == nil || map.userLocation == nil) { return } var lat = map.userLocation.coordinate.latitude - location.coordinate.latitude var lon = map.userLocation.coordinate.longitude - location.coordinate.longitude var region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: map.centerCoordinate.latitude - lat, longitude: map.centerCoordinate.longitude - lon), radius: MONITOR_RADIUS, identifier: String(format: "%.8f-%.8f", map.centerCoordinate.latitude, map.centerCoordinate.longitude)) var annotation = RegionAnnotation(coordinate: map.centerCoordinate, region: region) map.addAnnotation(annotation) map.addOverlay(MKCircle(centerCoordinate: annotation.coordinate, radius: MONITOR_RADIUS)) if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion) { locationManager.startMonitoringForRegion(region) } } // MARK: 地图相关 func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation.isKindOfClass(DeviceAnnotation) { let identifier = "DeviceAnnotationView" var anView = map.dequeueReusableAnnotationViewWithIdentifier(identifier) as MKPinAnnotationView! if anView == nil { anView = MKPinAnnotationView(annotation: deviceAnnotation, reuseIdentifier: identifier) anView.canShowCallout = true anView.pinColor = MKPinAnnotationColor.Purple } else { anView.annotation = annotation } if placemark != nil { var button = UIButton.buttonWithType(.DetailDisclosure) as UIButton button.addTarget(self, action: "displayPlacemarkInfo", forControlEvents: UIControlEvents.TouchUpInside) anView.rightCalloutAccessoryView = button } else { anView.rightCalloutAccessoryView = nil } return anView } else if annotation.isKindOfClass(RegionAnnotation) { let identifier = "RegionAnnotationView" var anView = map.dequeueReusableAnnotationViewWithIdentifier(identifier) as MKPinAnnotationView! if anView == nil { anView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) anView.canShowCallout = true anView.pinColor = MKPinAnnotationColor.Green } else { anView.annotation = annotation } return anView } return nil } func displayPlacemarkInfo() { var locationCtrl = PlacemarkViewController(nibName: "PlacemarkInfoView", bundle: nil) locationCtrl.placemark = placemark navigationController?.pushViewController(locationCtrl, animated: true) } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if overlay.isKindOfClass(MKCircle) { var render = MKCircleRenderer(overlay: overlay) render.strokeColor = UIColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.5) render.fillColor = UIColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.2) render.lineWidth = 1.0 return render } return nil } // MARK: 方向定位 func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) { heading = newHeading } // MARK: 定位相关 func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) { location = newLocation var chinaloc = ChinaGPS.encrypt(newLocation) if deviceAnnotation == nil { deviceAnnotation = DeviceAnnotation(coordinate: chinaloc.coordinate) map.addAnnotation(deviceAnnotation) } else { deviceAnnotation.coordinate = chinaloc.coordinate } deviceAnnotation.update(location: chinaloc) if geotime == nil || fabs(geotime.timeIntervalSinceNow) > 10.0 { geotime = NSDate() println("geocode", geotime.description) geocoder.reverseGeocodeLocation(chinaloc, completionHandler: { (placemarks, error) in if error == nil { self.processPlacemark(placemarks as [CLPlacemark]) } else { println(error) } }) } map.selectAnnotation(deviceAnnotation, animated: false) } func processPlacemark(placemarks: [CLPlacemark]) { var initialized = !(self.placemark == nil) placemark = placemarks.first! if placemark != nil && !initialized { map.removeAnnotation(deviceAnnotation) map.addAnnotation(deviceAnnotation) map.selectAnnotation(deviceAnnotation, animated: true) } if placemark != nil { deviceAnnotation.update(placemark: placemark) } } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { var event = RegionMonitorEvent(region: region as CLCircularRegion, timestamp: NSDate(), state: .Enter) monitorEvents.append(event) if !tableView.hidden { tableView.reloadData() } } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { var event = RegionMonitorEvent(region: region as CLCircularRegion, timestamp: NSDate(), state: .Exit) monitorEvents.append(event) if !tableView.hidden { tableView.reloadData() } } func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) { UIAlertView(title: "区域监听失败", message: error?.description, delegate: nil, cancelButtonTitle: "我知道了").show() } // MARK: 地图相关 func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) { if !isUpdated { map.setCenterCoordinate(userLocation.coordinate, animated: true) isUpdated = true } } }
swift-master/Regions/RegionsTests/RegionsTests.swift
// // RegionsTests.swift // RegionsTests // // Created by doudou on 8/26/14. // import UIKit import XCTest class RegionsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/NSURLDownload/NSURLDownload/ViewController.swift
// // ViewController.swift // NSURLDownload // // Created by larryhou on 3/25/15. // import Cocoa import Foundation import AppKit import WebKit class ViewController: NSViewController, NSURLDownloadDelegate { @IBOutlet weak var indicator: NSProgressIndicator! @IBOutlet weak var web: WebView! private var received = 0.0 private var total = 0.0 override func viewDidLoad() { super.viewDidLoad() start() } func start() { let url = NSURL(string: "http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.0.2.dmg") if url == nil { println("Cann't create NSURL object!") return } var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60.0) var download = NSURLDownload(request: request, delegate: self) download.deletesFileUponFailure = false println(download) indicator.doubleValue = 0 indicator.usesThreadedAnimation = true request = NSURLRequest(URL: NSURL(string: "http://im.qq.com")!) web.mainFrame.loadRequest(request) } func download(download: NSURLDownload, decideDestinationWithSuggestedFilename filename: String) { let path = NSHomeDirectory().stringByAppendingPathComponent("Desktop").stringByAppendingPathComponent(filename) download.setDestination(path, allowOverwrite: true) } func download(download: NSURLDownload, didCreateDestination path: String) { NSLog("%@", "created: \(path)") } func download(download: NSURLDownload, didReceiveResponse response: NSURLResponse) { total = Double(response.expectedContentLength) indicator.doubleValue = 0 NSLog("%@", response) } func downloadDidBegin(download: NSURLDownload) { NSLog("%@", "begin") } func download(download: NSURLDownload, didReceiveDataOfLength length: Int) { received += Double(length) indicator.doubleValue = received * 100 / total NSLog("data: %6d \t %.2f%", length, received * 100 / total) } func downloadDidFinish(download: NSURLDownload) { NSLog("%@", "finish") } func download(download: NSURLDownload, didFailWithError error: NSError) { NSLog("%@", error) println(error) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
swift-master/NSURLDownload/NSURLDownload/DownloadController.swift
// // DownloadController.swift // NSURLDownload // // Created by larryhou on 3/25/15. // import Foundation
swift-master/NSURLDownload/NSURLDownload/AppDelegate.swift
// // AppDelegate.swift // NSURLDownload // // Created by larryhou on 3/25/15. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
swift-master/NSURLDownload/NSURLDownload/main.swift
// // main.swift // NSURLDownload // // Created by larryhou on 3/25/15. // import Foundation println("Hello, World!")
swift-master/NSURLDownload/NSURLDownloadTests/NSURLDownloadTests.swift
// // NSURLDownloadTests.swift // NSURLDownloadTests // // Created by larryhou on 3/25/15. // import Cocoa import XCTest class NSURLDownloadTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/MRCodes/MRCodesUITests/MRCodesUITests.swift
// // MRCodesUITests.swift // MRCodesUITests // // Created by larryhou on 13/12/2015. // import XCTest class MRCodesUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
swift-master/MRCodes/MRCodes/ResultViewController.swift
// // ResultViewController.swift // MRCodes // // Created by larryhou on 2018/3/25. // import Foundation import AVFoundation import UIKit class ResultView: UIView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.cornerRadius = 8 if #available(iOS 11, *) { layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] } } } class ResultViewController: UIViewController { var mrcObjects: [AVMetadataMachineReadableCodeObject]! @IBOutlet weak var resultView: UIView! @IBOutlet weak var mrcContent: UITextView! @IBOutlet weak var mrcTitle: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.isHidden = true reload() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) resultView.frame = resultView.frame.offsetBy(dx: 0, dy: resultView.frame.height) animate(visible: true) view.isHidden = false } func animate(visible: Bool) { let frame = resultView.frame let bottom = CGRect(origin: CGPoint(x: 0, y: view.frame.height), size: frame.size) let top = bottom.offsetBy(dx: 0, dy: -frame.height) let to = visible ? top : bottom UIView.animate(withDuration: 0.3, animations: { self.resultView.frame = to }, completion: { if $0 && !visible { self.dismiss(animated: true, completion: nil) } }) } func reload() { if let data = mrcObjects.first, let stringValue = data.stringValue { if mrcTitle.text != data.type.rawValue { mrcTitle.text = data.type.rawValue } if mrcContent.text != stringValue { mrcContent.text = stringValue } } } }
swift-master/MRCodes/MRCodes/CameraPreviewView.swift
// // CameraPreviewView.swift // MRCodes // // Created by larryhou on 13/12/2015. // import Foundation import AVFoundation import UIKit extension CGPoint { func distance(to point: CGPoint) -> CGFloat { let dx = point.x - self.x let dy = point.y - self.y return sqrt(dx * dx + dy * dy) } } class CameraPreviewView: UIView { override static var layerClass: AnyClass { return AVCaptureVideoPreviewLayer.self } var session: AVCaptureSession! { get { return (self.layer as! AVCaptureVideoPreviewLayer).session } set { (self.layer as! AVCaptureVideoPreviewLayer).session = newValue } } } class CameraMetadataView: UIView { var mrcObjects: [AVMetadataMachineReadableCodeObject]! func setMetadataObjects(_ mrcObjects: [AVMetadataMachineReadableCodeObject]) { self.mrcObjects = unique(of: mrcObjects) setNeedsDisplay() } func getRelatedArea(of mrcObject: AVMetadataMachineReadableCodeObject) -> CGPath { var points: [CGPoint] = mrcObject.corners let path = CGMutablePath() path.move(to: points[0]) for i in 1..<points.count { path.addLine(to: points[i]) } path.addLine(to: points[0]) return path } func getRelatedCorners(of mrcObject: AVMetadataMachineReadableCodeObject) -> CGPath { let points = mrcObject.corners let length: CGFloat = 10 let path = CGMutablePath() for n in 0..<points.count { let pf = points[n] let pt = n < points.count - 1 ? points[n + 1] : points[0] let angle = atan2(pt.y - pf.y, pt.x - pf.x) let dx = length * cos(angle) let dy = length * sin(angle) path.move(to: pf) path.addLine(to: CGPoint(x: pf.x + dx, y: pf.y + dy)) path.move(to: pt) path.addLine(to: CGPoint(x: pt.x - dx, y: pt.y - dy)) } return path } func unique(of objects: [AVMetadataMachineReadableCodeObject]) -> [AVMetadataMachineReadableCodeObject] { guard objects.count >= 2 else {return objects} var list = objects.map({character(of: $0)}) list.sort(by: {$0.offset < $1.offset}) var result: [AVMetadataMachineReadableCodeObject] = [] var refer = list[0] result.append(refer.object) for n in 1..<list.count { let current = list[n] if current.center.distance(to: refer.center) < refer.radius { if current.radius > refer.radius { result[result.count - 1] = current.object } else {continue} } else { result.append(current.object) } refer = current } return result } func character(of mrcObject: AVMetadataMachineReadableCodeObject)->(center: CGPoint, radius: CGFloat, object: AVMetadataMachineReadableCodeObject, offset: CGFloat) { var center = CGPoint() for corner in mrcObject.corners { center.x += corner.x center.y += corner.y } center.x /= 4 center.y /= 4 let frameCenter = CGPoint(x: frame.origin.x + frame.width / 2, y: frame.origin.y + frame.height / 2) let offset = frameCenter.distance(to: center) let distances = mrcObject.corners.map { $0.distance(to: center) } let radius = distances.reduce(0, {$0 + $1}) / CGFloat(distances.count) return (center, radius, mrcObject, offset) } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else {return} if mrcObjects != nil && mrcObjects.count > 0 { context.saveGState() context.setLineJoin(.miter) context.setLineCap(.square) for n in 0..<mrcObjects.count { let mrc = mrcObjects[n] let color: UIColor = n == 0 ? .green : .yellow context.setStrokeColor(color.cgColor) context.setLineWidth(2.0) context.addPath(getRelatedCorners(of: mrc)) context.strokePath() let area = getRelatedArea(of: mrc) context.setLineWidth(0.5) context.addPath(area) context.strokePath() context.addPath(area) context.setFillColor(color.withAlphaComponent(0.1).cgColor) context.fillPath() if n == 0 { if let stringValue = mrc.stringValue { UIPasteboard.general.string = stringValue } } } context.restoreGState() } } }
swift-master/MRCodes/MRCodes/ReadViewController.swift
// // ViewController.swift // MRCodes // // Created by larryhou on 13/12/2015. // import UIKit import AVFoundation class ReadViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { private var FocusContext: String? private var ExposureContext: String? private var LensContext: String? @IBOutlet weak var torchSwitcher: UISwitch! @IBOutlet weak var previewView: CameraPreviewView! @IBOutlet weak var metadataView: CameraMetadataView! private var session: AVCaptureSession! private var activeCamera: AVCaptureDevice? override func viewDidLoad() { super.viewDidLoad() session = AVCaptureSession() session.sessionPreset = .photo previewView.session = session (previewView.layer as! AVCaptureVideoPreviewLayer).videoGravity = .resizeAspectFill AVCaptureDevice.requestAccess(for: .video) { (success: Bool) -> Void in let status = AVCaptureDevice.authorizationStatus(for: .video) if success { self.configSession() } else { print(status, status.rawValue) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let resultController = presentedViewController as? ResultViewController { resultController.animate(visible: false) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) torchSwitcher.isHidden = true if !session.isRunning { session.startRunning() } } func applicationWillEnterForeground() { metadataView.setMetadataObjects([]) } func findCamera(position: AVCaptureDevice.Position) -> AVCaptureDevice! { let list = AVCaptureDevice.devices() for device in list { if device.position == position { return device } } return nil } func configSession() { session.beginConfiguration() guard let camera = findCamera(position: .back) else {return} self.activeCamera = camera do { let cameraInput = try AVCaptureDeviceInput(device: camera) if session.canAddInput(cameraInput) { session.addInput(cameraInput) } setupCamera(camera: camera) } catch {} let metadata = AVCaptureMetadataOutput() if session.canAddOutput(metadata) { session.addOutput(metadata) metadata.setMetadataObjectsDelegate(self, queue: .main) var metadataTypes = metadata.availableMetadataObjectTypes for i in 0..<metadataTypes.count { if metadataTypes[i] == .face { metadataTypes.remove(at: i) break } } metadata.metadataObjectTypes = metadataTypes print(metadata.availableMetadataObjectTypes) } session.commitConfiguration() session.startRunning() } func setupCamera(camera: AVCaptureDevice) { do { try camera.lockForConfiguration() } catch { return } if camera.isFocusModeSupported(.continuousAutoFocus) { camera.focusMode = .continuousAutoFocus } if camera.isAutoFocusRangeRestrictionSupported { // camera.autoFocusRangeRestriction = .near } if camera.isSmoothAutoFocusSupported { camera.isSmoothAutoFocusEnabled = true } camera.unlockForConfiguration() // camera.addObserver(self, forKeyPath: "adjustingFocus", options: .new, context: &FocusContext) // camera.addObserver(self, forKeyPath: "exposureDuration", options: .new, context: &ExposureContext) camera.addObserver(self, forKeyPath: "lensPosition", options: .new, context: &LensContext) } @IBAction func torchStatusChange(_ sender: UISwitch) { guard let camera = self.activeCamera else { return } guard camera.isTorchAvailable else {return} do { try camera.lockForConfiguration() } catch { return } if sender.isOn { if camera.isTorchModeSupported(.on) { try? camera.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel) } } else { if camera.isTorchModeSupported(.off) { camera.torchMode = .off } checkTorchSwitcher(for: camera) } camera.unlockForConfiguration() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if context == &FocusContext || context == &ExposureContext || context == &LensContext, let camera = object as? AVCaptureDevice { // print(camera.exposureDuration.seconds, camera.activeFormat.minExposureDuration.seconds, camera.activeFormat.maxExposureDuration.seconds,camera.iso, camera.lensPosition) checkTorchSwitcher(for: camera) } } func checkTorchSwitcher(`for` camera: AVCaptureDevice) { if camera.iso >= 400 { torchSwitcher.isHidden = false } else { torchSwitcher.isHidden = !camera.isTorchActive } } // MARK: metadataObjects processing func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { var codes: [AVMetadataMachineReadableCodeObject] = [] var faces: [AVMetadataFaceObject] = [] let layer = previewView.layer as! AVCaptureVideoPreviewLayer for item in metadataObjects { guard let mrc = layer.transformedMetadataObject(for: item) else {continue} switch mrc { case is AVMetadataMachineReadableCodeObject: codes.append(mrc as! AVMetadataMachineReadableCodeObject) case is AVMetadataFaceObject: faces.append(mrc as! AVMetadataFaceObject) default: print(mrc) } } DispatchQueue.main.async { self.metadataView.setMetadataObjects(codes) self.showMetadataObjects(self.metadataView.mrcObjects) } } func showMetadataObjects(_ objects: [AVMetadataMachineReadableCodeObject]) { if let resultController = self.presentedViewController as? ResultViewController { resultController.mrcObjects = objects resultController.reload() resultController.animate(visible: true) } else { guard let resultController = storyboard?.instantiateViewController(withIdentifier: "ResultViewController") as? ResultViewController else { return } resultController.mrcObjects = objects resultController.view.frame = view.frame present(resultController, animated: false, completion: nil) } } // MARK: orientation override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let orientation = UIDevice.current.orientation if orientation.isLandscape || orientation.isPortrait { let layer = previewView.layer as! AVCaptureVideoPreviewLayer if layer.connection != nil { layer.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue)! } } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } override var prefersStatusBarHidden: Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/MRCodes/MRCodes/AppDelegate.swift
// // AppDelegate.swift // MRCodes // // Created by larryhou on 13/12/2015. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { UIApplication.shared.isIdleTimerDisabled = false // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { (window?.rootViewController as! ReadViewController).applicationWillEnterForeground() // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { UIApplication.shared.isIdleTimerDisabled = true // 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 applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/MRCodes/MRCodesTests/MRCodesTests.swift
// // MRCodesTests.swift // MRCodesTests // // Created by larryhou on 13/12/2015. // import XCTest @testable import MRCodes class MRCodesTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/CrashReport/CrashReport/ViewController.swift
// // ViewController.swift // CrashReport // // Created by larryhou on 8/4/16. // import Foundation import UIKit import GameplayKit class ViewController: UIViewController { var method: TestMethod = .none var bartitle: String = "" override func viewDidLoad() { navigationItem.title = bartitle switch method { case .null: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in let rect: CGRect? = nil print(rect!.width) } break case .memory: var list: [[UInt8]] = [] Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) {_ in let bytes = [UInt8](repeating: 10, count: 1024*1024) list.append(bytes) } break case .cpu: Timer.scheduledTimer(withTimeInterval: 0.0, repeats: false) {_ in self.ruineCPU() } break case .abort: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in abort() } break case .none: break } } func ruineCPU() { let width: Int32 = 110, height: Int32 = 110 let graph = GKGridGraph(fromGridStartingAt: int2(0, 0), width: width, height: height, diagonalsAllowed: false) var obstacles: [GKGridGraphNode] = [] let random = GKRandomSource.sharedRandom() for x in 0..<width { for y in 0..<height { let densitiy = 5 if random.nextInt(upperBound: densitiy) % densitiy == 1 { let node = graph.node(atGridPosition: int2(x, y)) obstacles.append(node!) } } } graph.remove(obstacles) func get_random_node() -> GKGraphNode { let nodes = graph.nodes! return nodes[random.nextInt(upperBound: nodes.count)] } while true { let queue = DispatchQueue(label: Date().description, qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.never, target: nil) queue.async { graph.findPath(from: get_random_node(), to: get_random_node()) } } } }
swift-master/CrashReport/CrashReport/TableViewController.swift
// // ViewController.swift // CrashReport // // Created by larryhou on 8/4/16. // import UIKit enum TestMethod: Int { case null = 0, memory, cpu, abort, none var description: String { switch self { case .null:return "null" case .memory:return "memory" case .cpu:return "cpu" case .abort:return "abort" case .none:return "none" } } } class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell")! if let method = TestMethod(rawValue: indexPath.row) { switch method { case .null: cell.textLabel?.text = "空指针访问" break case .memory: cell.textLabel?.text = "内存使用超限制" break case .cpu: cell.textLabel?.text = "CPU使用超限制" break case .abort: cell.textLabel?.text = "使用abort()制造闪退" break case .none: cell.textLabel?.text = "等待手动退出" break } } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "action" { if let controller = segue.destination as? ViewController { if let index = tableView.indexPathForSelectedRow, let method = TestMethod(rawValue: index.row) { tableView.deselectRow(at: index, animated: true) controller.method = method if let text = tableView.cellForRow(at: index)?.textLabel?.text { controller.bartitle = text } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print("memory warning") // Dispose of any resources that can be recreated. } }
swift-master/CrashReport/CrashReport/AppDelegate.swift
// // AppDelegate.swift // CrashReport // // Created by larryhou on 8/4/16. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // 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, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // 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 applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/CrashReport/CrashReportUITests/CrashReportUITests.swift
// // CrashReportUITests.swift // CrashReportUITests // // Created by larryhou on 8/4/16. // import XCTest class CrashReportUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. let app = XCUIApplication() let tablesQuery = app.tables tablesQuery.staticTexts["等待手动退出"].tap() app.navigationBars["等待手动退出"].buttons["测试列表"].tap() tablesQuery.staticTexts["CPU使用超限制"].tap() } }
swift-master/CrashReport/CrashReportTests/CrashReportTests.swift
// // CrashReportTests.swift // CrashReportTests // // Created by larryhou on 8/4/16. // import XCTest @testable import CrashReport class CrashReportTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
swift-master/Hardware/Hardware/ViewController.swift
// // ViewController.swift // Hardware // // Created by larryhou on 10/7/2017. // import UIKit class ItemCell: UITableViewCell { @IBOutlet var ib_name: UILabel! @IBOutlet var ib_value: UILabel! } class HeaderView: UITableViewHeaderFooterView { static let identifier = "section_header_view" var title: UILabel? override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) let title = UILabel() title.font = UIFont(name: "Courier New", size: 36) title.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(title) self.title = title let map: [String: Any] = ["title": title] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[title]-|", options: .alignAllLeft, metrics: nil, views: map)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[title]-|", options: .alignAllCenterY, metrics: nil, views: map)) backgroundView = UIView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { contentView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) } } class ViewController: UITableViewController { let background = DispatchQueue(label: "data_reload_queue") var data: [CategoryType: [ItemInfo]]! override func viewDidLoad() { super.viewDidLoad() data = [:] Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(reload), userInfo: nil, repeats: true) tableView.register(HeaderView.self, forHeaderFooterViewReuseIdentifier: HeaderView.identifier) self.navigationController?.navigationBar.titleTextAttributes = [.font: UIFont(name: "Courier New", size: 30)!] } @objc func reload() { background.async { HardwareModel.shared.reload() DispatchQueue.main.async { [unowned self] in self.data = [:] self.tableView.reloadData() } } } override func numberOfSections(in tableView: UITableView) -> Int { return 8 } private func filter(_ data: [ItemInfo]) -> [ItemInfo] { return data.filter({$0.parent == -1}) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let cate = CategoryType(rawValue: section) { if let count = self.data[cate]?.count, count > 0 { return count } let data = HardwareModel.shared.get(category: cate, reload: false) self.data[cate] = data return data.count } return 0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderView.identifier) as! HeaderView if let cate = CategoryType(rawValue: section) { header.title?.text = "\(cate)" } return header } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let cate = CategoryType(rawValue: section) { return "\(cate)" } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemCell if let cate = CategoryType(rawValue: indexPath.section), let data = self.data[cate] { let info = data[indexPath.row] cell.ib_value.text = info.value cell.ib_name.text = info.name } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "review", let cell = sender as? ItemCell { if let index = tableView.indexPath(for: cell), let cate = CategoryType(rawValue: index.section), let data = self.data[cate] { let item = data[index.row] if let dst = segue.destination as? ReviewController { dst.data = item } } } else { super.prepare(for: segue, sender: sender) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/Hardware/Hardware/ReviewController.swift
// // ReviewController.swift // Hardware // // Created by larryhou on 11/07/2017. // import Foundation import UIKit class ReviewController: UIViewController { @IBOutlet weak var ib_title: UILabel! @IBOutlet weak var ib_content: UILabel! var data: ItemInfo? override func viewDidLoad() { super.viewDidLoad() if let data = self.data { ib_title.text = data.name ib_title.sizeToFit() ib_content.text = data.value ib_content.sizeToFit() } } }
swift-master/Hardware/Hardware/AppDelegate.swift
// // AppDelegate.swift // Hardware // // Created by larryhou on 10/7/2017. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // 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, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // 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 applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Hardware") container.loadPersistentStores(completionHandler: { (_, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
swift-master/Hardware/Hardware/HardwareModel.swift
// // HardwareModel.swift // Hardware // // Created by larryhou on 10/7/2017. // import Foundation import CoreTelephony import AdSupport import UIKit import SystemConfiguration.CaptiveNetwork import CoreBluetooth enum CategoryType: Int { case telephony = 5, bluetooth = 6, process = 1, device = 0, screen = 2, network = 7, language = 3, timezone = 4 } struct ItemInfo { let id: Int, name, value: String let parent: Int init(name: String, value: String) { self.init(id: -1, name: name, value: value) } init(name: String, value: String, parent: Int) { self.init(id: -1, name: name, value: value, parent: parent) } init(id: Int, name: String, value: String, parent: Int = -1) { self.id = id self.name = name self.value = value self.parent = parent } } class HardwareModel: NSObject, CBCentralManagerDelegate { static private(set) var shared = HardwareModel() private var data: [CategoryType: [ItemInfo]] = [:] @discardableResult func reload() -> [CategoryType: [ItemInfo]] { var result: [CategoryType: [ItemInfo]] = [:] let categories: [CategoryType] = [.telephony, .process, .device, .screen, .network, .language, .bluetooth] for cate in categories { result[cate] = get(category: cate, reload: true) } return result } func get(category: CategoryType, reload: Bool = false) -> [ItemInfo] { if !reload, let data = self.data[category] { return data } let data: [ItemInfo] switch category { case .telephony: data = getTelephony() case .process: data = getProcess() case .device: data = getDevice() case .screen: data = getScreen() case .network: data = getNetwork() case .language: data = getLanguage() case .timezone: data = getTimezone() case .bluetooth: data = getBluetooth() } self.data[category] = data return data } var bluetooth: CBCentralManager! private func getBluetooth() -> [ItemInfo] { if bluetooth == nil { var result: [ItemInfo] = [] let options: [String: Any] = [CBCentralManagerOptionShowPowerAlertKey: 0] bluetooth = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: options) result.append(ItemInfo(name: "state", value: format(of: bluetooth.state))) return result } else { return self.data[.bluetooth]! } } private func format(of type: CBManagerState) -> String { switch type { case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" case .resetting: return "resetting" case .unauthorized: return "unauthorized" case .unsupported: return "unsupported" default: return "unknown" } } @available(iOS 5.0, *) func centralManagerDidUpdateState(_ central: CBCentralManager) { if var data = self.data[.bluetooth] { data.remove(at: 0) data.insert(ItemInfo(name: "state", value: format(of: central.state)), at: 0) self.data[.bluetooth] = data } } private func getTimezone() -> [ItemInfo] { var result: [ItemInfo] = [] let zone = TimeZone.current result.append(ItemInfo(name: "identifier", value: zone.identifier)) if let abbr = zone.abbreviation() { result.append(ItemInfo(name: "abbreviation", value: abbr)) } result.append(ItemInfo(name: "secondsFromGMT", value: format(duration: TimeInterval(zone.secondsFromGMT())))) return result } private func getLanguage() -> [ItemInfo] { var result: [ItemInfo] = [] let current = Locale.current result.append(ItemInfo(name: "current", value: "\(current.identifier) | \(current.localizedString(forIdentifier: current.identifier)!)")) var index = 0 for id in Locale.preferredLanguages { index += 1 if let name = current.localizedString(forIdentifier: id) { result.append(ItemInfo(name: "prefer_lang_\(index)", value: "\(id) | \(name)")) } else { result.append(ItemInfo(name: "prefer_lang_\(index)", value: id)) } } return result } private func getNetwork() -> [ItemInfo] { var inames: [String] = [] var result: [ItemInfo] = [] if let interfaces = CNCopySupportedInterfaces() as? [CFString] { for iname in interfaces { inames.append(iname as String) let node = ItemInfo(id: result.count, name: "interface", value: iname as String) result.append(node) if let data = CNCopyCurrentNetworkInfo(iname) as? [String: Any] { for (name, value) in data { if name == "BSSID" || name == "SSID" { result.append(ItemInfo(name: name, value: "\(value)", parent: node.id)) } } } } } var ifaddr: UnsafeMutablePointer<ifaddrs>? if getifaddrs(&ifaddr) == 0 { var pointer = ifaddr while pointer != nil { let interface = pointer!.pointee let family = interface.ifa_addr.pointee.sa_family if family == UInt8(AF_INET) || family == UInt8(AF_INET6) { let name = String(cString: interface.ifa_name) var host = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &host, socklen_t(host.count), nil, socklen_t(0), NI_NUMERICHOST) let address = String(cString: host) result.append(ItemInfo(name: name, value: address)) } pointer = pointer?.pointee.ifa_next } } return result } private func getScreen() -> [ItemInfo] { var result: [ItemInfo] = [] let info = UIScreen.main result.append(ItemInfo(name: "width", value: "\(info.bounds.width)")) result.append(ItemInfo(name: "height", value: "\(info.bounds.height)")) result.append(ItemInfo(name: "nativeScale", value: "\(info.nativeScale)")) result.append(ItemInfo(name: "scale", value: "\(info.scale)")) result.append(ItemInfo(name: "brightness", value: String(format: "%.4f", info.brightness))) result.append(ItemInfo(name: "softwareDimming", value: "\(info.wantsSoftwareDimming)")) return result } private func getDevice() -> [ItemInfo] { var result: [ItemInfo] = [] let info = UIDevice.current result.append(ItemInfo(name: "name", value: info.name)) result.append(ItemInfo(name: "systemName", value: info.systemName)) result.append(ItemInfo(name: "systemVersion", value: info.systemVersion)) result.append(ItemInfo(name: "localizedModel", value: info.localizedModel)) var system: utsname = utsname() if uname(&system) == 0 { withUnsafePointer(to: &system.machine.0) { (pointer: UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "model", value: value)) } withUnsafePointer(to: &system.nodename.0) { (pointer: UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "nodename", value: value)) } withUnsafePointer(to: &system.release.0) { (pointer: UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "release", value: value)) } withUnsafePointer(to: &system.sysname.0) { (pointer: UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "sysname", value: value)) } withUnsafePointer(to: &system.version.0) { (pointer: UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "version", value: value)) } } result.append(ItemInfo(name: "idiom", value: format(of: info.userInterfaceIdiom))) if let uuid = info.identifierForVendor { result.append(ItemInfo(name: "IDFV", value: uuid.description)) } result.append(ItemInfo(name: "IDFA", value: ASIdentifierManager.shared().advertisingIdentifier.description)) info.isBatteryMonitoringEnabled = true result.append(ItemInfo(name: "batteryLevel", value: String(format: "%3.0f%%", info.batteryLevel * 100))) result.append(ItemInfo(name: "batterState", value: format(of: info.batteryState))) info.isProximityMonitoringEnabled = true result.append(ItemInfo(name: "proximityState", value: "\(info.proximityState)")) result.append(ItemInfo(name: "architecture", value: arch())) if let value: String = sysctl(TYPE_NAME: HW_MACHINE) { result.append(ItemInfo(name: "HW_MACHINE", value: value)) } if let value: String = sysctl(TYPE_NAME: HW_MODEL) { result.append(ItemInfo(name: "HW_MODEL", value: value)) } if let value: Int = sysctl(TYPE_NAME: HW_CPU_FREQ) { result.append(ItemInfo(name: "HW_CPU_FREQ", value: "\(value)")) } if let value: Int = sysctl(TYPE_NAME: HW_BUS_FREQ) { result.append(ItemInfo(name: "HW_BUS_FREQ", value: "\(value)")) } if let value: Int = sysctl(TYPE_NAME: HW_TB_FREQ) { result.append(ItemInfo(name: "HW_TB_FREQ", value: "\(value)")) } if let value: Int = sysctl(TYPE_NAME: HW_BYTEORDER) { result.append(ItemInfo(name: "HW_BYTEORDER", value: "\(value)")) } if let value: Int = sysctl(TYPE_NAME: HW_PHYSMEM) { result.append(ItemInfo(name: "HW_PHYSMEM", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_USERMEM) { result.append(ItemInfo(name: "HW_USERMEM", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_PAGESIZE) { result.append(ItemInfo(name: "HW_PAGESIZE", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_L1ICACHESIZE) { result.append(ItemInfo(name: "HW_L1ICACHESIZE", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_L1DCACHESIZE) { result.append(ItemInfo(name: "HW_L1DCACHESIZE", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_L2CACHESIZE) { result.append(ItemInfo(name: "HW_L2CACHESIZE", value: format(memory: UInt64(value)))) } if let value: Int = sysctl(TYPE_NAME: HW_L3CACHESIZE) { result.append(ItemInfo(name: "HW_L3CACHESIZE", value: format(memory: UInt64(value)))) } return result } private func sysctl(TYPE_NAME: Int32, CTL_TYPE: Int32 = CTL_HW) -> Int? { var value = 0 var size: size_t = MemoryLayout<Int>.size var data = [CTL_TYPE, TYPE_NAME] Darwin.sysctl(&data, 2, &value, &size, nil, 0) return value } private func sysctl(TYPE_NAME: Int32, CTL_TYPE: Int32 = CTL_HW) -> String? { var params = [CTL_TYPE, TYPE_NAME] var size: size_t = 0 Darwin.sysctl(&params, 2, nil, &size, nil, 0) if let pointer = malloc(size) { Darwin.sysctl(&params, 2, pointer, &size, nil, 0) return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl(name: String, hexMode: Bool = false) -> String? { var size: size_t = 0 sysctlbyname(name, nil, &size, nil, 0) if let pointer = malloc(size) { sysctlbyname(name, pointer, &size, nil, 0) if hexMode { let value = Data(bytes: pointer, count: size).map({String(format: "%02X", $0)}).joined() free(pointer) return "0x\(value)" } return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl<T>(name:String)->T? where T: SignedInteger { var value: T = 0 var size: size_t = MemoryLayout<T>.size sysctlbyname(name, &value, &size, nil, 0) return value } private func arch() -> String { var value = "unknown" if let type: cpu_type_t = sysctl(name: "hw.cputype") { if let subtype: cpu_subtype_t = sysctl(name: "hw.cpusubtype") { value = String(format: "unknown[0x%08x|0x%08x]", type, subtype) if type == CPU_TYPE_X86 { switch subtype { case CPU_SUBTYPE_X86_64_ALL:value = "X86_64_ALL" case CPU_SUBTYPE_X86_64_H:value = "X86_64_H" case CPU_SUBTYPE_X86_ARCH1:value = "X86_ARCH1" default:break } } else if type == CPU_TYPE_ARM { switch subtype { case CPU_SUBTYPE_ARM_V6:value = "ARM_V6" case CPU_SUBTYPE_ARM_V6M:value = "ARM_V6M" case CPU_SUBTYPE_ARM_V7:value = "ARM_V7" case CPU_SUBTYPE_ARM_V7F:value = "ARM_V7F" case CPU_SUBTYPE_ARM_V7K:value = "ARM_V7K" case CPU_SUBTYPE_ARM_V7M:value = "ARM_V7M" case CPU_SUBTYPE_ARM_V7S:value = "ARM_V7S" case CPU_SUBTYPE_ARM_V7EM:value = "ARM_V7EM" case CPU_SUBTYPE_ARM_V8:value = "ARM_V8" default:break } } else if type == (CPU_TYPE_ARM | CPU_ARCH_ABI64) { switch subtype { case CPU_SUBTYPE_ARM64_V8:value = "ARM64_V8" case CPU_SUBTYPE_ARM64_ALL:value = "ARM64_ALL" default:break } } } } return value } private func getProcess() -> [ItemInfo] { var result: [ItemInfo] = [] let info = ProcessInfo.processInfo result.append(ItemInfo(name: "name", value: info.processName)) result.append(ItemInfo(name: "guid", value: info.globallyUniqueString)) result.append(ItemInfo(name: "id", value: "\(info.processIdentifier)")) result.append(ItemInfo(name: "hostName", value: info.hostName)) result.append(ItemInfo(name: "osVersion", value: info.operatingSystemVersionString)) result.append(ItemInfo(name: "coreCount", value: "\(info.processorCount)")) result.append(ItemInfo(name: "activeCoreCount", value: "\(info.activeProcessorCount)")) result.append(ItemInfo(name: "physicalMemory", value: format(memory: info.physicalMemory))) result.append(ItemInfo(name: "systemUptime", value: format(duration: info.systemUptime))) result.append(ItemInfo(name: "thermalState", value: format(of: info.thermalState))) result.append(ItemInfo(name: "lowPowerMode", value: "\(info.isLowPowerModeEnabled)")) var usage = rusage() if getrusage(RUSAGE_SELF, &usage) == 0 { result.append(ItemInfo(name: "cpu_time_user", value: format(of: usage.ru_utime))) result.append(ItemInfo(name: "cpu_time_system", value: format(of: usage.ru_stime))) } return result } private func format(of type: timeval) -> String { return String(format: "%d.%06ds", type.tv_sec, type.tv_usec) } private func format(memory: UInt64) -> String { var components: [String] = [] var memory = Double(memory) while memory > 1024 { memory /= 1024 components.append("1024") } if memory - floor(memory) > 0 { components.insert(String(format: "%.3f", memory), at: 0) } else { components.insert(String(format: "%.0f", memory), at: 0) } return components.joined(separator: "x") } private func format(of type: UIDeviceBatteryState) -> String { switch type { case .charging: return "charging" case .full: return "full" case .unplugged: return "unplugged" case .unknown: return "unknown" } } private func format(of type: ProcessInfo.ThermalState) -> String { switch type { case .critical: return "critical" case .fair: return "fair" case .nominal: return "nominal" case .serious: return "serious" } } private func format(of type: UIUserInterfaceIdiom) -> String { switch type { case .carPlay: return "carPlay" case .pad: return "pad" case .phone: return "phone" case .tv: return "tv" case .unspecified: return "unspecified" } } private func format(duration: TimeInterval) -> String { var duration = duration let bases: [Double] = [60, 60, 24] var list: [Double] = [] for value in bases { list.insert(fmod(duration, value), at: 0) duration = floor(duration / value) } if duration > 0 { list.insert(duration, at: 0) return String(format: "%.0f %02.0f:%02.0f:%.3f", arguments: list) } else { return String(format: "%02.0f:%02.0f:%06.3f", arguments: list) } } private func getTelephony() -> [ItemInfo] { var result: [ItemInfo] = [] let info = CTTelephonyNetworkInfo() if let telephony = info.currentRadioAccessTechnology { switch telephony { case CTRadioAccessTechnologyLTE: result.append(ItemInfo(name: "radio", value: "LTE")) case CTRadioAccessTechnologyEdge: result.append(ItemInfo(name: "radio", value: "EDGE")) case CTRadioAccessTechnologyGPRS: result.append(ItemInfo(name: "radio", value: "GPRS")) case CTRadioAccessTechnologyHSDPA: result.append(ItemInfo(name: "radio", value: "HSDPA")) case CTRadioAccessTechnologyHSUPA: result.append(ItemInfo(name: "radio", value: "HSUPA")) case CTRadioAccessTechnologyWCDMA: result.append(ItemInfo(name: "radio", value: "WCDMA")) case CTRadioAccessTechnologyCDMA1x: result.append(ItemInfo(name: "radio", value: "CDMA_1x")) case CTRadioAccessTechnologyCDMAEVDORev0: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_0")) case CTRadioAccessTechnologyCDMAEVDORevA: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_A")) case CTRadioAccessTechnologyCDMAEVDORevB: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_B")) default: result.append(ItemInfo(name: "radio", value: telephony)) } } if let carrier = info.subscriberCellularProvider { if let name = carrier.carrierName { result.append(ItemInfo(name: "carrier", value: name)) } result.append(ItemInfo(name: "VOIP", value: "\(carrier.allowsVOIP)")) if let isoCode = carrier.isoCountryCode { result.append(ItemInfo(name: "isoCode", value: isoCode)) } if let mobileCode = carrier.mobileCountryCode { result.append(ItemInfo(name: "mobileCode", value: mobileCode)) } if let networkCode = carrier.mobileNetworkCode { result.append(ItemInfo(name: "networkCode", value: networkCode)) } } return result } }
swift-master/Hardware/HardwareTests/HardwareTests.swift
// // HardwareTests.swift // HardwareTests // // Created by larryhou on 10/7/2017. // import XCTest @testable import Hardware class HardwareTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
swift-master/Hardware/HardwareUITests/HardwareUITests.swift
// // HardwareUITests.swift // HardwareUITests // // Created by larryhou on 10/7/2017. // import XCTest class HardwareUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
swift-master/JSONUsage/JSONUsage/ViewController.swift
// // ViewController.swift // JSONUsage // // Created by larryhou on 4/11/15. // import UIKit import Foundation class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() guard let url = Bundle.main.url(forResource: "0700", withExtension: "json"), let data = try? Data(contentsOf: url) else { print("JSON file not found") return } do { let jsonData = try JSONDecoder().decode(JSONData.self, from: data) print(jsonData) } catch { print(error.localizedDescription) } } } struct JSONData: Codable { struct Data: Codable { struct Indicators: Codable { struct Quote: Codable { let close: [Double?] let high: [Double?] let low: [Double?] let open: [Double?] let volume: [Double?] } let quote: [Quote] } struct Meta: Codable { struct TradingPeriod: Codable { let end: Int let gmtoffset: Int let start: Int let timezone: String } struct CurrentTradingPeriod: Codable { let post: TradingPeriod let pre: TradingPeriod let regular: TradingPeriod } let currency: String let currentTradingPeriod: CurrentTradingPeriod let dataGranularity: String let exchangeName: String let gmtoffset: Int let instrumentType: String let previousClose: Double let scale: Int let symbol: String let timezone: String let tradingPeriods: [[TradingPeriod]] } let indicators: Indicators let meta: Meta let timestamp: [Int] } let data: Data let debug: String let isLegacy: Bool let isValidRange: Bool }
swift-master/JSONUsage/JSONUsage/AppDelegate.swift
// // AppDelegate.swift // JSONUsage // // Created by larryhou on 4/11/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/JSONUsage/JSONUsageTests/JSONUsageTests.swift
// // JSONUsageTests.swift // JSONUsageTests // // Created by larryhou on 4/11/15. // import UIKit import XCTest class JSONUsageTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/Teslameter/Teslameter/ViewController.swift
// // ViewController.swift // Teslameter // // Created by larryhou on 9/18/14. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet var magnitude: UILabel! @IBOutlet var graph: TeslaGraphView! @IBOutlet var teslaX: UILabel! @IBOutlet var teslaY: UILabel! @IBOutlet var teslaZ: UILabel! private var attrX: [NSObject: AnyObject]! private var attrY: [NSObject: AnyObject]! private var attrZ: [NSObject: AnyObject]! private var positiveAttr: [NSObject: AnyObject]! private var nagitiveAttr: [NSObject: AnyObject]! private var locationManager: CLLocationManager! private var timestamp: NSDate! override func viewDidLoad() { super.viewDidLoad() attrX = [NSForegroundColorAttributeName: UIColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 1.0)] attrY = [NSForegroundColorAttributeName: UIColor.greenColor()] attrZ = [NSForegroundColorAttributeName: UIColor.blueColor()] positiveAttr = [NSForegroundColorAttributeName: UIColor.blackColor()] nagitiveAttr = [NSForegroundColorAttributeName: UIColor.redColor()] locationManager = CLLocationManager() locationManager.requestWhenInUseAuthorization() locationManager.headingFilter = kCLHeadingFilterNone locationManager.delegate = self locationManager.startUpdatingHeading() } private func setAttributedText(#label:UILabel, title: String, style: [NSObject: AnyObject], value: Double) { var text = NSMutableAttributedString(string: title, attributes: style) var attr = value > 0 ? positiveAttr : nagitiveAttr text.appendAttributedString(NSAttributedString(string: String(format: "%.1f", fabs(value)), attributes: attr)) label.attributedText = text } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: 罗盘定位 func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) { var mag = sqrt(newHeading.x * newHeading.x + newHeading.y * newHeading.y * newHeading.z * newHeading.z) magnitude.text = String(format: "%.1f", mag) graph.insertHeadingTesla(x: newHeading.x, y: newHeading.y, z: newHeading.z) setAttributedText(label: teslaX, title: "Xμ: ", style: attrX, value: newHeading.x) setAttributedText(label: teslaY, title: "Yμ: ", style: attrY, value: newHeading.y) setAttributedText(label: teslaZ, title: "Zμ: ", style: attrZ, value: newHeading.z) if timestamp == nil || newHeading.timestamp.timeIntervalSinceDate(timestamp) > 1 { timestamp = newHeading.timestamp //println(timestamp) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) } }
swift-master/Teslameter/Teslameter/AppDelegate.swift
// // AppDelegate.swift // Teslameter // // Created by larryhou on 9/18/14. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/Teslameter/Teslameter/TeslaGraphView.swift
// // TeslaGraphView.swift // Teslameter // // Created by larryhou on 9/18/14. // import Foundation import UIKit import CoreLocation class TeslaGraphView: UIView { enum TeslaAxis: Int { case X case Y case Z } private let GRAPH_DENSITY = 100 private let TICK_NUM = 4 private var buffer: [[CLHeadingComponentValue]] = [] private var index: Int = 0 func insertHeadingTesla(#x:CLHeadingComponentValue, y: CLHeadingComponentValue, z: CLHeadingComponentValue) { if buffer.count < GRAPH_DENSITY { buffer.append([0.0, 0.0, 0.0]) } buffer[index][TeslaAxis.X.rawValue] = x buffer[index][TeslaAxis.Y.rawValue] = y buffer[index][TeslaAxis.Z.rawValue] = z index = (index + 1) % GRAPH_DENSITY setNeedsDisplay() } private func drawGraph(#bounds:CGRect, inContext context: CGContextRef) { CGContextSaveGState(context) CGContextBeginPath(context) let delta = bounds.height / CGFloat( 2 * TICK_NUM) for i in 1..<(2 * TICK_NUM) { CGContextMoveToPoint(context, 0.0, delta * CGFloat(i)) CGContextAddLineToPoint(context, bounds.width, delta * CGFloat(i)) } CGContextSetLineWidth(context, 0.5) CGContextSetGrayStrokeColor(context, 0.75, 1.0) CGContextStrokePath(context) CGContextBeginPath(context) CGContextMoveToPoint(context, 0, bounds.height / 2) CGContextAddLineToPoint(context, bounds.width, bounds.height / 2) CGContextSetLineWidth(context, 0.5) CGContextSetGrayStrokeColor(context, 0.0, 1.0) CGContextStrokePath(context) CGContextRestoreGState(context) } private func drawTeslaBuffer(#axis:Int, fromIndex index: Int, inContext context: CGContextRef) { CGContextSaveGState(context) CGContextBeginPath(context) for i in 0..<buffer.count { var iter = (index + i) % buffer.count var comp: CGFloat = CGFloat(buffer[iter][axis] / 128 * 8) if comp > 0 { comp = bounds.height / 2 - fmin(comp, CGFloat(TICK_NUM)) * bounds.height / 2 / CGFloat(TICK_NUM) } else { comp = bounds.height / 2 + fmin(fabs(comp), CGFloat(TICK_NUM)) * bounds.height / 2 / CGFloat(TICK_NUM) } if i == 0 { CGContextMoveToPoint(context, 0, comp) } else { CGContextAddLineToPoint(context, CGFloat(i) * bounds.width / CGFloat(GRAPH_DENSITY), comp) } } CGContextSetLineWidth(context, 2.0) CGContextSetLineJoin(context, kCGLineJoinRound) switch TeslaAxis(rawValue: axis)! { case .X:CGContextSetRGBStrokeColor(context, 1.0, 0.0, 1.0, 1.0) case .Y:CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0) case .Z:CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0) } CGContextStrokePath(context) CGContextRestoreGState(context) } override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext() var bounds = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) drawGraph(bounds: bounds, inContext: context) CGContextSetAllowsAntialiasing(context, false) for axis in 0..<3 { drawTeslaBuffer(axis: axis, fromIndex: index, inContext: context) } CGContextSetAllowsAntialiasing(context, true) } }
swift-master/Teslameter/TeslameterTests/TeslameterTests.swift
// // TeslameterTests.swift // TeslameterTests // // Created by larryhou on 9/18/14. // import UIKit import XCTest class TeslameterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/UIWebView/UIWebView/ViewController.swift
// // ViewController.swift // UIWebView // // Created by larryhou on 3/27/15. // import UIKit class ViewController: UIViewController { @IBOutlet weak var web: UIWebView! override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("html", ofType: "data") if path == nil { println("path not exist") } else { let data = NSData(contentsOfFile: path!) web.loadData(data!, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/UIWebView/UIWebView/AppDelegate.swift
// // AppDelegate.swift // UIWebView // // Created by larryhou on 3/27/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/UIWebView/UIWebViewTests/UIWebViewTests.swift
// // UIWebViewTests.swift // UIWebViewTests // // Created by larryhou on 3/27/15. // import UIKit import XCTest class UIWebViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/yahooQuote/yahooQuote/main.swift
// // main.swift // yahooQuote // // Created by larryhou on 4/16/15. // import Foundation var verbose = false var eventTimeFormatter = NSDateFormatter() eventTimeFormatter.dateFormat = "yyyy-MM-dd" enum CooprActionType: String { case SPLIT = "SPLIT" case DIVIDEND = "DIVIDEND" } struct CoorpAction: Printable { let date: NSDate let type: CooprActionType var value: Double var description: String { let vstr = String(format: "%.6f", value) return "\(eventTimeFormatter.stringFromDate(date))|\(vstr)|\(type.rawValue)" } } func getQuoteRequest(ticket: String) -> NSURLRequest { var formatter = NSDateFormatter() formatter.dateFormat = "MM-dd-yyyy" var date = formatter.stringFromDate(NSDate()).componentsSeparatedByString("-") let url = "http://real-chart.finance.yahoo.com/table.csv?s=\(ticket)&d=\(date[0])&e=\(date[1])&f=\(date[2])&g=d&ignore=.csv" return NSURLRequest(URL: NSURL(string: url)!) } func getCoorpActionRequest(ticket: String) -> NSURLRequest { var formatter = NSDateFormatter() formatter.dateFormat = "MM-dd-yyyy" var date = formatter.stringFromDate(NSDate()).componentsSeparatedByString("-") let url = "http://ichart.finance.yahoo.com/x?s=\(ticket)&d=\(date[0])&e=\(date[1])&f=\(date[2])&g=v" return NSURLRequest(URL: NSURL(string: url)!) } var splits, dividends: [CoorpAction]! func fetchCooprActions(request: NSURLRequest) { if verbose { println(request.URL!) } var coorpActions: [CoorpAction]! var formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMdd" var response: NSURLResponse?, error: NSError? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) if error == nil && (response as! NSHTTPURLResponse).statusCode == 200 { coorpActions = [] let list = (NSString(data: data!, encoding: NSUTF8StringEncoding) as! String).componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) for i in 1..<list.count { let line = list[i].stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.ForcedOrderingSearch, range: nil) let cols = line.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ", ")) if cols.count < 3 { continue } let type = CooprActionType(rawValue: cols[0]) let date = formatter.dateFromString(cols[1]) let value: Double let digits = cols[2].componentsSeparatedByString(":").map({NSString(string: $0).doubleValue}) if type == CooprActionType.SPLIT { value = digits[0] / digits[1] } else { value = digits[0] } if type != nil && date != nil { coorpActions.append(CoorpAction(date: date!, type: type!, value: value)) } } if coorpActions.count == 0 { coorpActions = nil } } else { coorpActions = nil if verbose { println(response == nil ? error! : response!) } } if coorpActions != nil { coorpActions.sort({$0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970}) var values: [Double] = [] for i in 0..<coorpActions.count { if coorpActions[i].type == CooprActionType.SPLIT { splits = splits ?? [] splits.append(coorpActions[i]) values.append(coorpActions[i].value) } else if coorpActions[i].type == CooprActionType.DIVIDEND { dividends = dividends ?? [] dividends.append(coorpActions[i]) } } if verbose { println(dividends) println(splits) } if splits != nil { for i in 0..<splits.count { var multiple = values[i] for j in (i + 1)..<splits.count { multiple *= values[j] } splits[i].value = multiple } } } else { dividends = nil splits = nil } } func createActionMap(list: [CoorpAction]?, #formatter:NSDateFormatter) -> [String: CoorpAction] { var map: [String: CoorpAction] = [:] if list == nil { return map } for i in 0..<list!.count { let key = formatter.stringFromDate(list![i].date) map[key] = list![i] } return map } func formatQuote(text: String) -> String { let value = NSString(string: text).doubleValue return String(format: "%6.2f", value) } func parseQuote(data: [String]) { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" var dmap = createActionMap(dividends, formatter: formatter) var splitAction: CoorpAction! println("date,open,high,low,close,volume,split,dividend,adjclose") for i in 0..<data.count { let cols = data[i].componentsSeparatedByString(",") if cols.count < 7 { continue } let date = formatter.dateFromString(cols[0])! let open = formatQuote(cols[1]) let high = formatQuote(cols[2]) let low = formatQuote(cols[3]) let close = formatQuote(cols[4]) let volume = NSString(string: cols[5]).doubleValue let adjclose = formatQuote(cols[6]) var msg = "\(cols[0]),\(open),\(high),\(low),\(close)," + String(format: "%10.0f", volume) if splits != nil && splits.count > 0 { while splits.count > 0 { if (splitAction == nil || date.timeIntervalSinceDate(splitAction.date) >= 0) && date.timeIntervalSinceDate(splits[0].date) < 0 { splitAction = splits.first! } else { break } splits.removeAtIndex(0) } } else { if splitAction != nil && date.timeIntervalSinceDate(splitAction.date) >= 0 { splitAction = nil } } msg += "," + String(format: "%.6f", splitAction != nil ? splitAction.value : 1.0) var dividend = 0.0, key = cols[0] if dmap[key] != nil { dividend = dmap[key]!.value } msg += "," + String(format: "%.6f", dividend) msg += ",\(adjclose)" println(msg) } } func fetchQuote(request: NSURLRequest) { if verbose { println(request.URL!) } var response: NSURLResponse?, error: NSError? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) if error == nil && (response as! NSHTTPURLResponse).statusCode == 200 { let text = NSString(data: data!, encoding: NSUTF8StringEncoding)! var list = text.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as! [String] list.removeAtIndex(0) parseQuote(list.reverse()) } else { if verbose { println(response == nil ? error! : response!) } } } func judge(@autoclosure condition:() -> Bool, message: String) { if !condition() { println("ERR: " + message) exit(1) } } if Process.arguments.filter({$0 == "-h"}).count == 0 { let count = Process.arguments.filter({$0 == "-t"}).count judge(count >= 1, "[-t STOCK_TICKET] MUST be provided") judge(count == 1, "[-t STOCK_TICKET] has been set \(count) times") judge(Process.argc >= 3, "Unenough Parameters") } var ticket: String = "0700" var skip: Bool = false for i in 1..<Int(Process.argc) { let option = Process.arguments[i] if skip { skip = false continue } switch option { case "-t": judge(Process.arguments.count > i + 1, "-t lack of parameter") ticket = Process.arguments[i + 1] skip = true break case "-v": verbose = true break case "-h": let msg = Process.arguments[0] + " -t STOCK_TICKET" println(msg) exit(0) break default: println("Unsupported arguments: " + Process.arguments[i]) exit(2) } } fetchCooprActions(getCoorpActionRequest(ticket)) fetchQuote(getQuoteRequest(ticket))
swift-master/fetchQuote/fetchQuote/main.swift
// // main.swift // fetchQuote // // Created by larryhou on 4/11/15. // import Foundation var ticket: String = "0700.HK" var zone: String = "+0800" var related: NSDate? var verbose = false var automated = false var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd Z" var timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "YYYY-MM-dd,HH:mm:ss Z" func judge(@autoclosure condition:() -> Bool, message: String) { if !condition() { println("ERR: " + message) exit(1) } } if Process.arguments.filter({$0 == "-h"}).count == 0 { let count = Process.arguments.filter({$0 == "-t"}).count judge(count >= 1, "[-t STOCK_TICKET] MUST be provided") judge(count == 1, "[-t STOCK_TICKET] has been set \(count) times") judge(Process.argc >= 3, "Unenough Parameters") } var skip: Bool = false for i in 1..<Int(Process.argc) { let option = Process.arguments[i] if skip { skip = false continue } switch option { case "-t": judge(Process.arguments.count > i + 1, "-t lack of parameter") ticket = Process.arguments[i + 1] skip = true break case "-d": judge(Process.arguments.count > i + 1, "-d lack of parameter") related = dateFormatter.dateFromString(Process.arguments[i + 1] + " \(zone)") judge(related != nil, "Unsupported date format:\(Process.arguments[i + 1]), e.g.2015-04-09") skip = true break case "-z": judge(Process.arguments.count > i + 1, "-z lack of parameter") zone = Process.arguments[i + 1] let regex = NSPredicate(format: "SELF MATCHES %@", "[+-]\\d{4}") judge(regex.evaluateWithObject(zone), "Unsupported time zone format:\(zone), e.g. +0800") skip = true break case "-v": verbose = true break case "-a": automated = true break case "-h": let msg = Process.arguments[0] + " -t STOCK_TICKET [-z TIME_ZONE] [-d DATE]" println(msg) exit(0) break default: println("Unsupported arguments: " + Process.arguments[i]) exit(2) } } func getQuotesURL(var date: NSDate?) -> NSURL { if date == nil { date = NSDate() } let text = dateFormatter.stringFromDate(date!).componentsSeparatedByString(" ").first! date = timeFormatter.dateFromString("\(text),06:00:00 \(zone)") let refer = timeFormatter.dateFromString("\(text),20:00:00 \(zone)")! let s = UInt(date!.timeIntervalSince1970) let e = UInt(refer.timeIntervalSince1970) let url = "http://finance.yahoo.com/_td_charts_api/resource/charts;comparisonTickers=;events=div%7Csplit%7Cearn;gmtz=8;indicators=quote;period1=\(s);period2=\(e);queryString=%7B%22s%22%3A%22\(ticket)%2BInteractive%22%7D;range=1d;rangeSelected=undefined;ticker=\(ticket);useMock=false?crumb=a6xbm2fVIlt" return NSURL(string: url)! } class QuoteSpliter: Printable { let date: NSDate let ratios: [Int] init(date: NSDate, ratios: [Int]) { self.date = date self.ratios = ratios } var description: String { return dateFormatter.stringFromDate(date) + ", " + "/".join(ratios.map({"\($0)"})) } } func formatQuote(value: AnyObject, format: String = "%6.2f") -> String { return String(format: format, value as! Double) } func fetchQuoteOn(date: NSDate?) { let url = getQuotesURL(date) if verbose { println(url) } var response: NSURLResponse? var error: NSError? var spliters: [QuoteSpliter] = [] let data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: url), returningResponse: &response, error: &error) if data != nil { error = nil var result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) if error == nil { let json = result as! NSDictionary let map = json.valueForKeyPath("data.events.splits") as? [String: [String: AnyObject]] if map != nil { for (key, item) in map! { let time = NSString(string: key).integerValue let date = NSDate(timeIntervalSince1970: NSTimeInterval(time)) let ratios = (item["splitRatio"] as! String).componentsSeparatedByString("/").map({$0.toInt()!}) spliters.append(QuoteSpliter(date: date, ratios: ratios)) } } let quotes = (json.valueForKeyPath("data.indicators.quote") as! [[String: [AnyObject]]]).first! let stamps = json.valueForKeyPath("data.timestamp") as! [UInt] let OPEN = "open", HIGH = "high", LOW = "low", CLOSE = "close" let VOLUME = "volume" var list: [String] = [] for i in 0..<stamps.count { var item: [String] = [] var date = NSDate(timeIntervalSince1970: NSTimeInterval(stamps[i])) if quotes[OPEN]![i] is NSNull { continue } item.append(timeFormatter.stringFromDate(date).componentsSeparatedByString(" ").first!) item.append(formatQuote(quotes[OPEN]![i])) item.append(formatQuote(quotes[HIGH]![i])) item.append(formatQuote(quotes[LOW ]![i])) item.append(formatQuote(quotes[CLOSE]![i])) item.append("\(quotes[VOLUME]![i])") list.append(",".join(item)) } if spliters.count > 0 { println(spliters) } println("\n".join(list)) } else { if verbose { println(NSString(data: data!, encoding: NSUTF8StringEncoding)!) } } } else { if verbose { if response != nil { println(response!) } println(error!) } exit(202) } } if !automated { fetchQuoteOn(related) } else { let DAY: NSTimeInterval = 24 * 3600 related = NSDate(timeIntervalSince1970: NSDate().timeIntervalSince1970 + DAY) for i in 0...50 { fetchQuoteOn(NSDate(timeIntervalSince1970: related!.timeIntervalSince1970 - NSTimeInterval(i) * DAY)) } }
swift-master/MapAnnotation/MapAnnotationTests/MapAnnotationTests.swift
// // MapAnnotationTests.swift // MapAnnotationTests // // Created by larryhou on 4/4/15. // import UIKit import XCTest class MapAnnotationTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
swift-master/MapAnnotation/MapAnnotation/ViewController.swift
// // ViewController.swift // MapAnnotation // // Created by larryhou on 4/4/15. // import UIKit import MapKit class MapPinAnnotation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate self.title = NSString(format: "%.4f°/%.4f°", coordinate.latitude, coordinate.latitude) } } class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! private var _locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() _locationManager = CLLocationManager() _locationManager.requestAlwaysAuthorization() map.showsUserLocation = true } func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) { let location = map.userLocation.location map.setRegion(MKCoordinateRegionMakeWithDistance(location.coordinate, 200, 200), animated: true) map.showsUserLocation = false map.addAnnotation(MapPinAnnotation(coordinate: location.coordinate)) } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation.isKindOfClass(MapPinAnnotation) { let REUSE_IDENTIFIER = "MapPinAnnotation" var anView = map.dequeueReusableAnnotationViewWithIdentifier(REUSE_IDENTIFIER) as? MKPinAnnotationView if anView == nil { anView = MKPinAnnotationView(annotation: nil, reuseIdentifier: REUSE_IDENTIFIER) anView!.canShowCallout = true anView!.animatesDrop = true } anView!.annotation = annotation return anView } return nil } func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) { let anView = views.first as MKPinAnnotationView map.selectAnnotation(anView.annotation, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
swift-master/MapAnnotation/MapAnnotation/AppDelegate.swift
// // AppDelegate.swift // MapAnnotation // // Created by larryhou on 4/4/15. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // 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, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
swift-master/VideoDecode/VideoDecode/ViewController.swift
// // ViewController.swift // MovieEditor // // Created by larryhou on 03/01/2018. // import UIKit import AVFoundation import ReplayKit import ScreenRecording extension AVAssetReaderStatus { var description: String { switch self { case .cancelled: return "cancelled" case .completed: return "completed" case .reading: return "reading" case .unknown: return "unknown" case .failed: return "failed" } } } extension CMTime { var realtime: Double {return Double(value) / Double(timescale) } } class ViewController: UIViewController { var background = DispatchQueue(label: "track_read_queue") @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var loopIndicator: UILabel! @IBOutlet weak var timeIndicator: UILabel! var trackOutput: AVAssetReaderTrackOutput! var reader: AVAssetReader! var exporter: AVAssetExportSession! var outputURL: URL! var formatter: DateFormatter! var playCount = 0 override func viewDidLoad() { super.viewDidLoad() progressView.isHidden = true formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Do any additional setup after loading the view, typically from a nib. guard let bundle = Bundle.main.path(forResource: "movie", ofType: "bundle") else {return} let location = URL(fileURLWithPath: "\(bundle)/funny.mp4") let layer = AVPlayerLayer(player: AVPlayer(url: location)) layer.videoGravity = .resizeAspectFill layer.frame = view.frame view.layer.insertSublayer(layer, at: 0) layer.player?.play() loopIndicator.text = String(format: "#%02d", playCount) layer.player?.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 30), queue: .main, using: { (position) in if let duration = layer.player?.currentItem?.duration { if position == duration { self.playCount += 1 layer.player?.seek(to: kCMTimeZero) layer.player?.play() self.loopIndicator.text = String(format: "#%02d", self.playCount) } } self.timeIndicator.text = self.formatter.string(from: Date()) }) let tap = UITapGestureRecognizer(target: self, action: #selector(stop(_:))) tap.numberOfTapsRequired = 2 view.addGestureRecognizer(tap) } @IBAction func record(_ sender: UIButton) { recordButton.isHidden = true ScreenRecorder.shared.startRecording() } @IBAction func stop(_ sender: UITapGestureRecognizer) { guard sender.state == .recognized else { return } progressView.isHidden = false ScreenRecorder.shared.progressObserver = progressUpdate(_:) ScreenRecorder.shared.stopRecording(clipContext: "0-5;10-15") { (_, status) in print(status) self.recordButton.isHidden = false self.progressView.isHidden = true } } func progressUpdate(_ value: Float) { progressView.progress = value } override var prefersStatusBarHidden: Bool {return true} override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
swift-master/VideoDecode/VideoDecode/AppDelegate.swift
// // AppDelegate.swift // VideoDecode // // Created by larryhou on 08/01/2018. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // 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, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // 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 applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "VideoDecode") container.loadPersistentStores(completionHandler: { (_, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
swift-master/VideoDecode/VideoDecodeUITests/VideoDecodeUITests.swift
// // VideoDecodeUITests.swift // VideoDecodeUITests // // Created by larryhou on 08/01/2018. // import XCTest class VideoDecodeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
swift-master/VideoDecode/ScreenRecordingTests/ScreenRecordingTests.swift
// // ScreenRecordingTests.swift // ScreenRecordingTests // // Created by larryhou on 14/01/2018. // import XCTest @testable import ScreenRecording class ScreenRecordingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
swift-master/VideoDecode/VideoDecodeTests/VideoDecodeTests.swift
// // VideoDecodeTests.swift // VideoDecodeTests // // Created by larryhou on 08/01/2018. // import XCTest @testable import VideoDecode class VideoDecodeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
swift-master/VideoDecode/ScreenRecording/MovieEditor.swift
// // MovieEditor.swift // VideoDecode // // Created by larryhou on 09/01/2018. // import Foundation import AVFoundation import GameplayKit extension AVAssetExportSessionStatus: CustomStringConvertible { public var description: String { switch self { case .cancelled:return "cancelled" case .exporting:return "exporting" case .completed:return "completed" case .waiting:return "waiting" case .unknown:return "unknown" case .failed:return "failed" } } } private enum VideoTransitionDirection { case right, left, top, bottom } @objc public enum VideoTransition: Int { case dissolve, pushRight, pushLeft, pushTop, pushBottom, eraseRight, eraseLeft, eraseTop, eraseBottom, random } public class MovieEditor: NSObject { private(set) var asset: AVAsset! private(set) var insertClips: [CMTimeRange]! private var assetComposition: AVMutableComposition! private var transitionClips: [CMTimeRange]! private var passClips: [CMTimeRange]! var videoTransition: VideoTransition var transitionDuration: TimeInterval @objc public init(transition: VideoTransition = .dissolve, transitionDuration duration: TimeInterval = 1.0) { self.videoTransition = transition self.transitionDuration = duration } @objc public func cut(asset: AVAsset, with clips: [CMTimeRange], transition: VideoTransition = .dissolve) -> AVAssetExportSession? { guard asset.isReadable else { return nil } let insertClips: [CMTimeRange] = clips.filter({ !$0.duration.seconds.isNaN }) guard insertClips.count > 0 else { return nil } self.videoTransition = transition self.asset = asset self.insertClips = insertClips self.assetComposition = AVMutableComposition() let exporter = AVAssetExportSession(asset: assetComposition, presetName: AVAssetExportPreset1280x720) if let (videoComposition, mix) = composeMovieTracks() { exporter?.videoComposition = videoComposition exporter?.audioMix = mix } exporter?.outputFileType = AVFileType.mp4 return exporter } private func composeMovieTracks() -> (AVMutableVideoComposition, AVMutableAudioMix)? { let videoTracks = [ assetComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)!, assetComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)!] let audioTracks = [ assetComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)!, assetComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)!] self.transitionClips = [] self.passClips = [] let assetVideoTracks = asset.tracks(withMediaType: .video) let assetAudioTracks = asset.tracks(withMediaType: .audio) let extraTracks: [AVMutableCompositionTrack]? if assetAudioTracks.count > 1 { extraTracks = [ assetComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)!, assetComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)!] } else { extraTracks = nil } var anchor = kCMTimeZero let overlap = CMTime(seconds: transitionDuration, preferredTimescale: 600) for i in 0..<insertClips.count { let index = i % 2 let range = insertClips[i] try? videoTracks[index].insertTimeRange(range, of: assetVideoTracks[0], at: anchor) try? audioTracks[index].insertTimeRange(range, of: assetAudioTracks[0], at: anchor) try? extraTracks?[index].insertTimeRange(range, of: assetAudioTracks[1], at: anchor) var passClip = CMTimeRange(start: anchor, duration: range.duration) if i > 0 { passClip.start = passClip.start + overlap passClip.duration = passClip.duration - overlap } if i + 1 < insertClips.count { passClip.duration = passClip.duration - overlap } passClips.append(passClip) anchor = anchor + range.duration - overlap if i + 1 < insertClips.count { transitionClips.append(CMTimeRange(start: anchor, duration: overlap)) } } var mixParameters: [AVMutableAudioMixInputParameters] = [] var videoInstuctions: [AVMutableVideoCompositionInstruction] = [] for i in 0..<passClips.count { let index = i % 2 let instruction = AVMutableVideoCompositionInstruction() let layer = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTracks[index]) instruction.layerInstructions = [layer] instruction.timeRange = passClips[i] videoInstuctions.append(instruction) if i < transitionClips.count { let range = transitionClips[i] let instruction = AVMutableVideoCompositionInstruction() instruction.layerInstructions = getTransitionInstuctions(srcTrack: videoTracks[index], dstTrack: videoTracks[1-index], range: range, transition: videoTransition) instruction.timeRange = range videoInstuctions.append(instruction) mixParameters.append(contentsOf: getMixParameters(srcTrack: audioTracks[index], dstTrack: audioTracks[1-index], range: transitionClips[i])) if let extraTracks = extraTracks { mixParameters.append(contentsOf: getMixParameters(srcTrack: extraTracks[index], dstTrack: extraTracks[1-index], range: transitionClips[i])) } } } let videoComposition = AVMutableVideoComposition() videoComposition.renderSize = assetVideoTracks[0].naturalSize videoComposition.frameDuration = CMTime(value: 1, timescale: 30) videoComposition.instructions = videoInstuctions let mix = AVMutableAudioMix() mix.inputParameters = mixParameters return (videoComposition, mix) } private func getMixParameters(srcTrack: AVMutableCompositionTrack, dstTrack: AVMutableCompositionTrack, range: CMTimeRange) -> [AVMutableAudioMixInputParameters] { var result: [AVMutableAudioMixInputParameters] = [] var parameter = AVMutableAudioMixInputParameters(track: srcTrack) parameter.setVolumeRamp(fromStartVolume: 1.0, toEndVolume: 0.0, timeRange: range) parameter.setVolume(1.0, at: range.end) result.append(parameter) parameter = AVMutableAudioMixInputParameters(track: dstTrack) parameter.setVolumeRamp(fromStartVolume: 0.0, toEndVolume: 1.0, timeRange: range) result.append(parameter) return result } private func getTransitionInstuctions(srcTrack: AVMutableCompositionTrack, dstTrack: AVMutableCompositionTrack, range: CMTimeRange, transition: VideoTransition) -> [AVMutableVideoCompositionLayerInstruction] { switch transition { case .dissolve: return dissolve(srcTrack: srcTrack, dstTrack: dstTrack, range: range) case .pushRight: return push(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .right) case .pushLeft: return push(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .left) case .pushTop: return push(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .top) case .pushBottom: return push(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .bottom) case .eraseRight: return erase(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .right) case .eraseLeft: return erase(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .left) case .eraseTop: return erase(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .top) case .eraseBottom: return erase(srcTrack: srcTrack, dstTrack: dstTrack, range: range, direction: .bottom) case .random: let transitions: [VideoTransition] = [.dissolve, .pushTop, .pushBottom, .pushLeft, .pushRight, .eraseTop, .eraseBottom, .eraseRight, .eraseLeft] let index = Int(GKRandomSource.sharedRandom().nextUniform() * Float(transitions.count)) return getTransitionInstuctions(srcTrack: srcTrack, dstTrack: dstTrack, range: range, transition: transitions[index]) } } private func dissolve(srcTrack: AVMutableCompositionTrack, dstTrack: AVMutableCompositionTrack, range: CMTimeRange) -> [AVMutableVideoCompositionLayerInstruction] { let src = AVMutableVideoCompositionLayerInstruction(assetTrack: srcTrack) src.setOpacityRamp(fromStartOpacity: 1.0, toEndOpacity: 0.0, timeRange: range) let dst = AVMutableVideoCompositionLayerInstruction(assetTrack: dstTrack) dst.setOpacityRamp(fromStartOpacity: 0.0, toEndOpacity: 1.0, timeRange: range) return [src, dst] } // MARK: push transition effect private func push(srcTrack: AVMutableCompositionTrack, dstTrack: AVMutableCompositionTrack, range: CMTimeRange, direction: VideoTransitionDirection) -> [AVMutableVideoCompositionLayerInstruction] { let size = srcTrack.naturalSize let center = CGAffineTransform.identity let left = center.translatedBy(x: -size.width, y: 0) let right = center.translatedBy(x: size.width, y: 0) let top = center.translatedBy(x: 0, y: -size.height) let bottom = center.translatedBy(x: 0, y: size.height) let src = AVMutableVideoCompositionLayerInstruction(assetTrack: srcTrack) let dst = AVMutableVideoCompositionLayerInstruction(assetTrack: dstTrack) switch direction { case .left: src.setTransformRamp(fromStart: center, toEnd: left, timeRange: range) dst.setTransformRamp(fromStart: right, toEnd: center, timeRange: range) case .right: src.setTransformRamp(fromStart: center, toEnd: right, timeRange: range) dst.setTransformRamp(fromStart: left, toEnd: center, timeRange: range) case .top: src.setTransformRamp(fromStart: center, toEnd: top, timeRange: range) dst.setTransformRamp(fromStart: bottom, toEnd: center, timeRange: range) case .bottom: src.setTransformRamp(fromStart: center, toEnd: bottom, timeRange: range) dst.setTransformRamp(fromStart: top, toEnd: center, timeRange: range) } return [src, dst] } // MARK: erase transition effect private func erase(srcTrack: AVMutableCompositionTrack, dstTrack: AVMutableCompositionTrack, range: CMTimeRange, direction: VideoTransitionDirection) -> [AVMutableVideoCompositionLayerInstruction] { let size = srcTrack.naturalSize let full = CGRect(origin: CGPoint.zero, size: size) let left = CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: size.height)) let right = left.offsetBy(dx: size.width, dy: 0) let top = CGRect(origin: CGPoint.zero, size: CGSize(width: size.width, height: 0)) let bottom = top.offsetBy(dx: 0, dy: size.height) let src = AVMutableVideoCompositionLayerInstruction(assetTrack: srcTrack) let dst = AVMutableVideoCompositionLayerInstruction(assetTrack: dstTrack) switch direction { case .left: src.setCropRectangleRamp(fromStartCropRectangle: full, toEndCropRectangle: left, timeRange: range) dst.setCropRectangleRamp(fromStartCropRectangle: right, toEndCropRectangle: full, timeRange: range) case .right: src.setCropRectangleRamp(fromStartCropRectangle: full, toEndCropRectangle: right, timeRange: range) dst.setCropRectangleRamp(fromStartCropRectangle: left, toEndCropRectangle: full, timeRange: range) case .top: src.setCropRectangleRamp(fromStartCropRectangle: full, toEndCropRectangle: top, timeRange: range) dst.setCropRectangleRamp(fromStartCropRectangle: bottom, toEndCropRectangle: full, timeRange: range) case .bottom: src.setCropRectangleRamp(fromStartCropRectangle: full, toEndCropRectangle: bottom, timeRange: range) dst.setCropRectangleRamp(fromStartCropRectangle: top, toEndCropRectangle: full, timeRange: range) } return [src, dst] } }
swift-master/VideoDecode/ScreenRecording/ScreenRecorder.swift
// // ScreenRecorder.swift // VideoDecode // // Created by larryhou on 10/01/2018. // import Foundation import ReplayKit import AVKit import UIKit.UIGestureRecognizerSubclass extension RPSampleBufferType: CustomStringConvertible { public var description: String { switch self { case .audioApp:return "audio_app" case .audioMic:return "audio_mic" case .video:return "video" } } } class UITouchGestureRecognizer: UIGestureRecognizer { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { self.state = .began } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { self.state = .changed } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { self.state = .ended } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { self.state = .cancelled } } private let recordMovie = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("record.mp4") private let exportMovie = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("export.mp4") public class ScreenRecorder: NSObject { @objc public static let shared: ScreenRecorder = ScreenRecorder(cameraViewport: CGSize(width: 100, height: 100)) private let cameraViewport: CGSize private var writer: AssetWriter! private var syncdata: [[Double]] = [] init(cameraViewport: CGSize = CGSize(width: 50, height: 50)) { self.cameraViewport = cameraViewport } @objc public var isRecording: Bool { return RPScreenRecorder.shared().isRecording } @objc public func startRecording(completion: ((Error?) -> Void)? = nil) { writer = try! AssetWriter(url: recordMovie) syncdata.removeAll() let recorder = RPScreenRecorder.shared() recorder.isMicrophoneEnabled = true recorder.isCameraEnabled = true recorder.cameraPosition = .front recorder.startCapture(handler: receiveScreenSample(sample:type:error:)) { (error) in DispatchQueue.main.async { self.setupCamera() if let cameraView = recorder.cameraPreviewView { cameraView.frame = CGRect(origin: CGPoint.zero, size: self.cameraViewport) cameraView.mask = self.drawCameraShape(size: self.cameraViewport) if let rootView = UIApplication.shared.keyWindow?.rootViewController?.view { let options: UIViewAnimationOptions = [.curveLinear, .transitionCrossDissolve] UIView.transition(with: rootView, duration: 1.0, options: options, animations: { rootView.addSubview(cameraView) }, completion: nil) } } completion?(error) } } } // MARK: camera private func setupCamera() { guard let cameraView = RPScreenRecorder.shared().cameraPreviewView else {return} if cameraView.constraints.count > 0 {return} let tap = UITouchGestureRecognizer(target: self, action: #selector(changeCamera(_:))) cameraView.addGestureRecognizer(tap) let pan = UIPanGestureRecognizer(target: self, action: #selector(moveCameraPreview(_:))) pan.maximumNumberOfTouches = 1 cameraView.addGestureRecognizer(pan) tap.require(toFail: pan) } @objc private func moveCameraPreview(_ gesture: UIPanGestureRecognizer) { guard let view = gesture.view else {return} switch gesture.state { case .began: gesture.setTranslation(CGPoint.zero, in: view) case .changed: let translation = gesture.translation(in: view) view.frame = view.frame.offsetBy(dx: translation.x, dy: translation.y) gesture.setTranslation(CGPoint.zero, in: view) case .ended: let bounds = UIScreen.main.bounds, frame = view.frame var offset = CGPoint.zero if frame.maxX > bounds.width { offset.x = bounds.width - frame.maxX } else if frame.minX < 0 { offset.x = -frame.minX } if frame.maxY > bounds.height { offset.y = bounds.height - frame.maxY } else if frame.minY < 0 { offset.y = -frame.minY } UIView.animate(withDuration: 0.5) { view.frame = frame.offsetBy(dx: offset.x, dy: offset.y) } default:break } } @objc private func changeCamera(_ gesture: UITouchGestureRecognizer) { guard gesture.state == .began else { return } if gesture.numberOfTouches >= 2 { let position = RPScreenRecorder.shared().cameraPosition switch position { case .back: RPScreenRecorder.shared().cameraPosition = .front case .front: RPScreenRecorder.shared().cameraPosition = .back } } else { if let view = RPScreenRecorder.shared().cameraPreviewView { let alpha: CGFloat if view.alpha == 1.0 { alpha = 0.2 } else { alpha = 1.0 } view.layer.removeAllAnimations() UIView.animate(withDuration: 0.2) { view.alpha = alpha } } } } private func drawCameraShape(size: CGSize) -> UIImageView? { UIGraphicsBeginImageContext(size) guard let context = UIGraphicsGetCurrentContext() else { return nil } UIColor.black.setFill() context.addEllipse(in: CGRect(origin: CGPoint.zero, size: size)) context.fillPath() let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return UIImageView(image: image) } // MARK: sample private var synctime: CMTime = kCMTimeZero private func receiveScreenSample(sample: CMSampleBuffer, type: RPSampleBufferType, error: Error?) { if error == nil { writer.append(sample: sample, type: type) if type == .video { let position = CMSampleBufferGetPresentationTimeStamp(sample) - writer.timeOffset if Int(position.seconds) % 5 == 0 && (position - synctime).seconds >= 1 { synctime = position synchronize(timestamp: position.seconds) } } } else { print(error ?? CMSampleBufferGetPresentationTimeStamp(sample).seconds) } } @objc public var fetchUnityTime:(() -> Double)? // get game timestamp for timesync private func synchronize(timestamp value: Double) { print("sychronize", value) if let time = fetchUnityTime?() { syncdata.append([value, time]) } } private func startExportSession(clipContext: String? = nil, completion: ((URL, AVAssetExportSessionStatus) -> Void)? = nil) { guard let clipContext = clipContext else { completion?(recordMovie, .cancelled) return } let offset: Double if syncdata.count > 0 { let samples = syncdata.map({ $0[0] - $0[1] }) offset = samples.reduce(0, { $0 + $1 }) / Double(samples.count) print("[SYNC]", samples, "OFFSET", offset) } else { offset = 0 } let clips = clipContext.split(separator: ";").map { (item) -> CMTimeRange in let pair = item.split(separator: "-").map({Double($0) ?? .nan}) let f = CMTime(seconds: pair[0] + offset, preferredTimescale: 600) let t = CMTime(seconds: pair[1] + offset, preferredTimescale: 600) return CMTimeRange(start: f, end: t) } if FileManager.default.fileExists(atPath: exportMovie.path) { try? FileManager.default.removeItem(at: exportMovie) } let editor = MovieEditor(transition: .dissolve, transitionDuration: 1.0) if let exporter = editor.cut(asset: AVAsset(url: recordMovie), with: clips) { self.exporter = exporter exporter.outputURL = exportMovie exporter.exportAsynchronously { DispatchQueue.main.async { completion?(exportMovie, exporter.status) self.reviewMovie(exportMovie) } } Timer.scheduledTimer(timeInterval: 1/30, target: self, selector: #selector(progressUpdate(_:)), userInfo: nil, repeats: true) } } private var exporter: AVAssetExportSession! @objc public func stopRecording(clipContext: String? = nil, completion: ((URL, AVAssetExportSessionStatus) -> Void)? = nil) { RPScreenRecorder.shared().stopCapture { (error) in print(error ?? "stop success") DispatchQueue.main.async { self.writer.save { self.startExportSession(clipContext: clipContext, completion: completion) } if let cameraView = RPScreenRecorder.shared().cameraPreviewView, let rootView = cameraView.superview { let options: UIViewAnimationOptions = [.curveLinear, .transitionCrossDissolve] UIView.transition(with: rootView, duration: 0.25, options: options, animations: { cameraView.removeFromSuperview() }, completion: nil) } } } } private func reviewMovie(_ url: URL) { if let rootViewController = UIApplication.shared.keyWindow?.rootViewController { let player = AVPlayer(url: url) let reviewController = AVPlayerViewController() reviewController.player = player rootViewController.present(reviewController, animated: true, completion: nil) player.play() } } @objc public var progressObserver: ((Float) -> Void)? @objc private func progressUpdate(_ timer: Timer) { progressObserver?(exporter.progress) if exporter.progress == 1.0 { timer.invalidate() } } } extension AVAssetWriterStatus: CustomStringConvertible { public var description: String { switch self { case .cancelled:return "cancelled" case .completed:return "completed" case .writing:return "writing" case .unknown:return "unknown" case .failed:return "failed" } } } class AssetWriter { private let writer: AVAssetWriter let url: URL private var movieTracks: [RPSampleBufferType: AVAssetWriterInput] = [:] init(url: URL) throws { self.url = url if FileManager.default.fileExists(atPath: url.path) { try? FileManager.default.removeItem(at: url) } self.writer = try AVAssetWriter(url: url, fileType: .mp4) self.writer.movieTimeScale = 600 } private var initialized = false private func setup(sample: CMSampleBuffer) { if (initialized) { return } initialized = true let videoOptions: [String: Any] = [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: UIScreen.main.bounds.width, AVVideoHeightKey: UIScreen.main.bounds.height] movieTracks[.video] = AVAssetWriterInput(mediaType: .video, outputSettings: videoOptions) if let format = CMSampleBufferGetFormatDescription(sample), let stream = CMAudioFormatDescriptionGetStreamBasicDescription(format) { let audioOptions: [String: Any] = [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVNumberOfChannelsKey: stream.pointee.mChannelsPerFrame, AVSampleRateKey: stream.pointee.mSampleRate] movieTracks[.audioApp] = AVAssetWriterInput(mediaType: .audio, outputSettings: audioOptions) movieTracks[.audioMic] = AVAssetWriterInput(mediaType: .audio, outputSettings: audioOptions) for (type, track) in movieTracks { track.expectsMediaDataInRealTime = true if writer.canAdd(track) { writer.add(track) } else { print("[AssetWriter] add track[\(type)] input fails") } } } timeOffset = CMSampleBufferGetPresentationTimeStamp(sample) writer.startWriting() writer.startSession(atSourceTime: timeOffset) } private(set) var timeOffset: CMTime = kCMTimeZero private let background = DispatchQueue(label: "video_encode_queue") func append(sample: CMSampleBuffer, type: RPSampleBufferType) { guard CMSampleBufferIsValid(sample) else {return} background.sync { if !initialized { setup(sample: sample) } if let track = movieTracks[type], track.isReadyForMoreMediaData { if type == .video { track.append(sample) if writer.status == .failed { print(type, writer.error!) } } else { track.append(sample) if writer.status == .failed { print(type, writer.error!) } } } } } func save(completion:(() -> Void)? = nil) { self.writer.finishWriting { print("finish", self.writer.status, self.writer.error ?? "success") completion?() } } }
swift-master/urlcodec/urlcodec/main.swift
// // main.swift // urlcodec // // Created by larryhou on 31/7/2015. // import Foundation var decodeMode = true, verbose = false var arguments = Process.arguments arguments = Array(arguments[1..<arguments.count]) let manager = ArgumentsManager() manager.insertOption("--encode-mode", abbr: "-e", help: "Use url encode mode to process", hasValue: false) { decodeMode = false } manager.insertOption("--decode-mode", abbr: "-d", help: "Use url decode mode to process", hasValue: false) { decodeMode = true } manager.insertOption("--verbose", abbr: "-v", help: "Enable verbose printing", hasValue: false) { verbose = true } manager.insertOption("--help", abbr: "-h", help: "Show help message", hasValue: false) { manager.showHelpMessage() exit(0) } while arguments.count > 0 { let text = arguments[0] if manager.recognizeOption(text, triggerWhenMatch: true) { arguments.removeAtIndex(0) if let hasValue = manager.getOption(text)?.hasValue where hasValue { //TODO: parsing argument value } } else { break } } if verbose { print(Process.arguments) } if arguments.count > 0 { while arguments.count > 0 { var text = arguments.removeAtIndex(0) if decodeMode { text = text.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! } else { text = text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! } print(text) } } else { manager.showHelpMessage(stderr) exit(1) }
swift-master/urlcodec/urlcodec/ArgumentsManager.swift
// // ArgumentsManager.swift // urlcodec // // Created by larryhou on 1/8/2015. // import Foundation class ArgumentsManager { struct ArgumentOption { let name: String, abbr: String, help: String, hasValue: Bool, trigger:() -> Void } private var map: [String: ArgumentOption] private var options: [ArgumentOption] private var pattern: NSRegularExpression! init() { self.options = [] self.map = [:] do { pattern = try NSRegularExpression(pattern: "^-[a-z]+|--[a-z_-]{2,}$", options: NSRegularExpressionOptions.CaseInsensitive) } catch {} } func insertOption(name: String, abbr: String, help: String, hasValue: Bool, trigger:() -> Void) { if name == "" && abbr == "" { return } let argOption = ArgumentOption(name: name, abbr: abbr, help: help, hasValue: hasValue, trigger: trigger) options.append(argOption) map[name] = argOption map[abbr] = argOption } func getOption(name: String) -> ArgumentOption? { return map[name] } func recognizeOption(value: String, triggerWhenMatch: Bool = false) -> Bool { let matches = pattern.matchesInString(value, options: NSMatchingOptions.ReportProgress, range: NSRange(location: 0, length: NSString(string: value).length)) if matches.count > 0 { if triggerWhenMatch { trigger(value) } return true } return false } func trigger(name: String) { map[name]?.trigger() } func padding(var value: String, length: Int, var filling: String = " ") -> String { if NSString(string: filling).length == 0 { filling = " " } else { filling = filling.substringToIndex(filling.startIndex.successor()) } while NSString(string: value).length < length { value += filling } return value } func showHelpMessage(stream: UnsafeMutablePointer<FILE> = stdout) { var maxNameLength = 0 var maxAbbrLength = 0 var abbrs: [String] = [] for var i = 0; i < options.count; i++ { maxNameLength = max(maxNameLength, NSString(string: options[i].name).length) maxAbbrLength = max(maxAbbrLength, NSString(string: options[i].abbr).length) abbrs.append(options[i].abbr) } fputs("urlcodec " + " ".join(abbrs) + " String ...\n", stream) for i in 0 ..< options.count { let item = options[i] var help = padding(item.abbr, length: maxAbbrLength) help += item.name == "" || item.abbr == "" ? " " : "," help += " " + padding(item.name, length: maxNameLength) + "\t" + item.help fputs(help + "\n", stream) } } }
swift-master/VisualEffect/VisualEffectTests/VisualEffectTests.swift
// // VisualEffectTests.swift // VisualEffectTests // // Created by larryhou on 28/08/2017. // import XCTest @testable import VisualEffect class VisualEffectTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
swift-master/VisualEffect/VisualEffect/ViewController.swift
// // ViewController.swift // VisualEffect // // Created by larryhou on 28/08/2017. // import UIKit class BlurController: UIViewController { @IBOutlet weak var blurView: UIVisualEffectView! override func viewDidLoad() { super.viewDidLoad() let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:))) view.addGestureRecognizer(pan) blurView.clipsToBounds = true } var fractionComplete = CGFloat.nan var dismissAnimator: UIViewPropertyAnimator! @objc func panUpdate(sender: UIPanGestureRecognizer) { switch sender.state { case .began: dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in self.view.frame.origin.y = self.view.frame.height self.blurView.layer.cornerRadius = 40 } dismissAnimator.addCompletion { [unowned self] position in if position == .end { self.dismiss(animated: false, completion: nil) } self.fractionComplete = CGFloat.nan } dismissAnimator.pauseAnimation() case .changed: if fractionComplete.isNaN {fractionComplete = 0} let translation = sender.translation(in: view) fractionComplete += translation.y / view.frame.height fractionComplete = min(1, max(0, fractionComplete)) dismissAnimator.fractionComplete = fractionComplete sender.setTranslation(CGPoint.zero, in: view) default: if dismissAnimator.fractionComplete <= 0.25 { dismissAnimator.isReversed = true } dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0) } } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
swift-master/VisualEffect/VisualEffect/AppDelegate.swift
// // AppDelegate.swift // VisualEffect // // Created by larryhou on 28/08/2017. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // 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, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // 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 applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }