Swift examples
Small pieces of an app built on the AudienceKit package, one per thing a screen does. They have no UI of their own,
so the same code feeds a SwiftUI view, a widget or a watch app, and the SDK’s tests run every one against
AudienceKitTesting’s GraphQLStub (in ExamplesTests.swift), the stub your own app’s tests can use too.
| File | What it shows |
|---|---|
WhatsOn.swift |
A locale’s upcoming events grouped by night, in the locale’s time zone, for a list or a widget |
NewsDigest.swift |
A Markdown digest of a locale’s news and its national news |
MemberActions.swift |
What a signed-in member does: RSVP, calendar links, the door pass (Apple platforms, which have CryptoKit) and reporting |
Signing in, the session and realtime are in the package’s README.
WhatsOn.swift
Section titled “WhatsOn.swift”// The "What's on" screen: a locale's upcoming events grouped by night, the way a list or a widget shows them. The// sections are plain values, so the same function feeds a SwiftUI List, a widget timeline or a watch complication://// List(nights) { night in// Section(night.title) { ForEach(night.rows) { row in Text(row.name) } }// }import AudienceKitimport Foundation
public enum WhatsOn { /// One night's events, soonest first. public struct Night: Identifiable, Equatable, Sendable { public let id: String public let title: String public let rows: [Row] }
/// What a row shows: the event, where, and when, in the locale's time zone. public struct Row: Identifiable, Equatable, Sendable { public let id: String public let name: String public let place: String? public let time: String public let canceled: Bool }
/// Groups `events` by the night they start on in `timeZone`; events with no start yet are left out. public static func nights(_ events: [Event], timeZone: TimeZone) -> [Night] { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = timeZone let title = DateFormatter() title.locale = Locale(identifier: "en_US_POSIX") title.timeZone = timeZone title.dateFormat = "EEEE, MMMM d" let time = DateFormatter() time.locale = Locale(identifier: "en_US_POSIX") time.timeZone = timeZone time.dateFormat = "h:mm a"
let scheduled = events.compactMap { event in event.startAt.map { (event, $0) } }.sorted { $0.1 < $1.1 } var nights: [Night] = [] for (event, start) in scheduled { let day = calendar.startOfDay(for: start) let row = Row(id: event.id, name: event.name ?? "Untitled", place: event.venueName, time: time.string(from: start), canceled: event.isCanceled) let key = ISO8601DateFormatter().string(from: day) if let last = nights.last, last.id == key { nights[nights.count - 1] = Night(id: key, title: last.title, rows: last.rows + [row]) } else { nights.append(Night(id: key, title: title.string(from: start), rows: [row])) } } return nights }
/// The locale's upcoming events, by night. public static func load(_ client: AudienceKitClient, localeID: String, timeZone: TimeZone = TimeZone(identifier: "America/Denver")!) async throws -> [Night] { nights(try await client.events(window: .upcoming, localeID: localeID), timeZone: timeZone) }}NewsDigest.swift
Section titled “NewsDigest.swift”// A Markdown digest of a locale's news, for a newsletter, a share sheet or a "This week" card in the app. Empty for an// audience without Soapbox, rather than failing.import AudienceKitimport Foundation
public enum NewsDigest { /// One article as a Markdown list item. A teaser carries only the start: the rest is on the publication's site. public static func line(_ article: Article) -> String { let name = article.publication.name var text = "- **\(article.title)**, \(article.byline) for \(name)" if article.teaser, let url = article.canonicalUrl { text += " ([read on \(name)](https://github.com/lwm-luminx/audience-kit-sdk/blob/main/swift/Examples/\(url)))" } if let summary = article.summary { text += "\n \(summary)" } if let disclosure = article.disclosure { text += "\n _\(disclosure)_" } return text }
/// The digest for the locale named `localeName` (or the audience's first): its news, then the national news. public static func digest(_ client: AudienceKitClient, localeName: String? = nil) async throws -> String { let locales = try await client.locales() guard let locale = locales.first(where: { $0.name == localeName }) ?? locales.first else { return "" } async let local = client.articles(localeID: locale.id, first: 10) async let national = client.nationalArticles(localeID: locale.id, first: 5) let news = try await local var sections = ["# \(locale.name ?? "Your city") this week"] if !news.isEmpty { sections.append("## Local news\n\n" + news.map(line).joined(separator: "\n")) } let seen = Set(news.map(\.id)) let elsewhere = try await national.filter { !seen.contains($0.id) } if !elsewhere.isEmpty { sections.append("## Around the country\n\n" + elsewhere.map(line).joined(separator: "\n")) } return sections.count > 1 ? sections.joined(separator: "\n\n") + "\n" : "" }}MemberActions.swift
Section titled “MemberActions.swift”// What a signed-in member does in the app, in the order a night out goes: RSVP, add it to their calendar, show the// cover pass at the door, and report something they saw in chat.import AudienceKitimport Foundation
public enum MemberActions { /// Says they're going, and returns their answer as the API recorded it. public static func goingTo(_ client: AudienceKitClient, eventID: String) async throws -> RSVPState { try await client.setRSVP(.attending, forEvent: eventID) }
/// Links that add every event they're going to (and every event at `venueID`) to their own calendar: open /// `webcalUrl` for Apple Calendar or Outlook, `googleUrl` for Google Calendar. public static func calendarLinks(_ client: AudienceKitClient, venueID: String? = nil) async throws -> CalendarLinks { if let venueID { return try await client.followVenueInCalendar(venueID: venueID).links } return try await client.createCalendarFeed().links }
#if canImport(CryptoKit) /// The door code and how many seconds it's good for. public struct DoorPass: Equatable, Sendable { public let code: String public let refreshInSeconds: Int }
/// The code to show at the door for tonight's cover at a venue. It changes every 30 seconds, so draw it as a QR /// code (in a `TimelineView(.periodic(from: .now, by: 1))`) and draw it again when `refreshInSeconds` runs out. /// It's made on the phone, so it works with no signal. public static func doorPass(_ client: AudienceKitClient, venueID: String, at date: Date = Date()) async throws -> DoorPass? { guard let pass = try await client.venueCover(venueID: venueID)?.viewerAdmission, pass.status == .paid, let secret = pass.passSecret, let code = CoverPass.code(admissionID: pass.id, secret: secret, at: date) else { return nil } return DoorPass(code: code, refreshInSeconds: CoverPass.secondsRemaining(at: date)) } #endif
/// Reports a chat message as harassment and blocks whoever sent it. public static func reportHarassment(_ client: AudienceKitClient, messageID: String) async throws -> ReportResult { try await client.reportContent(.message, id: messageID, reason: ReportCopy.reasons[1], block: true) }}