### Loading the Setup View Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupviewcontroller Loads the cloud service setup view with specified options. Use this method to present the setup interface to the user. It takes an array of options and a completion handler that indicates success or failure. ```swift func load(options: [SKCloudServiceSetupOptionsKey : Any], completionHandler: ((Bool, (any Error)?) -> Void)?) { // ... implementation details ... } ``` -------------------------------- ### Load and Present Setup View Controller (Swift) Source: https://developer.apple.com/documentation/storekit/offering-apple-music-subscription-in-your-app Loads the setup view controller with options and presents it modally if the loading is successful and no errors occur. ```swift controller.load(options: options) { [weak self] (result: Bool, error: Error?) in guard error == nil else { return } if result { self?.present(controller, animated: true, completion: nil) } } ``` -------------------------------- ### Load and Present Setup View Controller (Objective-C) Source: https://developer.apple.com/documentation/storekit/offering-apple-music-subscription-in-your-app Loads the setup view controller with options and presents it modally if the loading is successful and no errors occur. ```objectivec [controller loadWithOptions:options completionHandler:^(BOOL result, NSError *error) { if(error != nil) { // Handle error. } else if (result) { [self presentViewController:controller animated:YES completion:nil]; } }]; ``` -------------------------------- ### load(options:completionHandler:) Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupviewcontroller Loads the cloud service setup view with the specified options. This method is used to initiate the setup process for cloud services. ```APIDOC ## Loading the setup view `func load(options: [SKCloudServiceSetupOptionsKey : Any], completionHandler: ((Bool, (any Error)?) -> Void)?)` Loads the cloud service setup view with the specified options. The completion handler is called with a boolean indicating success and an optional error object. ``` -------------------------------- ### Start Downloads with SKPaymentQueue (Swift) Source: https://developer.apple.com/documentation/storekit/skpaymentqueue/start%28_%3A%29 Adds a set of `SKDownload` objects to the download list. The downloads must be associated with a successfully purchased but unfinished transaction. This method is deprecated. ```swift func start(_ downloads: [SKDownload]) ``` -------------------------------- ### Start SKRequest - Swift Source: https://developer.apple.com/documentation/storekit/skrequest/start%28%29 The `start()` method is used to initiate a request to the Apple App Store. The results of the request are delivered to the delegate object. This method is deprecated across multiple Apple platforms. ```swift func start() ``` -------------------------------- ### StoreView Example with ProductIconPhase Source: https://developer.apple.com/documentation/storekit/producticonphase This example demonstrates how to use the ProductIconPhase enumeration within a StoreView to conditionally display different UI elements based on the loading status of a product's promotional image. ```APIDOC StoreView(products: [ product1, product2, // Additional products, as needed. ]) { product, phase in switch phase { case .loading: MyPlaceholder() case .failure(let error): MyErrorView(error) case .unavailable: MyDefaultIcon() case .success(let promotedIcon): promotedIcon } } ``` -------------------------------- ### Initialize ProductView with Configuration Source: https://developer.apple.com/documentation/storekit/productview Create a ProductView using a configuration object for styling. ```swift init(ProductViewStyleConfiguration) ``` -------------------------------- ### Getting the Recent Subscription Start Date Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/renewalinfo Retrieves the earliest start date of a subscription series, ignoring short lapses in paid service. ```swift var recentSubscriptionStartDate: Date ``` -------------------------------- ### Getting the period date range Source: https://developer.apple.com/documentation/storekit/product/subscriptionperiod Calculates the date range of a subscription period, starting at the reference date. ```APIDOC ## Getting the period date range ### Description Calculates the date range of a subscription period, starting at the reference date. ### Method `func dateRange(referenceDate: Date) -> Range` ### Parameters - **referenceDate** (Date) - The starting date for the range calculation. ``` -------------------------------- ### Creating a ProductView with Custom Icons Source: https://developer.apple.com/documentation/storekit/productview/init%28id%3Apreferspromotionalicon%3Aicon%3Aplaceholdericon%3A%29 Example of initializing a `ProductView` with a specific product ID, a custom icon using a system image, and a gray system image as a placeholder. ```swift ProductView(id: "com.example.product") { Image(systemName: "star.fill") .foregroundStyle(.yellow) } placeholderIcon: { Image(systemName: "star.fill") .foregroundStyle(.gray) } ``` -------------------------------- ### Getting the Price Increase Status Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/renewalinfo/priceincreasestatus-swift.enum This example shows how to access the price increase status for an auto-renewable subscription. ```swift let priceIncreaseStatus: Product.SubscriptionInfo.RenewalInfo.PriceIncreaseStatus ``` -------------------------------- ### GET additionalValue(forKey:) Source: https://developer.apple.com/documentation/storekit/skoverlay/appclipconfiguration/additionalvalue%28forkey%3A%29 Retrieves an object associated with a specific key used for verifying and associating app installations with ad campaigns. ```APIDOC ## GET additionalValue(forKey:) ### Description Returns the object associated with the specified key. This is used to verify and associate an app installation with an ad campaign. ### Method Instance Method ### Endpoint additionalValue(forKey: String) -> Any? ### Parameters #### Path Parameters - **key** (String) - Required - The string that identifies an additional value. ### Request Example ```swift let value = overlay.additionalValue(forKey: "campaign_id") ``` ### Response #### Success Response - **value** (Any?) - The associated value of the key, or nil if no value exists. #### Response Example ```json "campaign_12345" ``` ``` -------------------------------- ### Initialize StoreView with Preloaded Products and Promotional Images Source: https://developer.apple.com/documentation/storekit/storeview Create a StoreView that displays a collection of preloaded products, using their promotional images. ```swift init(products: some Collection, icon: (Product, ProductIconPhase) -> Icon) ``` -------------------------------- ### init(_:icon:) Source: https://developer.apple.com/documentation/storekit/subscriptionofferview/init%28_%3Aicon%3A%29 Initializes a `SubscriptionOfferView` with a `Product` and a closure that provides a custom icon based on the `ProductIconPhase`. ```APIDOC ## init(_:icon:) ### Description Initializes a `SubscriptionOfferView` with a `Product` and a closure that provides a custom icon based on the `ProductIconPhase`. ### Parameters #### Path Parameters * `subscription` (Product) - Required - The product for which to display subscription information. * `icon` (@ViewBuilder (ProductIconPhase) -> Icon) - Required - A closure that returns a view representing the icon. The closure receives the current `ProductIconPhase`. ### Generics * `PlaceholderIcon` - Must conform to `EmptyView`. ``` -------------------------------- ### Get Overlay Start Frame (Swift) Source: https://developer.apple.com/documentation/storekit/skoverlay/transitioncontext/startframe Retrieves the size and location of the overlay before the transition begins. This property is read-only and returns a CGRect value. ```swift var startFrame: CGRect { get } ``` -------------------------------- ### Get and Set campaignToken (Swift) Source: https://developer.apple.com/documentation/storekit/skoverlay/appclipconfiguration/campaigntoken The campaignToken is a String? that represents an ad campaign for measuring effectiveness. It is available on iOS, iPadOS, Mac Catalyst, and visionOS starting from version 14.0. ```swift var campaignToken: String? { get set } ``` -------------------------------- ### Get SKAdTestPostback Version Source: https://developer.apple.com/documentation/storekittest/skadtestpostback/version Retrieves the SKAdNetwork version associated with a postback. This property is read-only and returns a value of type SKAdTestPostbackVersion. It is available on iOS, iPadOS, and Mac Catalyst starting from version 15.4. ```swift var version: SKAdTestPostbackVersion { get } ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/storekit/regularproductviewstyle/init%28%29 Creates a regular product view style. ```APIDOC ## init() ### Description Creates a regular product view style. ### Method `init()` ### Parameters This initializer does not take any parameters. ### Availability StoreKit SwiftUI iOS 17.0+ iPadOS 17.0+ Mac Catalyst 17.0+ macOS 14.0+ tvOS 17.0+ visionOS 1.0+ watchOS 10.0+ ``` -------------------------------- ### Initialize StoreView with Products Source: https://developer.apple.com/documentation/storekit/storeview/init%28products%3Apreferspromotionalicon%3A%29 Use this initializer to create a `StoreView` that displays a collection of products. By default, promotional icons are not shown. ```swift nonisolated init( products: some Collection, prefersPromotionalIcon: Bool = false ) where Icon == EmptyView, PlaceholderIcon == EmptyView ``` -------------------------------- ### SKDownloadState.waiting Case Example (Swift) Source: https://developer.apple.com/documentation/storekit/skdownloadstate/waiting This code snippet demonstrates the usage of the 'waiting' case within the SKDownloadState enumeration in Swift. It indicates that the download has not started yet. This case is deprecated across multiple Apple operating system versions. ```swift case waiting ``` -------------------------------- ### Displaying products with StoreKit StoreView in SwiftUI Source: https://developer.apple.com/documentation/storekit/getting-started-with-in-app-purchases-using-storekit-views This SwiftUI view demonstrates how to use the StoreView component to render a grid of products. It requires an environment-injected Store object and a list of product IDs to determine which items to display. ```swift import StoreKit import SwiftUI struct AllProductsView: View { // Your app's data store. @Environment(Store.self) private var store: Store var body: some View { @Bindable var store = store VStack { // ProductID.all is an array of your product ID strings. StoreView(ids: ProductID.all) .storeButton(.hidden, for: .cancellation) .storeButton(.visible, for: .restorePurchases) } .padding() } } ``` -------------------------------- ### Define Product IDs with Swift Enum Source: https://developer.apple.com/documentation/storekit/getting-started-with-in-app-purchases-using-storekit-views Defines product IDs for in-app purchases using a Swift enumeration with raw string values. This approach enhances code readability and provides compile-time error checking when new products are added. ```swift enum ProductID: String { case consumable = "consumable" case consumablePack = "consumable_pack" case nonconsumable = "nonconsumable" case subscriptionMonthly = "subscription_monthly" case subscriptionYearly = "subscription_yearly" case subscriptionPremiumYearly = "premium_subscription_yearly" } ``` -------------------------------- ### Creating a StoreView with a Custom Icon Source: https://developer.apple.com/documentation/storekit/storeview/init%28products%3Apreferspromotionalicon%3Aicon%3A%29 Example of how to instantiate a `StoreView` with a list of products and a custom icon using a system image. ```swift StoreView(products: [ product1, product2, // Add products as needed. ]) { product in Image(systemName: "star.fill") .foregroundStyle(.yellow) } ``` -------------------------------- ### Initialize and Monitor StoreKit Transactions in Swift Source: https://developer.apple.com/documentation/storekit/getting-started-with-in-app-purchases-using-storekit-views This Swift code initializes a Store class that monitors StoreKit transactions. It checks for unfinished transactions, current entitlements, and ongoing updates at app startup and in the background. It relies on the Foundation, Observation, and StoreKit frameworks. ```swift import Foundation import Observation import StoreKit @MainActor @Observable final class Store { private let defaultsKey = "com.example.consumable count" private let nonConsumableDefaultsKey = "com.example.nonconsumable" public var consumableCount: Int { willSet { UserDefaults.standard.set(newValue, forKey: defaultsKey) } } public var boughtNonConsumable: Bool = false public var activeSubscription: String? = nil init() { self.consumableCount = UserDefaults.standard.integer(forKey: defaultsKey) // Returns 0 on first app launch. // Because the tasks below capture 'self' in their closures, this object must be fully initialized before this point. Task(priority: .background) { // Finish any unfinished transactions -- for example, if the app was terminated before finishing a transaction. for await verificationResult in Transaction.unfinished { await handle(updatedTransaction: verificationResult) } // Fetch current entitlements for all product types except consumables. for await verificationResult in Transaction.currentEntitlements { await handle(updatedTransaction: verificationResult) } } Task(priority: .background) { for await verificationResult in Transaction.updates { await handle(updatedTransaction: verificationResult) } } } // Placeholder for the handle method, which is defined in the next snippet. private func handle(updatedTransaction verificationResult: VerificationResult) async { // Implementation provided in the next code snippet. } } // Define ProductID enum for clarity, assuming it's defined elsewhere or needs to be added. enum ProductID: RawRepresentable { case consumable case consumablePack case nonconsumable case subscriptionMonthly case subscriptionYearly case subscriptionPremiumYearly var rawValue: String { switch self { case .consumable: return "com.example.consumable" case .consumablePack: return "com.example.consumablepack" case .nonconsumable: return "com.example.nonconsumable" case .subscriptionMonthly: return "com.example.subscription.monthly" case .subscriptionYearly: return "com.example.subscription.yearly" case .subscriptionPremiumYearly: return "com.example.subscription.premium.yearly" } } init?(rawValue: String) { switch rawValue { case "com.example.consumable": self = .consumable case "com.example.consumablepack": self = .consumablePack case "com.example.nonconsumable": self = .nonconsumable case "com.example.subscription.monthly": self = .subscriptionMonthly case "com.example.subscription.yearly": self = .subscriptionYearly case "com.example.subscription.premium.yearly": self = .subscriptionPremiumYearly default: return nil } } } ``` -------------------------------- ### Initiate a Purchase Source: https://developer.apple.com/documentation/storekit/productviewstyleconfiguration/purchase%28%29 Call this method to start the purchase process for a product. Use this instead of directly calling `purchase(options:)` on the product. ```swift func purchase() ``` -------------------------------- ### Handle StoreKit Transaction Updates in Swift Source: https://developer.apple.com/documentation/storekit/getting-started-with-in-app-purchases-using-storekit-views This Swift code defines the `handle(updatedTransaction:)` method for the Store class. It processes verified StoreKit transactions, managing product access based on whether the transaction is a purchase, a renewal, or a revocation. It ensures transactions are finished after processing. ```swift private func handle(updatedTransaction verificationResult: VerificationResult) async { // The code below handles only verified transactions; handle unverified transactions based on your business model. guard case .verified(let transaction) = verificationResult else { return } if let _ = transaction.revocationDate { // Remove access to the product identified by `transaction.productID`. // `Transaction.revocationReason` provides details about the revoked transaction. guard let productID = ProductID(rawValue: transaction.productID) else { print("Unexpected product: (transaction.productID).") return } switch productID { case .consumable: consumableCount -= 1 case .consumablePack: consumableCount -= 10 case .nonconsumable: boughtNonConsumable = false case .subscriptionMonthly, .subscriptionYearly, .subscriptionPremiumYearly: // In an app that supports Family Sharing, there might be another entitlement that still provides access to the subscription. activeSubscription = nil } await transaction.finish() return } else if let expirationDate = transaction.expirationDate, expirationDate < Date() { // In an app that supports Family Sharing, there might be another entitlement that still provides access to the subscription. activeSubscription = nil return } else { // Provide access to the product identified by transaction.productID. guard let productID = ProductID(rawValue: transaction.productID) else { print("Unexpected product: (transaction.productID).") return } print("transaction ID (transaction.id), product ID (transaction.productID)") switch productID { case .consumable: consumableCount += 1 case .consumablePack: consumableCount += 10 case .nonconsumable: boughtNonConsumable = true case .subscriptionMonthly, .subscriptionYearly, .subscriptionPremiumYearly: // In an app that supports Family Sharing, there might be another entitlement that already provides access to the subscription. activeSubscription = transaction.productID } await transaction.finish() return } } // Assuming ProductID enum is defined as in the previous snippet or globally. ``` -------------------------------- ### Initialize StoreView with Product IDs, Promotional Images, and Custom Placeholder Source: https://developer.apple.com/documentation/storekit/storeview Create a StoreView that loads products from the App Store using identifiers, displays their promotional images, and uses a custom placeholder icon. ```swift init(ids: some Collection, icon: (Product, ProductIconPhase) -> Icon, placeholderIcon: () -> PlaceholderIcon) ``` -------------------------------- ### Set and Get StoreKit Test Locale Source: https://developer.apple.com/documentation/storekittest/sktestsession/locale The 'locale' property determines the localization metadata the test environment uses for fetching localized metadata for SKProductsRequest. You can set this property to override the default locale specified in your StoreKit configuration file. It is available on iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, and watchOS starting from specific versions. ```swift var locale: Locale { get set } ``` -------------------------------- ### init(_:icon:) Source: https://developer.apple.com/documentation/storekit/productview/init%28_%3Aicon%3A%29 Creates a view to display a product that the system already loaded from the App Store, and merchandise it using its promotional image. The product view asynchronously loads and displays the product’s promotional image. The `ProductIconPhase` value indicates whether the promotional image is loading, unavailable, or whether it succeeded or failed to load. ```APIDOC ## init(_:icon:) ### Description Creates a view to display a product that the system already loaded from the App Store, and merchandise it using its promotional image. ### Signature ```swift nonisolated init( _ product: Product, @ViewBuilder icon: @escaping (ProductIconPhase) -> Icon ) where PlaceholderIcon == EmptyView ``` ### Parameters `product` - **Type**: Product - **Description**: The product to merchandise. `icon` - **Type**: @escaping (ProductIconPhase) -> Icon - **Description**: A closure that receives a `ProductIconPhase` as an input, which indicates the state of the loading operation of the product’s promoted image, and returns the view to display for the specified phase. ### Discussion The product view asynchronously loads and displays the product’s promotional image. The `ProductIconPhase` value indicates whether the promotional image is loading, unavailable, or whether it succeeded or failed to load. Use the `ProductIconPhase` to monitor current loading phase, and to decide the image to return in the `icon` closure. ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/storekit/compactpickersubscriptionstorecontrolstyle/init%28%29 Creates a compact picker subscription store control style. ```APIDOC ## init() ### Description Creates a compact picker subscription store control style. ### Method `init()` ### Parameters This initializer does not take any parameters. ### Availability StoreKit SwiftUI iOS 18.0+ iPadOS 18.0+ Mac Catalyst 18.0+ macOS 15.0+ visionOS 2.0+ ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/storekit/productview/init%28id%3Aicon%3Aplaceholdericon%3A%29 Creates a view to load an individual product from the App Store, and merchandise it using its promotional image and a custom placeholder icon. ```APIDOC ## init(id:icon:placeholderIcon:) ### Description Creates a view to load an individual product from the App Store, and merchandise it using its promotional image and a custom placeholder icon. ### Parameters #### Path Parameters * **productID** (Product.ID) - Required - The product identifier to load from the App Store. * **icon** ( (ProductIconPhase) -> Icon ) - Required - A closure that receives a `ProductIconPhase` as an input, which indicates the state of the loading operation of the product’s promotional image, and returns the view to display for the specified phase. * **placeholderIcon** ( () -> PlaceholderIcon ) - Required - A closure that returns an icon to display until the system finishes loading the product from the App Store. ### Discussion The product view shows the `placeholderIcon` until the system finishes loading the product. After the product finishes loading, the view asynchronously loads and displays the product’s promotional image. Use the `ProductIconPhase` to monitor the current loading state of the product’s promotional image. If the product is unavailable, the view displays the `placeholderIcon` as a fallback. The `ProductIconPhase` value indicates whether the promotional image is loading, unavailable, or whether it succeeded or failed to load. Use the phase to decide what to draw. While the image’s loading operation is in the `ProductIconPhase.loading` phase, consider displaying the same view that you provide in the `placeholderIcon` closure. For more information, see `ProductIconPhase`. ``` -------------------------------- ### Load Cloud Service Setup View (Swift) Source: https://developer.apple.com/documentation/storekit/skarcadeservice A function to load the setup view for cloud services, specifically for offering Apple Music subscriptions. It accepts options to configure the setup and uses a completion handler to report success or failure. ```swift func load(options: [SKCloudServiceSetupOptionsKey : Any], completionHandler: ((Bool, (any Error)?) -> Void)?) ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/storekit/subscriptionstoreview/init%28subscriptions%3Amarketingcontent%3A%29 Creates a view that displays a collection of subscription options, and merchandises them with custom marketing content. ```APIDOC ## init(subscriptions:marketingContent:) ### Description Creates a view that displays a collection of subscription options, and merchandises them with custom marketing content. ### Parameters `subscriptions` A collection of auto-renewable subscription `Product` instances to merchandise. The auto-renewable subscriptions need to belong to the same subscription group. `marketingContent` A view that contains marketing content to display above the store controls. ``` -------------------------------- ### Get Offer Payment Mode String Representation Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/renewalinfo/offerpaymentmodestringrepresentation Access the `offerPaymentModeStringRepresentation` to get the string representation of the payment mode. This property is deprecated and should not be used in new code. ```swift @backDeployed(before: iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0) var offerPaymentModeStringRepresentation: String? { get } ``` -------------------------------- ### Initializer: init(configuration:) Source: https://developer.apple.com/documentation/storekit/skoverlay/init%28configuration%3A%29 Creates an overlay instance used to recommend another app on the App Store. ```APIDOC ## init(configuration:) ### Description Creates an overlay you use to recommend another app on the App Store. This initializer supports iOS 14.0+, iPadOS 14.0+, Mac Catalyst 14.0+, and visionOS 1.0+. ### Method Initializer ### Endpoint SKOverlay.init(configuration: SKOverlay.Configuration) ### Parameters #### Path Parameters - **configuration** (SKOverlay.Configuration) - Required - The object that represents the overlay’s attributes, such as its position on the screen. Use `SKOverlay.AppConfiguration` for standard apps or `SKOverlay.AppClipConfiguration` for App Clips. ### Request Example ```swift let config = SKOverlay.AppConfiguration(appIdentifier: "123456789", position: .bottom) let overlay = SKOverlay(configuration: config) ``` ### Response #### Success Response - **instance** (SKOverlay) - Returns an initialized SKOverlay object ready to be presented. ``` -------------------------------- ### Handling Product Icon Loading Phases Source: https://developer.apple.com/documentation/storekit/producticonphase Use this pattern to display different views based on the loading phase of a product's promotional image. This example shows how to render a placeholder, an error view, a default icon, or the successfully loaded image. ```swift StoreView(products: [ product1, product2, // Additional products, as needed. ]) { product, phase in switch phase { case .loading: MyPlaceholder() case .failure(let error): MyErrorView(error) case .unavailable: MyDefaultIcon() case .success(let promotedIcon): promotedIcon } } ``` -------------------------------- ### Get all subscription statuses Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/status-swift.struct/all Use the `all` static property to get an `AsyncStream` that emits tuples containing a `groupID` and an array of `Product.SubscriptionInfo.Status` objects. This stream provides ongoing updates about subscription statuses. ```swift static var all: AsyncStream<(groupID: String, statuses: [Product.SubscriptionInfo.Status])> { get } ``` -------------------------------- ### Initialize StoreView with Preloaded Products Source: https://developer.apple.com/documentation/storekit/storeview Create a StoreView that displays a collection of products that have already been loaded. Optionally, specify if promotional icons should be preferred. ```swift init(products: some Collection, prefersPromotionalIcon: Bool) ``` -------------------------------- ### Initialize StoreView with Product IDs, Custom Icon, and Placeholder Source: https://developer.apple.com/documentation/storekit/storeview Create a StoreView that loads products from the App Store using identifiers, uses a custom view for each product's icon, and a custom placeholder icon. ```swift init(ids: some Collection, prefersPromotionalIcon: Bool, icon: (Product) -> Icon, placeholderIcon: () -> PlaceholderIcon) ``` -------------------------------- ### StoreKitPurchaseAPI init() Source: https://developer.apple.com/documentation/storekittest/storekitpurchaseapi/init%28%29 Initializes a new instance of the StoreKitPurchaseAPI. ```APIDOC ## init() ### Description Initializes a new instance of the StoreKitPurchaseAPI. ### Availability - iOS 17.0+ - iPadOS 17.0+ - Mac Catalyst 17.0+ - macOS 14.0+ - tvOS 17.0+ - visionOS 1.0+ - watchOS 10.0+ ### Syntax ```swift init() ``` ``` -------------------------------- ### Loading Cloud Service Setup View (Swift) Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupoptionskey Loads the cloud service setup view with specified options and a completion handler. This function is deprecated and may be removed in future versions. ```swift func load(options: [SKCloudServiceSetupOptionsKey : Any], completionHandler: ((Bool, (any Error)?) -> Void)?) ``` -------------------------------- ### init(subscriptions:content:) Source: https://developer.apple.com/documentation/storekit/subscriptionstoreview/init%28subscriptions%3Acontent%3A%29 Initializes a `SubscriptionStoreView` with a collection of `Product` objects and a content closure. The content closure is responsible for building the view's content, which must conform to `StoreContent`. ```APIDOC ## Initializer: init(subscriptions:content:) ### Description Initializes a `SubscriptionStoreView` with a collection of `Product` objects and a content closure. The content closure is responsible for building the view's content, which must conform to `StoreContent`. ### Signature ```swift nonisolated init( subscriptions: some Collection, @StoreContentBuilder content: () -> C ) where Content == SubscriptionStoreContentView, C : StoreContent ``` ### Parameters * `subscriptions`: A collection of `Product` objects to display. * `content`: A closure that returns the content view for the subscription store. The content must conform to `StoreContent`. ### Availability iOS 18.0+, iPadOS 18.0+, Mac Catalyst 18.0+, macOS 15.0+, tvOS 18.0+, visionOS 2.0+, watchOS 11.0+ ### See Also * `init(groupID: String, visibleRelationships: Product.SubscriptionRelationship, content: () -> C)` * `init(productIDs: some Collection, content: () -> C) ``` -------------------------------- ### init(productIDs:marketingContent:) Source: https://developer.apple.com/documentation/storekit/subscriptionstoreview/init%28productids%3Amarketingcontent%3A%29 Creates a view that loads a collection of subscriptions from the App Store, and merchandises them with custom marketing content. ```APIDOC ## init(productIDs:marketingContent:) ### Description Creates a view that loads a collection of subscriptions from the App Store, and merchandises them with custom marketing content. ### Parameters #### Parameters - **productIDs** (some Collection) - The product identifiers to load from the App Store. - **marketingContent** (() -> Content) - The view that contains marketing content to display above the store controls. ``` -------------------------------- ### Cloud Service Setup View Controller Dismissal Notification Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupviewcontrollerdelegate Implements the cloudServiceSetupViewControllerDidDismiss method to receive notification when the cloud service setup view controller is dismissed. This method is part of the SKCloudServiceSetupViewControllerDelegate protocol. ```swift func cloudServiceSetupViewControllerDidDismiss(SKCloudServiceSetupViewController) ``` -------------------------------- ### Initialize StoreView with Preloaded Products and Custom Icon Source: https://developer.apple.com/documentation/storekit/storeview Create a StoreView that displays a collection of preloaded products, using a custom view for each product's icon. ```swift init(products: some Collection, prefersPromotionalIcon: Bool, icon: (Product) -> Icon) ``` -------------------------------- ### SKCloudServiceSetupOptionsKey: Specifying Setup Actions (Swift) Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupoptionskey Defines keys used to specify the action for a cloud service setup entry point. These keys help determine the user's interaction with the service. ```swift struct SKCloudServiceSetupOptionsKey static let action: SKCloudServiceSetupOptionsKey ``` -------------------------------- ### init(_:content:marketingContent:) Source: https://developer.apple.com/documentation/storekit/subscriptionoptiongroup/init%28_%3Acontent%3Amarketingcontent%3A%29-550q0 Initializes a `SubscriptionOptionGroup` with a label, content, and optional marketing content. This initializer is available across multiple Apple platforms starting from specific OS versions. ```APIDOC ## Initializer ### init(_:content:marketingContent:) StoreKitSwiftUIiOS 18.0+iPadOS 18.0+Mac Catalyst 18.0+macOS 15.0+tvOS 18.0+visionOS 2.0+watchOS 11.0+ ```swift @MainActor @preconcurrency init( _ label: some StringProtocol, @StoreContentBuilder content: () -> Content, @ViewBuilder marketingContent: () -> MarketingContent ) ``` Available when `Content` conforms to `StoreContent`, `Label` is `Text`, and `MarketingContent` conforms to `View`. ``` -------------------------------- ### init(ids:icon:placeholderIcon:) Source: https://developer.apple.com/documentation/storekit/storeview/init%28ids%3Aicon%3Aplaceholdericon%3A%29 Creates a view to load a collection of products from the App Store using product identifiers, and merchandise them using their promotional images and a custom placeholder icon. ```APIDOC ## init(ids:icon:placeholderIcon:) ### Description Creates a view to load a collection of products from the App Store using product identifiers, and merchandise them using their promotional images and a custom placeholder icon. ### Parameters `productIDs` (some Collection) - Required - The product identifiers to load from the App Store. `icon` (@ViewBuilder @escaping (Product, ProductIconPhase) -> Icon) - Required - A closure that receives a `Product` and a `ProductIconPhase` as input. The `ProductIconPhase` indicates the state of the loading operation of the product’s promotional image. The closure returns the view to display for the given product and phase value. `placeholderIcon` (@ViewBuilder () -> PlaceholderIcon) - Required - A closure that returns the view that the store view uses while the products are loading. The store view uses the same placeholder image for all the products. ### Discussion The store view shows the custom `placeholderIcon` until all products finish loading. After the products finish loading, the view asynchronously loads and displays each product’s promotional image. Use the `ProductIconPhase` to monitor the current loading state of a product’s promotional image, and provide a view for each phase. Consider returning the view provided in the `placeholderIcon` closure for during the `ProductIconPhase.loading` phase. If a product is unavailable, the store view uses the view that the `placeholderIcon` closure provides as a fallback. ``` -------------------------------- ### SKAdNetwork 3 postback JSON examples Source: https://developer.apple.com/documentation/storekit/combining-parameters-for-skadnetwork-3-postbacks Example JSON structures for winning and nonwinning SKAdNetwork 3 postbacks. These demonstrate the expected fields and data types received by ad networks. ```json { "version": "3.0", "ad-network-id": "example123.skadnetwork", "campaign-id": 42, "transaction-id": "6aafb7a5-0170-41b5-bbe4-fe71dedf1e28", "app-id": 525463029, "attribution-signature": "MEYCIQD5eq3AUlamORiGovqFiHWI4RZT/PrM3VEiXUrsC+M51wIhAPMANZA9c07raZJ64gVaXhB9+9yZj/X6DcNxONdccQij", "redownload": true, "source-app-id": 1234567891, "fidelity-type": 1, "conversion-value": 20, "did-win": true } ``` ```json { "version": "3.0", "ad-network-id": "example123.skadnetwork", "campaign-id": 42, "transaction-id": "f9ac267a-a889-44ce-b5f7-0166d11461f0", "app-id": 525463029, "attribution-signature": "MEUCIQDDetUtkyc/MiQvVJ5I6HIO1E7l598572Wljot2Onzd4wIgVJLzVcyAV+TXksGNoa0DTMXEPgNPeHCmD4fw1ABXX0g=", "redownload": true, "fidelity-type": 1, "did-win": false } ``` -------------------------------- ### Load Cloud Service Setup View in Swift Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupviewcontroller/load%28options%3Acompletionhandler%3A%29 Loads the cloud service setup view controller with specified options. This method is deprecated and supports both completion handler callbacks and modern Swift concurrency. ```Swift func load( options: [SKCloudServiceSetupOptionsKey : Any] = [:], completionHandler: ((Bool, (any Error)?) -> Void)? = nil ) ``` ```Swift func load(options: [SKCloudServiceSetupOptionsKey : Any] = [:]) async throws -> Bool ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/storekit/automaticsubscriptionofferviewstyle/init%28%29 Initializes a new instance of AutomaticSubscriptionOfferViewStyle. This is the default initializer and does not take any parameters. ```APIDOC ## init() ### Description Initializes a new instance of `AutomaticSubscriptionOfferViewStyle`. This is the default initializer and does not take any parameters. ### Method `init()` ### Parameters This initializer does not take any parameters. ### Response An instance of `AutomaticSubscriptionOfferViewStyle`. ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/storekittest/storekitloadproductsapi/init%28%29 Initializes a new instance of the StoreKit object. This is the primary entry point for setting up StoreKit services. ```APIDOC ## init() ### Description Initializes a new StoreKit instance. This method must be called to prepare the framework for product requests and transaction handling. ### Method N/A (Initializer) ### Endpoint init() ### Availability - iOS 17.0+ - iPadOS 17.0+ - Mac Catalyst 17.0+ - macOS 14.0+ - tvOS 17.0+ - visionOS 1.0+ - watchOS 10.0+ ### Request Example ```swift let storeKit = StoreKit() ``` ### Response #### Success Response - **instance** (Object) - Returns an initialized StoreKit instance. ``` -------------------------------- ### Access recentSubscriptionStartDate Property in Swift Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/renewalinfo/recentsubscriptionstartdate This property returns the Date representing the start of a subscription series. It is available across multiple Apple platforms starting from iOS 15.0 and includes back-deployment attributes for older OS versions. ```swift @backDeployed(before: iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, macCatalyst 16.0) var recentSubscriptionStartDate: Date { get } ``` -------------------------------- ### Getting Subscription Relationship Source: https://developer.apple.com/documentation/storekit/product Provides information about the relationship of a subscription. ```APIDOC ## Getting subscription relationship `struct SubscriptionRelationship` Description: Information about the subscription relationship. ``` -------------------------------- ### Initiating a Purchase Source: https://developer.apple.com/documentation/storekit/productviewstyleconfiguration Call this method to start the purchase flow for the product. Ensure the product and its state are properly loaded before initiating a purchase. ```swift func purchase() ``` -------------------------------- ### init(_:prefersPromotionalIcon:icon:) Source: https://developer.apple.com/documentation/storekit/subscriptionofferview/init%28_%3Apreferspromotionalicon%3Aicon%3A%29 Initializes a new instance of SubscriptionOfferView. This view displays information about a subscription product, with options to customize the promotional icon display and provide a custom icon view. ```APIDOC ## Initializer: init(_:prefersPromotionalIcon:icon:) ### Description Initializes a `SubscriptionOfferView` with a specific subscription product. You can optionally specify whether to prefer a promotional icon and provide a custom view for the icon. ### Parameters - **subscription** (`Product`) - Required - The subscription product to display. - **prefersPromotionalIcon** (`Bool`) - Optional - A Boolean value that indicates whether to prefer displaying a promotional icon. Defaults to `false`. - **icon** (`() -> Icon`) - Required - A view builder that provides the custom view for the icon. The `Icon` type is generic and constrained by `PlaceholderIcon == EmptyView`. ``` -------------------------------- ### SKCloudServiceSetupMessageIdentifier Source: https://developer.apple.com/documentation/storekit/skcloudservicesetupmessageidentifier Identifiers for the available messages the setup view can present to the user. ```APIDOC ## SKCloudServiceSetupMessageIdentifier ### Description Identifiers for the available messages the setup view can present to the user. ### Structure ```swift struct SKCloudServiceSetupMessageIdentifier ``` ### Topics #### Initializing Identifiers `init(rawValue: String)` Initializes a cloud service setup message identifier based on the provided raw value. #### Message Identifiers `static let addMusic: SKCloudServiceSetupMessageIdentifier` Message identifier for adding music. Deprecated `static let connect: SKCloudServiceSetupMessageIdentifier` Message identifier for connecting. Deprecated `static let join: SKCloudServiceSetupMessageIdentifier` Message identifier for joining. Deprecated `static let playMusic: SKCloudServiceSetupMessageIdentifier` Message identifier for playing music. Deprecated ### Relationships #### Conforms To * `Equatable` * `Hashable` * `RawRepresentable` * `Sendable` * `SendableMetatype` ### See Also #### Indicating Setup Options `static let action: SKCloudServiceSetupOptionsKey` A key that specifies the action for a setup entry point. Deprecated `struct SKCloudServiceSetupAction` A string used to specify the type of setup action to offer for a cloud service. `static let iTunesItemIdentifier: SKCloudServiceSetupOptionsKey` A key that specifies the iTunes Store item that the user is trying to access through the service. Deprecated `static let affiliateToken: SKCloudServiceSetupOptionsKey` A key that specifies the iTunes Store affiliate token. Deprecated `static let campaignToken: SKCloudServiceSetupOptionsKey` A key that specifies the iTunes Store affiliate campaign token. Deprecated `static let messageIdentifier: SKCloudServiceSetupOptionsKey` A key that is used to select the main message presented to the user for this setup view. Deprecated ``` -------------------------------- ### Get Purchased Quantity Source: https://developer.apple.com/documentation/storekit/transaction/ownershiptype-swift.struct Returns the number of consumable products that were purchased. ```swift let purchasedQuantity: Int ``` -------------------------------- ### init(_:content:) Source: https://developer.apple.com/documentation/storekit/subscriptionoptiongroup/init%28_%3Acontent%3A%29-2nlpw Initializes a new instance of SubscriptionOptionGroup. This initializer takes a LocalizedStringKey for the label and a closure that provides the content for the group. The content must conform to the StoreContent protocol. ```APIDOC ## Initializer ### Signature ```swift @MainActor @preconcurrency init( _ label: LocalizedStringKey, @StoreContentBuilder content: () -> Content ) ``` ### Parameters * `label` (LocalizedStringKey) - A localized string key that provides the label for the subscription option group. * `content` (() -> Content) - A closure that returns the content for the subscription option group. `Content` must conform to `StoreContent`. ### Availability * iOS 18.0+ * iPadOS 18.0+ * Mac Catalyst 18.0+ * macOS 15.0+ * tvOS 18.0+ * visionOS 2.0+ * watchOS 11.0+ ### Requirements Available when `Content` conforms to `StoreContent`, `Label` is `Text`, and `MarketingContent` is `AutomaticSubscriptionStoreMarketingContent`. ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/storekit/automaticproductviewstyle/init%28%29 Creates an automatic product view style. This initializer is available for iOS 17.0+, iPadOS 17.0+, Mac Catalyst 17.0+, macOS 14.0+, tvOS 17.0+, visionOS 1.0+, and watchOS 10.0+. ```APIDOC ## Initializer ### init() Creates an automatic product view style. **Platforms:** * StoreKit * SwiftUI * iOS 17.0+ * iPadOS 17.0+ * Mac Catalyst 17.0+ * macOS 14.0+ * tvOS 17.0+ * visionOS 1.0+ * watchOS 10.0+ ```swift nonisolated init() ``` ``` -------------------------------- ### Getting Offers Source: https://developer.apple.com/documentation/storekit/transaction/offer-swift.struct Properties related to retrieving offers associated with a transaction. ```APIDOC ## Getting Offers - `offer`: `Transaction.Offer?` - A subscription offer that applies to the transaction at the next renewal period. - `eligibleWinBackOfferIDs`: `[String]` - An array of strings that represent identifiers of win-back offers that the customer is eligible to redeem, sorted with the best offers first. ``` -------------------------------- ### init(productIDs:content:) Source: https://developer.apple.com/documentation/storekit/subscriptionstoreview/init%28productids%3Acontent%3A%29 Initializes a `SubscriptionStoreView` using a collection of product identifiers and a content closure. The `content` closure builds the view's content, which must conform to `StoreContent`. ```APIDOC ## init(productIDs:content:) ### Description Initializes a `SubscriptionStoreView` with a collection of product identifiers and a content closure. ### Parameters - `productIDs` (some Collection) - A collection of product identifiers for the subscriptions. - `content` (() -> C) - A closure that returns the content for the view, where `C` conforms to `StoreContent` and `Content` is `SubscriptionStoreContentView`. ``` -------------------------------- ### Getting a placement Source: https://developer.apple.com/documentation/storekit/subscriptionstorecontrolplacement Provides the default placement for a subscription store control. ```APIDOC ## static var automatic: Self ### Description The default placement for a subscription store control. ### Required true ``` -------------------------------- ### Getting the Expiration Reason Source: https://developer.apple.com/documentation/storekit/product/subscriptioninfo/renewalinfo Retrieves the reason the auto-renewable subscription expired. ```swift let expirationReason: Product.SubscriptionInfo.RenewalInfo.ExpirationReason? ``` -------------------------------- ### Presenting App Store product pages with StoreKit Source: https://developer.apple.com/documentation/storekit/offering-media-for-sale-in-your-app Demonstrates how to configure parameters, initialize the SKStoreProductViewController, and load product information from the App Store. ```swift var parametersDictionary = [SKStoreProductParameterITunesItemIdentifier: product.productIdentifier] // Create a store product view controller. let store = SKStoreProductViewController() store.delegate = self /* Attempt to load the selected product from the App Store. Display the store product view controller if successful. Print an error message, otherwise. */ store.loadProduct(withParameters: parametersDictionary, completionBlock: {[unowned self] (result: Bool, error: Error?) in if result { self.present(store, animated: true, completion: { print("The store view controller was presented.") }) } else { if let error = error { print("Error: \(error.localizedDescription)") } }}) ``` -------------------------------- ### GET Message.Messages Source: https://developer.apple.com/documentation/storekit/message/messages-swift.struct Retrieves the asynchronous sequence of messages from the App Store. ```APIDOC ## GET Message.Messages ### Description Retrieves an asynchronous sequence of messages sent by the App Store to the application. This structure should not be initialized directly; use the static `messages` property. ### Method GET ### Endpoint Message.Messages ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```swift // Accessing the messages sequence for await message in Message.messages { print("Received message: \(message)") } ``` ### Response #### Success Response (200) - **message** (Message) - An individual message object sent from the App Store. #### Response Example { "message": { "reason": "subscription-offer", "id": "msg_12345" } } ``` -------------------------------- ### Creating the style Source: https://developer.apple.com/documentation/storekit/compactproductviewstyle Initializes a new instance of CompactProductViewStyle. ```APIDOC init() Initializes a new instance of CompactProductViewStyle. ``` -------------------------------- ### Initiate Product Purchase Source: https://developer.apple.com/documentation/StoreKit/Product Initiates a purchase for the product. Use the `options` parameter to specify purchase details like account tokens or promotional offers. The `confirmIn` parameter is used to present the confirmation sheet. ```swift func purchase(options: Set) async throws -> Product.PurchaseResult ``` ```swift func purchase(confirmIn: some UIScene, options: Set) async throws -> Product.PurchaseResult ``` ```swift func purchase(confirmIn: UIViewController, options: Set) async throws -> Product.PurchaseResult ``` ```swift func purchase(confirmIn: NSWindow, options: Set) async throws -> Product.PurchaseResult ``` -------------------------------- ### Getting Subscription Relationship Source: https://developer.apple.com/documentation/StoreKit/Product Provides information about the relationship of a product to subscriptions. ```APIDOC ## Getting subscription relationship ### Description Accesses details regarding the subscription relationship of a product. ### Related Structures - `Product.SubscriptionRelationship`: Structure containing subscription relationship information. ``` -------------------------------- ### POST /updatePostbackConversionValue Source: https://developer.apple.com/documentation/StoreKit/SKAdNetwork/CoarseConversionValue Updates the conversion values for an advertised app installation. ```APIDOC ## Method: updatePostbackConversionValue ### Description Updates the fine and coarse conversion values for an app installation. This method is used to report conversion progress to ad networks. ### Parameters - **fineValue** (Int) - Required - The fine conversion value to report. - **coarseValue** (SKAdNetwork.CoarseConversionValue) - Required - The coarse conversion value (low, medium, high). - **lockWindow** (Bool) - Optional - Whether to lock the conversion window. - **completionHandler** (Closure) - Optional - Callback to handle errors during the update. ### Response - **Success** (200) - The conversion value update was successfully queued. - **Error** (Error) - Returns an error if the update fails. ``` -------------------------------- ### init(products:prefersPromotionalIcon:) Source: https://developer.apple.com/documentation/storekit/storeview/init%28products%3Apreferspromotionalicon%3A%29 Creates a view to load and merchandise a collection of products from the App Store. By default, promotional images are not shown. Setting `prefersPromotionalIcon` to `true` enables the display of promotional images if available. ```APIDOC ## init(products:prefersPromotionalIcon:) ### Description Creates a view to load and merchandise a collection of products from the App Store. ### Parameters #### Parameters - **products** (some Collection) - The products to merchandise. - **prefersPromotionalIcon** (Bool) - A Boolean value that indicates whether to use promotional images from the App Store, if they’re available. Defaults to `false`. ### Discussion By default, the store view doesn’t show promotional images. If you set `prefersPromotionalIcon` to `true`, the store view uses each product’s promotional image as its icon. ``` -------------------------------- ### StoreKit SKError.Code Error Code Examples Source: https://developer.apple.com/documentation/storekit/skerror/invalidofferidentifier This Swift code snippet provides examples of various error codes within the `SKError.Code` enum for StoreKit. These codes help identify specific issues related to payments, store products, cloud services, and offer parameters. ```swift static var unknown: SKError.Code static var clientInvalid: SKError.Code static var paymentCancelled: SKError.Code static var paymentInvalid: SKError.Code static var paymentNotAllowed: SKError.Code static var storeProductNotAvailable: SKError.Code static var cloudServicePermissionDenied: SKError.Code static var cloudServiceNetworkConnectionFailed: SKError.Code static var cloudServiceRevoked: SKError.Code static var privacyAcknowledgementRequired: SKError.Code static var unauthorizedRequestData: SKError.Code static var invalidOfferPrice: SKError.Code static var invalidSignature: SKError.Code static var missingOfferParams: SKError.Code ```