SwiftPizza App for Apple ActivityKit & WidgetKit

Last update: Aug 2, 2022

activitykit-128x128_2x

iOS16 Live Activities (๏ฃฟ ActivityKit Demo)

SwiftPizza ๐Ÿ• ๐Ÿ‘จ๐Ÿปโ€๐Ÿณ App for Apple ActivityKit & WidgetKit

This is the first project example referring to the latest Apple ActivityKit beta release.

Live Activities will help you follow an ongoing activity right from your Lock Screen, so you can track the progress of your food delivery or use the Now Playing controls without unlocking your device.

Preview

CleanShot 2022-07-29 at 13 37 05

More Videos

https://twitter.com/1998design/status/1552681295607566336?s=21&t=waceX8VvaP-VCGc2KJmHpw https://twitter.com/1998design/status/1552686498276814848?s=21&t=waceX8VvaP-VCGc2KJmHpw

Environment

  • iOS 16 beta 4 or above
  • Xcode 14 beta 4 or above

Tutorial

Medium: https://1998design.medium.com/how-to-create-live-activities-widget-for-ios-16-2c07889f1235

Usage

Info.plist

Add NSSupportsLiveActivities key and set to YES.

Import

import ActivityKit

Activity Attributes (Targeted to both App and Widget)

struct PizzaDeliveryAttributes: ActivityAttributes {
    public typealias PizzaDeliveryStatus = ContentState

    public struct ContentState: Codable, Hashable {
        var driverName: String
        var estimatedDeliveryTime: Date
    }

    var numberOfPizzas: Int
    var totalAmount: String
}

Gist: https://gist.github.com/1998code/c58a0e53ce1eae2ba5f0549ae6d9a370

Functions (Start / Update / Stop / Show ALL)

func startDeliveryPizza() {
    let pizzaDeliveryAttributes = PizzaDeliveryAttributes(numberOfPizzas: 1, totalAmount:"$99")

    let initialContentState = PizzaDeliveryAttributes.PizzaDeliveryStatus(driverName: "TIM ๐Ÿ‘จ๐Ÿปโ€๐Ÿณ", estimatedDeliveryTime: Date().addingTimeInterval(15 * 60))

    do {
        let deliveryActivity = try Activity<PizzaDeliveryAttributes>.request(
            attributes: pizzaDeliveryAttributes,
            contentState: initialContentState,
            pushType: nil)
        print("Requested a pizza delivery Live Activity \(deliveryActivity.id)")
    } catch (let error) {
        print("Error requesting pizza delivery Live Activity \(error.localizedDescription)")
    }
}

func updateDeliveryPizza() {
    Task {
        let updatedDeliveryStatus = PizzaDeliveryAttributes.PizzaDeliveryStatus(driverName: "TIM ๐Ÿ‘จ๐Ÿปโ€๐Ÿณ", estimatedDeliveryTime: Date().addingTimeInterval(60 * 60))

        for activity in Activity<PizzaDeliveryAttributes>.activities{
            await activity.update(using: updatedDeliveryStatus)
        }
    }
}

func stopDeliveryPizza() {
    Task {
        for activity in Activity<PizzaDeliveryAttributes>.activities{
            await activity.end(dismissalPolicy: .immediate)
        }
    }
}

func showAllDeliveries() {
    Task {
        for activity in Activity<PizzaDeliveryAttributes>.activities {
            print("Pizza delivery details: \(activity.id) -> \(activity.attributes)")
        }
    }
}

Gist: https://gist.github.com/1998code/f32848acf22dc776b168f82cd68e8c61

Widgets

import ActivityKit
import WidgetKit
import SwiftUI

@main
struct Widgets: WidgetBundle {
   var body: some Widget {
       PizzaDeliveryActivityWidget()
   }
}

struct PizzaDeliveryActivityWidget: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(attributesType: PizzaDeliveryAttributes.self) { context in
            VStack(alignment: .leading) {
                HStack {
                    VStack(alignment: .leading) {
                        Text("\(context.state.driverName) is on the way!").font(.headline)
                        HStack {
                            VStack {
                                Divider().frame(height: 6).overlay(.blue).cornerRadius(5)
                            }
                            Image(systemName: "box.truck.badge.clock.fill").foregroundColor(.blue)
                            VStack {
                                RoundedRectangle(cornerRadius: 5)
                                    .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
                                    .frame(height: 6)
                            }
                            Text(context.state.estimatedDeliveryTime, style: .timer)
                            VStack {
                                RoundedRectangle(cornerRadius: 5)
                                    .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
                                    .frame(height: 6)
                            }
                            Image(systemName: "house.fill").foregroundColor(.green)
                        }
                    }.padding(.trailing, 25)
                    Text("\(context.attributes.numberOfPizzas) ๐Ÿ•").font(.title).bold()
                }.padding(5)
                Text("You've already paid: \(context.attributes.totalAmount) + $9.9 Delivery Fee ๐Ÿ’ธ").font(.caption).foregroundColor(.secondary)
            }.padding(15)
        }
    }
}

Gist: https://gist.github.com/1998code/fea1227e866bc8c9a82ed1dc9654cdc3

Responses

Start Activity

// Requested a pizza delivery Live Activity DA288E1B-F6F5-4BF1-AA73-E43E0CC13150

Show ALL Activities

// Pizza delivery details: DA288E1B-F6F5-4BF1-AA73-E43E0CC13150 -> PizzaDeliveryAttributes(numberOfPizzas: 1, totalAmount: "$99")

Resources

https://developer.apple.com/documentation/activitykit/displaying-live-data-on-the-lock-screen-with-live-activities

Legal

Swiftยฎ and SwiftUIยฎ are trademarks of Apple Inc.

GitHub

https://github.com/1998code/iOS16-Live-Activities
You might also like...

Provides some Apple Wallet functionality, like adding passes, removing passes and checking passises for existing.

Provides some Apple Wallet functionality, like adding passes, removing passes and checking passises for existing.

react-native-wallet-manager Provides some Apple Wallet's functionality, like adding passes, removing passes and checking passises for existing. Instal

Jul 18, 2022

Apple Developer Academy @ POSTECH Afternoon Session Team 13 MC2

Apple Developer Academy @ POSTECH Afternoon Session Team 13 MC2

๐Ÿ“ฑ Project Title A brief description of what this project does and who it's for ๐Ÿ“Œ Features Light/dark mode toggle Live previews Fullscreen mode Cross

Jul 19, 2022

React Native Todo List example app which uses Redux for managing app state

React Native Todo List example app which uses Redux for managing app state

react-native-redux-todo-list A sample todo list app developed by using React Native and Redux. How to run the app Install react-native If you don't ha

Feb 16, 2022

Google-Blogger-iOS-App - Using Google Blogger API to build an iOS app like Medium

Google Blogger iOS App Using Google Blogger API to build an iOS app like Medium๏ผ

May 16, 2022

Codepath-intro-prework - Hello World iOS App | Prework Project for CodePath Intro to Mobile App Development

Codepath-intro-prework - Hello World iOS App | Prework Project for CodePath Intro to Mobile App Development

Hello World iOS App App Description Prework Project for CodePath Intro to Mobile

Jan 25, 2022

Turn your Swift data model into a working CRUD app.

Turn your Swift data model into a working CRUD app.

Model2App is a simple library that lets you quickly generate a CRUD iOS app based on just a data model defined in Swift. (CRUD - Create Read Update De

Aug 5, 2022

an onboarding app built in SwiftUI

an onboarding app built in SwiftUI

hello hello is application onboarding macOS devices. Inspired by Kandji's Liftoff Logo created with Type with Pride font family Warning DO NOT USE THI

Jul 20, 2022

LinearMouse - A minimal app to get rid of mouse acceleration on macOS

LinearMouse A minimal app to get rid of mouse acceleration on macOS. Features Reverse the direction of scrolling. Linear scrolling (disable scrolling

Aug 8, 2022

A template Vapor app with nginx frontend.

A template Vapor app with nginx frontend.

This is an example Vapor app. It contains the app itself, as well as surrounding components (Postgres database, nginx frontend for providing secure connection), all runnable out of the box with docker compose. It is a good starting point for Vapor development of an API server which you could access from macOS and iOS clients.

Jul 1, 2022
Comments
  • 1. How you preview the live activity UI on development?

    It's a helpful and amazing demo!

    but I don't see any preview code on this demo. I wanna know how to preview the activity widget use the PreviewProvider ? or you just run entire app to preview the UI?

    struct live_activities_Previews: PreviewProvider {
        static var previews: some View {
            live_activitiesEntryView(context: !how to create this!)
                .previewContext(WidgetPreviewContext(family: .systemSmall))
        }
    }
    

    Thanks!

    Reviewed by Yggdrasilqh at 2022-07-30 12:11
Mimicrated views and controls to native Apple appearance.
Mimicrated views and controls to native Apple appearance.

Mimicrated views and controls to native Apple appearance. If you have any ideas of what elements can be added, let me know. Below you will see previews of all the elements and how to use them.

Jul 29, 2022
A apple search ads attribution plugin for flutter

A apple search ads attribution plugin for flutter

Oct 27, 2021
A collection of Swift Tutorials built with Apple's DocC.

Swift Tutorials This is not a package, it's just a bunch of tutorials This project uses Apple's DocC (Documentation Compiler) to create a set of Swift

Apr 15, 2022
An Apple Watch remake of the Poketch from Pokemon Diamond and Pearl made with SwiftUI
An Apple Watch remake of the Poketch from Pokemon Diamond and Pearl made with SwiftUI

Apple Watch Poketch What is it? It's an Apple Watch remake of the "Poketch" from Pokemon Diamond and Pearl made with SwiftUI! Check out the YouTube vi

Nov 19, 2021
Home Assistant for Apple Platforms

Home Assistant for Apple Platforms Getting Started Home Assistant uses Bundler, Homebrew and Cocoapods to manage build dependencies. You'll need Xcode

Nov 23, 2021
Open-source implementation of Apple's Combine for processing values over time

CombineX ็ฎ€ไฝ“ไธญๆ–‡ Open-source implementation of Apple's Combine for processing values over time. Though CombineX have implemented all the Combine interfac

Dec 30, 2021
Restaurant - Educational application from the Apple Mobile Development Course for MDA
Restaurant - Educational application from the Apple Mobile Development Course for MDA

Restaurant Educational application from the Apple Mobile Development Course for

Jan 14, 2022
Apple SMC library & tool

SMCKit An Apple System Management Controller (SMC) library & command line tool in Swift for Intel based Macs. The library works by talking to the Appl

Jun 26, 2022
Appwrite playground - a simple way to explore the Appwrite API & Appwrite Apple SDK

Appwrite's Apple Playground ?? Appwrite playground is a simple way to explore the Appwrite API & Appwrite Apple SDK. Use the source code of this repos

Jul 1, 2022
SwiftyXPC - a wrapper for Appleโ€™s XPC interprocess communication library that gives it an easy-to-use, idiomatic Swift interface.

SwiftyXPC is a wrapper for Appleโ€™s XPC interprocess communication library that gives it an easy-to-use, idiomatic Swift interface.

Jul 31, 2022