SwiftPizza App for Apple ActivityKit & WidgetKit

Overview

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.

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

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

โ˜Ž๏ธ NextcloudKit Apple library

NextcloudKit Installation Carthage Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary framework

A Swift cross-platform (Apple and Linux) networking library.

KippleNetworking A Swift library that offers cross-platform (Apple and Linux) networking support, intended for the creation of cross-platform SDKs to

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

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๏ผ

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

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

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

Comments
  • How you preview the live activity UI on development?

    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!

    opened by Yggdrasilqh 2
  • Revert

    Revert "Update project to support APNs updates"

    Reverts 1998code/iOS16-Live-Activities#9

    Bugs: -Time is not correct CleanShot 2022-10-27 at 20 50 38@2x

    • Error Occur when token is missed, please try the following instead.
    @State var remotePush = false
    .
    .
    .
    pushType: remotePush ? .token : nil
    
    opened by 1998code 1
  • Restyle Revert

    Restyle Revert "Update project to support APNs updates"

    Automated style fixes for #10, created by Restyled.

    The following restylers made fixes:

    To incorporate these changes, merge this Pull Request into the original. We recommend using the Squash or Rebase strategies.

    NOTE: As work continues on the original Pull Request, this process will re-run and update (force-push) this Pull Request with updated style fixes as necessary. If the style is fixed manually at any point (i.e. this process finds no fixes to make), this Pull Request will be closed automatically.

    Sorry if this was unexpected. To disable it, see our documentation.

    opened by restyled-io[bot] 0
Owner
MING
๏ฃฟ Developer, UI Designer, Engineer WWDC Award Winner
MING
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.

Ivan Vorobei 85 Dec 3, 2022
A apple search ads attribution plugin for flutter

A apple search ads attribution plugin for flutter

liam 0 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

Swift Innovators Network 11 Aug 9, 2022
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

Andrรฉ Arko 1 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

null 0 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

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

Restaurant Educational application from the Apple Mobile Development Course for

NIKOLAY NIKITIN 0 Aug 8, 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

Omeed 415 Dec 10, 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

Appwrite 24 Nov 22, 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.

null 36 Jan 1, 2023