Repository: bizz84/SwiftyStoreKit
Branch: master
Commit: 48d4d4c0b6a6
Files: 97
Total size: 548.1 KB
Directory structure:
gitextract_04t8es3j/
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ ├── feature_request.md
│ └── question.md
├── .gitignore
├── .swiftlint.yml
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dangerfile
├── Gemfile
├── LICENSE.md
├── Package.swift
├── README.md
├── Sources/
│ └── SwiftyStoreKit/
│ ├── AppleReceiptValidator.swift
│ ├── CompleteTransactionsController.swift
│ ├── InAppProductQueryRequest.swift
│ ├── InAppReceipt.swift
│ ├── InAppReceiptRefreshRequest.swift
│ ├── InAppReceiptVerificator.swift
│ ├── OS.swift
│ ├── PaymentQueueController.swift
│ ├── PaymentsController.swift
│ ├── Platforms/
│ │ ├── Info-iOS.plist
│ │ ├── Info-macOS.plist
│ │ ├── Info-tvOS.plist
│ │ ├── Info-watchOS.plist
│ │ ├── SwiftyStoreKit-iOS.h
│ │ ├── SwiftyStoreKit-macOS.h
│ │ ├── SwiftyStoreKit-tvOS.h
│ │ └── SwiftyStoreKit-watchOS.h
│ ├── ProductsInfoController.swift
│ ├── RestorePurchasesController.swift
│ ├── SKProduct+LocalizedPrice.swift
│ ├── SKProductDiscount+LocalizedPrice.swift
│ ├── SwiftyStoreKit+Types.swift
│ └── SwiftyStoreKit.swift
├── SwiftyStoreKit-iOS-Demo/
│ ├── AppDelegate.swift
│ ├── Assets.xcassets/
│ │ ├── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Background.imageset/
│ │ │ └── Contents.json
│ │ └── Contents.json
│ ├── Base.lproj/
│ │ ├── LaunchScreen.storyboard
│ │ └── Main.storyboard
│ ├── Info.plist
│ ├── NetworkActivityIndicatorManager.swift
│ └── ViewController.swift
├── SwiftyStoreKit-macOS-Demo/
│ ├── AppDelegate.swift
│ ├── Assets.xcassets/
│ │ ├── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ └── Contents.json
│ ├── Base.lproj/
│ │ └── Main.storyboard
│ ├── Info.plist
│ └── ViewController.swift
├── SwiftyStoreKit-tvOS-Demo/
│ ├── Assets.xcassets/
│ │ ├── App Icon & Top Shelf Image.brandassets/
│ │ │ ├── App Icon - Large.imagestack/
│ │ │ │ ├── Back.imagestacklayer/
│ │ │ │ │ ├── Content.imageset/
│ │ │ │ │ │ └── Contents.json
│ │ │ │ │ └── Contents.json
│ │ │ │ ├── Contents.json
│ │ │ │ ├── Front.imagestacklayer/
│ │ │ │ │ ├── Content.imageset/
│ │ │ │ │ │ └── Contents.json
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Middle.imagestacklayer/
│ │ │ │ ├── Content.imageset/
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Contents.json
│ │ │ ├── App Icon - Small.imagestack/
│ │ │ │ ├── Back.imagestacklayer/
│ │ │ │ │ ├── Content.imageset/
│ │ │ │ │ │ └── Contents.json
│ │ │ │ │ └── Contents.json
│ │ │ │ ├── Contents.json
│ │ │ │ ├── Front.imagestacklayer/
│ │ │ │ │ ├── Content.imageset/
│ │ │ │ │ │ └── Contents.json
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Middle.imagestacklayer/
│ │ │ │ ├── Content.imageset/
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Contents.json
│ │ │ ├── Contents.json
│ │ │ ├── Top Shelf Image Wide.imageset/
│ │ │ │ └── Contents.json
│ │ │ └── Top Shelf Image.imageset/
│ │ │ └── Contents.json
│ │ ├── Contents.json
│ │ └── LaunchImage.launchimage/
│ │ └── Contents.json
│ ├── Base.lproj/
│ │ └── Main.storyboard
│ └── Info.plist
├── SwiftyStoreKit.podspec
├── SwiftyStoreKit.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/
│ └── xcschemes/
│ ├── SwiftyStoreKit-iOS-Demo.xcscheme
│ ├── SwiftyStoreKit-iOS.xcscheme
│ ├── SwiftyStoreKit-macOS-Demo.xcscheme
│ ├── SwiftyStoreKit-macOS.xcscheme
│ ├── SwiftyStoreKit-tvOS-Demo.xcscheme
│ ├── SwiftyStoreKit-tvOS.xcscheme
│ ├── SwiftyStoreKitTests.xcscheme
│ └── SwiftyStoreKit_watchOS.xcscheme
├── Tests/
│ └── SwiftyStoreKitTests/
│ ├── CompleteTransactionsControllerTests.swift
│ ├── InAppReceiptTests.swift
│ ├── InAppReceiptVerificatorTests.swift
│ ├── Info-Tests.plist
│ ├── PaymentQueueControllerTests.swift
│ ├── PaymentQueueSpy.swift
│ ├── PaymentTransactionObserverFake.swift
│ ├── PaymentsControllerTests.swift
│ ├── ProductsInfoControllerTests.swift
│ ├── RestorePurchasesControllerTests.swift
│ ├── TestPaymentTransaction.swift
│ └── TestProduct.swift
└── scripts/
├── build.sh
└── install_swiftlint.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'type: bug'
assignees: ''
---
## Bug Report
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Step one...
**Expected behavior**
A clear and concise description of what you expected to happen.
## Platform Information
- OS: [e.g. iOS 13.4, watchOS 6.2.1, tvOS 9.2.3, macOS 10.14.3, Catalyst 13.0]
- Purchase Type: [e.g. consumable, non-consumable, auto-renewable subscription, non-renewing subscription, discount]
- Environment: [e.g. sandbox, app review, production]
- SwiftyStoreKit version: [e.g. 0.16]
## Additional context
Add any other context about the problem here.
**Potentially Related Issues**
- Issue #___
**Screenshots**
If applicable, add screenshots to help explain your problem.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'type: enhancement'
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/ISSUE_TEMPLATE/question.md
================================================
---
name: Question
about: General questions about SwiftyStoreKit
title: ''
labels: 'type: question'
assignees: ''
---
## Question
Please explain your question in detail here.
================================================
FILE: .gitignore
================================================
# Xcode
.DS_Store
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
*.xcworkspace
!default.xcworkspace
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
xcodebuild.log
# Pods - for those of you who use CocoaPods
Pods
# emacs
*~
# Swift Package Manager
.build/
# Carthage
Carthage/Build
================================================
FILE: .swiftlint.yml
================================================
# included:
# - Sources
# rule identifiers to exclude from running
disabled_rules:
- line_length
- identifier_name
- trailing_whitespace
# configurable rules can be customized from this configuration file
line_length: 250
================================================
FILE: .travis.yml
================================================
language: objective-c
osx_image: xcode11.5
before_install:
- gem install xcpretty
# - rvm get stable
install:
- ./scripts/install_swiftlint.sh
- bundle install --path vendor/bundle
script:
- swiftlint
- ./scripts/build.sh
- bundle exec danger --verbose
================================================
FILE: CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
* Make `ProductsInfoController`'s `retrieveProductsInfo` thread safe ([#405]https://github.com/bizz84/SwiftyStoreKit/pull/495), related issues: [#344](https://github.com/bizz84/SwiftyStoreKit/issues/344) and [#468](https://github.com/bizz84/SwiftyStoreKit/issues/468)
## [0.15.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.15.0) Update project to Swift 5, Xcode 10.2
* Update project to Swift 5 ([#457](https://github.com/bizz84/SwiftyStoreKit/pull/457)), related issue: [#456](https://github.com/bizz84/SwiftyStoreKit/issues/456)
* Add basic SwiftPM manifest file ([#460](https://github.com/bizz84/SwiftyStoreKit/pull/460))
## [0.14.2](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.14.2) Remove `canMakePayments` check on purchase method
* Remove `canMakePayments` check on purchase method ([#434](https://github.com/bizz84/SwiftyStoreKit/pull/434))
## [0.14.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.14.1) Add missing `else` condition in `SwiftyStoreKit.purchaseProduct`
* Add missing `else` condition in `SwiftyStoreKit.purchaseProduct` ([#426](https://github.com/bizz84/SwiftyStoreKit/pull/426))
## [0.14.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.14.0) Add `isInIntroOfferPeriod` property, update project to Swift 4.2, Xcode 10
* Added new property `isInIntroOfferPeriod` to ReceiptItem ([#404](https://github.com/bizz84/SwiftyStoreKit/pull/404), [#409](https://github.com/bizz84/SwiftyStoreKit/pull/409))
* Add Swift 4.2 Support ([#408](https://github.com/bizz84/SwiftyStoreKit/pull/408)), update project to Xcode 10 ([#410](https://github.com/bizz84/SwiftyStoreKit/pull/410))
## [0.13.3](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.13.3) Fix macOS compile error on Xcode 10.0 beta (10L176w)
* Fix macOS compile error on Xcode 10.0 beta (10L176w) ([#381](https://github.com/bizz84/SwiftyStoreKit/pull/381), see [#380](https://github.com/bizz84/SwiftyStoreKit/issues/380))
## [0.13.2](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.13.2) Swift 4.1 / Xcode 9.3 Support
* Swift 4.1 / Xcode 9.3 Support ([#360](https://github.com/bizz84/SwiftyStoreKit/pull/360))
## [0.13.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.13.1) Add support Ask To Buy
* Add a wrapper for `simulatesAskToBuyInSandbox` ([#349](https://github.com/bizz84/SwiftyStoreKit/pull/349))
## [0.13.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.13.0) Add support for downloading content hosted with Apple
* Add support for downloading content hosted with Apple ([#343](https://github.com/bizz84/SwiftyStoreKit/pull/343), related issue: [#128](https://github.com/bizz84/SwiftyStoreKit/issues/128))
* Add table of contents to README ([#346](https://github.com/bizz84/SwiftyStoreKit/pull/346))
## [0.12.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.12.1) Assert that `completeTransactions` was called when the app launches.
* Assert that `completeTransactions()` was called when the app launches ([#337](https://github.com/bizz84/SwiftyStoreKit/pull/337), related issue: [#287](https://github.com/bizz84/SwiftyStoreKit/issues/287))
## [0.12.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.12.0) Add `verifySubscriptions` method for subscription groups
* Add `verifySubscriptions` method to check all subscriptions in a group at once ([#333](https://github.com/bizz84/SwiftyStoreKit/pull/333), related issue: [#194](https://github.com/bizz84/SwiftyStoreKit/issues/194))
* Rename `verifySubscription(type:productId:inReceipt:validUntil:)` to `verifySubscription(ofType:productId:inReceipt:validUntil:)` ([#333](https://github.com/bizz84/SwiftyStoreKit/pull/333))
* Add video tutorials section in README ([#328](https://github.com/bizz84/SwiftyStoreKit/pull/328), [#330](https://github.com/bizz84/SwiftyStoreKit/pull/330), see [#326](https://github.com/bizz84/SwiftyStoreKit/issues/326))
* Update iOS Demo App ([#327](https://github.com/bizz84/SwiftyStoreKit/pull/327), see [#147](https://github.com/bizz84/SwiftyStoreKit/issues/147))
## [0.11.3](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.11.3) `completeTransactions` finishes failed transactions if `atomically: false`
* Add `originalTransaction` to `PurchaseDetails` ([#323](https://github.com/bizz84/SwiftyStoreKit/pull/323), fix for [#302](https://github.com/bizz84/SwiftyStoreKit/issues/302))
* Bug fix: `completeTransactions` finishes failed transactions if `atomically: false` ([#322](https://github.com/bizz84/SwiftyStoreKit/pull/322), related issues: [#307](https://github.com/bizz84/SwiftyStoreKit/issues/307), [#288](https://github.com/bizz84/SwiftyStoreKit/issues/288))
## [0.11.2](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.11.2) Remove `SKProduct.localizedIntroductoryPrice`
* Remove `localizedIntroductoryPrice` ([#320](https://github.com/bizz84/SwiftyStoreKit/pull/320), see [#319](https://github.com/bizz84/SwiftyStoreKit/issues/319), [#318](https://github.com/bizz84/SwiftyStoreKit/pull/318), [#315](https://github.com/bizz84/SwiftyStoreKit/pull/315))
## [0.11.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.11.1) Add `PaymentTransaction.transactionDate` and `SKProduct.localizedIntroductoryPrice`
* Add `transactionDate` to `PaymentTransaction` ([#316](https://github.com/bizz84/SwiftyStoreKit/pull/316), see [#312](https://github.com/bizz84/SwiftyStoreKit/issues/312)).
* Add `localizedIntroductoryPrice` to `SKProduct` ([#318](https://github.com/bizz84/SwiftyStoreKit/pull/318)).
## [0.11.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.11.0) Add `fetchReceipt` method + update `verifyReceipt` and `ReceiptValidator` protocol
* Add `fetchReceipt` method. Update `verifyReceipt` to use it ([#278](https://github.com/bizz84/SwiftyStoreKit/pull/278), related issues: [#272](https://github.com/bizz84/SwiftyStoreKit/issues/272), [#223](https://github.com/bizz84/SwiftyStoreKit/issues/223)).
* Update `fetchReceipt` and `ReceiptValidator` to use receipt as `Data` rather than `String`. This is consistent with `localReceiptData` ([#284](https://github.com/bizz84/SwiftyStoreKit/pull/284), see [#272](https://github.com/bizz84/SwiftyStoreKit/issues/272)).
* Remove `password` from `ReceiptValidator` protocol as this is specific to `AppleReceiptValidator` ([#281](https://github.com/bizz84/SwiftyStoreKit/pull/281/), see [#263](https://github.com/bizz84/SwiftyStoreKit/issues/263)). **Note**: This is an API breaking change.
* Unwrap `receipt["receipt"]?["in_app"]` in two steps (addresses casting problems) ([#283](https://github.com/bizz84/SwiftyStoreKit/pull/283), related issue [#256](https://github.com/bizz84/SwiftyStoreKit/issues/256)).
## [0.10.8](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.8) Update to swiftlint 0.22.0
* Update to swiftlint 0.22.0 ([#270](https://github.com/bizz84/SwiftyStoreKit/pull/270), fix for [#273](https://github.com/bizz84/SwiftyStoreKit/issues/273))
## [0.10.7](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.7) Fix for concurrent `retrieveProductsInfo` calls
* `ProductsInfoController`: Keep track of multiple completion blocks for the same request ([#259](https://github.com/bizz84/SwiftyStoreKit/pull/259), fix for [#250](https://github.com/bizz84/SwiftyStoreKit/issues/250))
## [0.10.6](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.6) Add support for shouldAddStorePayment
* Add support for the new `SKPaymentTransactionObserver.shouldAddStorePayment` method in iOS 11 ([#257](https://github.com/bizz84/SwiftyStoreKit/pull/257), related issue: [#240](https://github.com/bizz84/SwiftyStoreKit/issues/240))
* Update swiftlint to version 0.21.0 ([#258](https://github.com/bizz84/SwiftyStoreKit/pull/258))
## [0.10.5](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.5) Filter out transactions in purchasing state
* Filter out all transactions with `state == .purchasing` early in purchase flows (related to [#169](https://github.com/bizz84/SwiftyStoreKit/issues/169), [#188](https://github.com/bizz84/SwiftyStoreKit/pull/188), [#179](https://github.com/bizz84/SwiftyStoreKit/issues/179))
* Sample app: print localized description when a purchase fails with `.unknown` error
## [0.10.4](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.4) Documentation and updates for Xcode 9
* Update to Xcode 9 recommended project settings ([#247](https://github.com/bizz84/SwiftyStoreKit/pull/247))
* Update build script iOS version to 10.3.1 ([#245](https://github.com/bizz84/SwiftyStoreKit/pull/245))
* Update notes about Xcode 9, Swift 4 support to README
## [0.10.3](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.3) Add `forceRefresh` option to `verifyReceipt`
* Add `forceRefresh` option to `verifyReceipt` ([#224](https://github.com/bizz84/SwiftyStoreKit/pull/224), fix for [#223](https://github.com/bizz84/SwiftyStoreKit/issues/223))
## [0.10.2](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.2) Remove SKProduct caching
* Remove SKProduct caching ([#222](https://github.com/bizz84/SwiftyStoreKit/pull/222), related issue: [#212](https://github.com/bizz84/SwiftyStoreKit/issues/212))
* Adds new purchase product method based on SKProduct
## [0.10.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.1) Danger, xcpretty integration
* Adds Danger for better Pull Request etiquette ([#215](https://github.com/bizz84/SwiftyStoreKit/pull/215)).
* Adds xcpretty to improve build logs ([#217](https://github.com/bizz84/SwiftyStoreKit/pull/217))
* Update SwiftLint to 0.18.1 ([#218](https://github.com/bizz84/SwiftyStoreKit/pull/218))
## [0.10.0](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.10.0) `verifyReceipt` now automatically refreshes the receipt if needed
#### API removed: `refreshReceipt`
This release simplifies the receipt verification flows by removing the `refreshReceipt` method from the public API.
Now clients only need to call `verifyReceipt` and the receipt is refreshed internally if needed.
Addressed in [#213](https://github.com/bizz84/SwiftyStoreKit/pull/213), related issue: [#42](https://github.com/bizz84/SwiftyStoreKit/issues/42).
The documentation in the README and various methods has also been considerably improved.
## [0.9.3](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.9.3) Dispatch callbacks on main thread on macOS
This is a minor release to ensure callbacks are dispatched on the main thread on macOS.
PR [#214](https://github.com/bizz84/SwiftyStoreKit/pull/214), fix for [#211](https://github.com/bizz84/SwiftyStoreKit/issues/211).
## [0.9.2](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.9.2) Fix for failing receipt verification due to missing optional field
This is a critical fix for [#208](https://github.com/bizz84/SwiftyStoreKit/issues/208).
If you're using release 0.9.0, please update.
## [0.9.1](https://github.com/bizz84/SwiftyStoreKit/releases/tag/0.9.1) Expose SKProduct in PurchaseDetails type returned by PurchaseResult
This is a minor release which includes a fix for [#185](https://github.com/bizz84/SwiftyStoreKit/issues/185) (addressed in [#206](https://github.com/bizz84/SwiftyStoreKit/pull/206)). Summary:
When a purchase succeeds, it is desirable to get access to the purchased `SKProduct` in the completion block, so that it's possible to query the `price` and other properties.
With this change, this is now possible:
```swift
SwiftyStoreKit.purchaseProduct("productId", atomically: true) { result in
if case .success(let purchase) = result {
// Deliver content from server, then:
if purchase.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("Purchased product with price: \(purchase.product.price)")
}
}
```
## [0.9.0](https://github.com/bizz84/SwiftyStoreKit/releases/edit/0.9.0) Verify Subscription improvements + added quantity and originalTransaction to Payment
**NOTE** This release introduces some API breaking changes (see [#202](https://github.com/bizz84/SwiftyStoreKit/pull/202)). Change-set:
### [#198](https://github.com/bizz84/SwiftyStoreKit/pull/198): Subscription verification unit tests
### [#199](https://github.com/bizz84/SwiftyStoreKit/pull/199) (fixes [#192](https://github.com/bizz84/SwiftyStoreKit/issues/192), [#190](https://github.com/bizz84/SwiftyStoreKit/issues/190) and [#65](https://github.com/bizz84/SwiftyStoreKit/issues/65)): Add `ReceiptItem` to `VerifyPurchaseResult`, `VerifySubscriptionResult`
This change introduces a new strong-typed `ReceiptItem` struct:
```swift
public struct ReceiptItem {
// The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the SKPayment object stored in the transaction’s payment property.
public let productId: String
// The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property.
public let quantity: Int
// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s transactionIdentifier property.
public let transactionId: String
// For a transaction that restores a previous transaction, the transaction identifier of the original transaction. Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s transactionIdentifier property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
public let originalTransactionId: String
// The date and time that the item was purchased. This value corresponds to the transaction’s transactionDate property.
public let purchaseDate: Date
// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s transactionDate property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
public let originalPurchaseDate: Date
// The primary key for identifying subscription purchases.
public let webOrderLineItemId: String
// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is only present for auto-renewable subscription receipts.
public let subscriptionExpirationDate: Date?
// For a transaction that was canceled by Apple customer support, the time and date of the cancellation. Treat a canceled receipt the same as if no purchase had ever been made.
public let cancellationDate: Date?
public let isTrialPeriod: Bool
}
```
This is parsed from the receipt and returned as part of the `verifySubscription` and `verifyPurchase` methods:
```swift
// Result for Consumable and NonConsumable
public enum VerifyPurchaseResult {
case purchased(item: ReceiptItem)
case notPurchased
}
// Verify subscription result
public enum VerifySubscriptionResult {
case purchased(expiryDate: Date, items: [ReceiptItem])
case expired(expiryDate: Date, items: [ReceiptItem])
case notPurchased
}
```
Note that when one or more subscriptions are found for a given product id, they are returned as a `ReceiptItem` array ordered by `expiryDate`, with the first one being the newest.
This is useful to get all the valid date ranges for a given subscription.
### [#202](https://github.com/bizz84/SwiftyStoreKit/pull/202) (fix for [#200](https://github.com/bizz84/SwiftyStoreKit/issues/200)): It's now possible to specify the quantity when making a purchase. Quantity is also accessible in the callback.
#### This is an API breaking change. `Product` has been renamed to `Purchase`:
```swift
public struct Purchase {
public let productId: String
public let quantity: Int
public let transaction: PaymentTransaction
public let needsFinishTransaction: Bool
}
```
#### `PurchaseResult`
```swift
public enum PurchaseResult {
//case success(product: Product) // old
case success(purchase: Purchase) // new
case error(error: SKError)
}
```
#### `RestoreResults`
```swift
public struct RestoreResults {
//public let restoredProducts: [Product] // old
//public let restoreFailedProducts: [(SKError, String?)] // old
public let restoredPurchases: [Purchase] // new
public let restoreFailedPurchases: [(SKError, String?)] // new
}
```
### [#203](https://github.com/bizz84/SwiftyStoreKit/pull/203) (fix for [#193](https://github.com/bizz84/SwiftyStoreKit/issues/193)): Add `originalTransaction` from `SKPaymentTransaction.original` to `Payment` type
## TODO: Older releases
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at hello@samspencer.art. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to SwiftyStoreKit
### All contributions to SwiftyStoreKit are welcome. 😎
This project is becoming widely adopted and its growth is now limited by the time the main maintainer can allocate.
Going forward, the aim is to **transfer some of the maintainance and development effort to the community**.
If you want to help developing SwiftyStoreKit, please look for issues marked with a blue **contributions welcome** label. See [this issue](https://github.com/bizz84/SwiftyStoreKit/issues/192) for an example.
The maintainer will use this label initially for simple tasks that are appropriate for beginners and first time contributors.
As the project and its community grows:
* intermediate and advanced tasks will be opened up to contributors
* most experienced contributors will be able to gain **admin** rights to review and merge pull requests
**Note**: While the maintainer(s) try to regularly keep the project alive and healthy, issues and pull requests are not always reviewed in a timely manner. 🕰
## Scope
SwiftyStoreKit aims to be a lightweight wrapper on top of [StoreKit](https://developer.apple.com/reference/storekit).
While SwiftyStoreKit offers access to the [local receipt data](https://developer.apple.com/reference/foundation/bundle/1407276-appstorereceipturl), it is a non-goal to add support for persisting IAP data locally. It is up to clients to do this with a storage solution of choice (i.e. NSUserDefaults, CoreData, Keychain).
**Swift Version**: SwiftyStoreKit includes [Swift 2.3](https://github.com/bizz84/SwiftyStoreKit/tree/swift-2.3) and [Swift 2.2](https://github.com/bizz84/SwiftyStoreKit/tree/swift-2.2) branches. These legacy versions are no longer maintained and all active development happens on [master](https://github.com/bizz84/SwiftyStoreKit) and [develop](https://github.com/bizz84/SwiftyStoreKit/tree/develop), which support Swift 3.x and Swift 4.x.
**Objective-C**: Currently, SwiftyStoreKit cannot be used in Objective-C projects. The main limitation is that most classes and types in the library are Swift-only. See [related issue](https://github.com/bizz84/SwiftyStoreKit/issues/123).
## Pull requests
The project uses [gitflow](http://nvie.com/posts/a-successful-git-branching-model/) as a branching model.
In short:
* All pull requests for **new features** and **bug fixes** should be made into the `develop` branch.
* Pull requests for **hot fixes** can be done into both `master` and `develop`.
* The maintainer(s) will merge `develop` into `master` and create a release tag as new features are added.
* All releases [can be found here](https://github.com/bizz84/SwiftyStoreKit/releases).
## Open Features / Enhancement Requests
These are intermediate / advanced tasks that will hopefully be implemented in the future:
### Local Receipt validation
SwiftyStoreKit offers a reference implementation for [receipt validation with Apple](https://github.com/bizz84/SwiftyStoreKit/blob/master/SwiftyStoreKit/AppleReceiptValidator.swift).
This could be extended by implementing local receipt validation as recommended by Apple. See [related issue](https://github.com/bizz84/SwiftyStoreKit/issues/101).
### Support for content hosted by Apple for non-consumable products
See [related issue](https://github.com/bizz84/SwiftyStoreKit/issues/128).
### Increase unit test coverage
The payment flows are unit tested fairly extensively. Additional unit test coverage is welcome:
- [ ] Dependency injection for SwiftyStoreKit dependencies
- [ ] Unit tests on main [SwiftyStoreKit class](https://github.com/bizz84/SwiftyStoreKit/blob/master/SwiftyStoreKit/SwiftyStoreKit.swift).
- [ ] Unit tests for receipt verification code.
See [related issue](https://github.com/bizz84/SwiftyStoreKit/issues/38).
## Issues
If SwiftyStoreKit doesn't work as you expect, please review [any open issues](https://github.com/bizz84/SwiftyStoreKit/issues) before opening a new one.
================================================
FILE: Dangerfile
================================================
# Ensure there is a summary for a pull request
fail 'Please provide a summary in the Pull Request description' if github.pr_body.length < 5
# Warn about develop branch
warn("Please target PRs to `develop` branch") if github.branch_for_base != "develop"
# Sometimes it's a README fix, or something like that - which isn't relevant for
# including in a project's CHANGELOG for example
declared_trivial = github.pr_title.include? "#trivial"
# Make it more obvious that a PR is a work in progress and shouldn't be merged yet
warn("PR is classed as Work in Progress") if github.pr_title.include? "[WIP]"
# Warn no CHANGELOG
warn("No CHANGELOG changes made") if git.lines_of_code > 50 && !git.modified_files.include?("CHANGELOG.md") && !declared_trivial
# Warn when there is a big PR
warn("Big PR") if git.lines_of_code > 500
## Let's check if there are any changes in the project folder
has_app_changes = !git.modified_files.grep(/SwiftyStoreKit/).empty?
## Then, we should check if tests are updated
has_test_changes = !git.modified_files.grep(/SwiftyStoreKitTests/).empty?
## Finally, let's combine them and put extra condition
## for changed number of lines of code
if has_app_changes && !has_test_changes && git.lines_of_code > 20
fail("Tests were not updated", sticky: false)
end
================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'
gem 'danger'
================================================
FILE: LICENSE.md
================================================
Copyright (c) 2015-2016 Andrea Bizzotto bizz84@gmail.com
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 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in 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 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 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.
================================================
FILE: Package.swift
================================================
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "SwiftyStoreKit",
platforms: [.iOS("9.0"), .macOS("10.10"), .tvOS("9.0"), .watchOS("6.2")],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftyStoreKit",
targets: ["SwiftyStoreKit"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftyStoreKit",
dependencies: []),
.testTarget(
name: "SwiftyStoreKitTests",
dependencies: ["SwiftyStoreKit"])
]
)
================================================
FILE: README.md
================================================
[](http://mit-license.org)
[](https://developer.apple.com/resources/)
[](https://developer.apple.com/swift)
[](https://travis-ci.org/bizz84/SwiftyStoreKit)
[](https://github.com/bizz84/SwiftyStoreKit/issues)
[](https://join.slack.com/t/swiftystorekit/shared_invite/enQtODY3OTYxOTExMzE5LWVkNGY4MzcwY2VjNGM4MGU4NDFhMGE5YmUxMGM3ZTQ4NjVjNTRkNTJhNDAyMWZmY2M5OWE5MDE0ODc3OGJjMmM)
SwiftyStoreKit is a lightweight In App Purchases framework for iOS, tvOS, watchOS, macOS, and Mac Catalyst.
## Features
- Super easy-to-use block-based API
- Support for consumable and non-consumable in-app purchases
- Support for free, auto-renewable and non-renewing subscriptions
- Support for in-app purchases started in the App Store (iOS 11)
- Support for subscription discounts and offers
- Remote receipt verification
- Verify purchases, subscriptions, subscription groups
- Downloading content hosted with Apple
- iOS, tvOS, watchOS, macOS, and Catalyst compatible
## SwiftyStoreKit Alternatives
During WWDC21, Apple introduced [StoreKit 2](https://developer.apple.com/videos/play/wwdc2021/10114/), a brand new Swift API for in-app purchases and auto-renewable subscriptions.
While it would be highly desirable to support StoreKit 2 in this project, [little progress](https://github.com/bizz84/SwiftyStoreKit/issues/550) has been made over the last year and most issues [remain unanswered](https://github.com/bizz84/SwiftyStoreKit/issues).
Fortunately, there are some very good alternatives to SwiftyStoreKit, backed by real companies. By choosing their products, you'll make a safe choice and get much better support.
### RevenueCat
[RevenueCat](https://www.revenuecat.com/) is a great alternative to SwiftyStoreKit, offering great APIs, support, and much more at a very [reasonable price](https://www.revenuecat.com/pricing).
If you've been using SwiftyStoreKit and want to migrate to RevenueCat, this guide covers everything you need:
- [SwiftyStoreKit Migration](https://docs.revenuecat.com/docs/swiftystorekit)
Or if you're just getting started, consider skipping SwiftyStoreKit altogether and signing up for [RevenueCat](https://www.revenuecat.com/).
### Glassfy
[Glassfy](https://glassfy.io/) makes it easy to build, handle, and optimize in-app subscriptions. If you switch to Glassfy from SwiftyStoreKit, you'll get a 20% discount by using this [affiliate link](https://dashboard.glassfy.io/referral?code=SWIFTYSTOREKIT20).
- Glassfy [pricing page](https://glassfy.io/pricing.html) - 20% off
- Glassfy [migration guide](https://docs.glassfy.io/get-started/migrate-ssk) to support you with the migration
> Note from the author: if you sign up with the link above, I will receive an affiliate commission from Glassfy, at no cost to yourself. I only recommend products that I personally know and believe will help you.
### Apphud
[Apphud](https://apphud.com/) is more than just making a purchase and validating receipts. Apphud is all-in-one infrastructure for your app growth. [Sign up for free](https://app.apphud.com/sign_up) and try it out.
Or you can learn [how to migrate your app from SwiftyStoreKit to Apphud](https://docs.apphud.com/getting-started/migrate-from-swiftystorekit).
### Adapty
With Adapty you can set up subscriptions in just an hour following these [simple steps](https://docs.adapty.io/docs/quickstart) and instantly launch in-app purchases with the [Paywall Builder](https://adapty.io/paywall-builder/). Adapty not only gives you the tools to embed purchases but also helps your customers grow.
And the best part is that [it’s free for apps <$10k](https://adapty.io/pricing/).
## Contributions Wanted
SwiftyStoreKit makes it easy for an incredible number of developers to seemlessly integrate in-App Purchases. This project, however, is now **community-led**. We need help building out features and writing tests (see [issue #550](https://github.com/bizz84/SwiftyStoreKit/issues/550)).
### Maintainers Wanted
The author is no longer maintaining this project actively. If you'd like to become a maintainer, [join the Slack workspace](https://join.slack.com/t/swiftystorekit/shared_invite/enQtODY3OTYxOTExMzE5LWVkNGY4MzcwY2VjNGM4MGU4NDFhMGE5YmUxMGM3ZTQ4NjVjNTRkNTJhNDAyMWZmY2M5OWE5MDE0ODc3OGJjMmM) and enter the [#maintainers](https://app.slack.com/client/TL2JYQ458/CLG62K26A/details/) channel.
Going forward, SwiftyStoreKit should be made for the community, by the community.
More info here: [The Future of SwiftyStoreKit: Maintainers Wanted](https://medium.com/@biz84/the-future-of-swiftystorekit-maintainers-needed-f60d01572c91).
## Requirements
If you've shipped an app in the last five years, you're probably good to go. Some features (like discounts) are only available on new OS versions, but most features are available as far back as:
| iOS | watchOS | tvOS | macOS | Mac Catalyst |
| --- | ------- | ---- | ----- | ------------ |
| 8.0 | 6.2 | 9.0 | 10.10 | 13.0 |
## Installation
There are a number of ways to install SwiftyStoreKit for your project. Swift Package Manager, CocoaPods, and Carthage integrations are the preferred and recommended approaches.
Regardless, make sure to import the project wherever you may use it:
```swift
import SwiftyStoreKit
```
### Swift Package Manager
The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into Xcode and the Swift compiler. **This is the recommended installation method.** Updates to SwiftyStoreKit will always be available immediately to projects with SPM. SPM is also integrated directly with Xcode.
If you are using Xcode 11 or later:
1. Click `File`
2. `Swift Packages`
3. `Add Package Dependency...`
4. Specify the git URL for SwiftyStoreKit.
```swift
https://github.com/bizz84/SwiftyStoreKit.git
```
### Carthage
To integrate SwiftyStoreKit into your Xcode project using [Carthage](https://github.com/Carthage/Carthage), specify it in your Cartfile:
```ogdl
github "bizz84/SwiftyStoreKit"
```
**NOTE**: Please ensure that you have the [latest](https://github.com/Carthage/Carthage/releases) Carthage installed.
### CocoaPods
SwiftyStoreKit can be installed as a [CocoaPod](https://cocoapods.org/) and builds as a Swift framework. To install, include this in your Podfile.
```ruby
use_frameworks!
pod 'SwiftyStoreKit'
```
## Contributing
Got issues / pull requests / want to contribute? [Read here](CONTRIBUTING.md).
# Documentation
Full documentation is available on the [SwiftyStoreKit Wiki](https://github.com/bizz84/SwiftyStoreKit/wiki). As SwiftyStoreKit (and Apple's StoreKit) gains features, platforms, and implementation approaches, new information will be added to the Wiki. Essential documentation is available here in the README and should be enough to get you up and running.
## App startup
### Complete Transactions
Apple recommends to register a transaction observer [as soon as the app starts](https://developer.apple.com/library/ios/technotes/tn2387/_index.html):
> Adding your app's observer at launch ensures that it will persist during all launches of your app, thus allowing your app to receive all the payment queue notifications.
SwiftyStoreKit supports this by calling `completeTransactions()` when the app starts:
```swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// see notes below for the meaning of Atomic / Non-Atomic
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
// Unlock content
case .failed, .purchasing, .deferred:
break // do nothing
}
}
}
return true
}
```
If there are any pending transactions at this point, these will be reported by the completion block so that the app state and UI can be updated.
If there are no pending transactions, the completion block will **not** be called.
Note that `completeTransactions()` **should only be called once** in your code, in `application(:didFinishLaunchingWithOptions:)`.
## Purchases
### Retrieve products info
```swift
SwiftyStoreKit.retrieveProductsInfo(["com.musevisions.SwiftyStoreKit.Purchase1"]) { result in
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
print("Product: \(product.localizedDescription), price: \(priceString)")
}
else if let invalidProductId = result.invalidProductIDs.first {
print("Invalid product identifier: \(invalidProductId)")
}
else {
print("Error: \(result.error)")
}
}
```
### Purchase a product (given a product id)
* **Atomic**: to be used when the content is delivered immediately.
```swift
SwiftyStoreKit.purchaseProduct("com.musevisions.SwiftyStoreKit.Purchase1", quantity: 1, atomically: true) { result in
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
default: print((error as NSError).localizedDescription)
}
}
}
```
* **Non-Atomic**: to be used when the content is delivered by the server.
```swift
SwiftyStoreKit.purchaseProduct("com.musevisions.SwiftyStoreKit.Purchase1", quantity: 1, atomically: false) { result in
switch result {
case .success(let product):
// fetch content from your server, then:
if product.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(product.transaction)
}
print("Purchase Success: \(product.productId)")
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
default: print((error as NSError).localizedDescription)
}
}
}
```
### Additional Purchase Documentation
These additional topics are available on the Wiki:
- [Purchase a product (given a SKProduct)](https://github.com/bizz84/SwiftyStoreKit/wiki/Purchasing#purchase-a-product-given-a-skproduct)
- [Handle purchases started on the App Store (iOS 11)](https://github.com/bizz84/SwiftyStoreKit/wiki/App-Store-Purchases)
### Restore Previous Purchases
According to [Apple - Restoring Purchased Products](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/Restoring.html#//apple_ref/doc/uid/TP40008267-CH8-SW9):
> In most cases, all your app needs to do is refresh its receipt and deliver the products in its receipt. The refreshed receipt contains a record of the user’s purchases in this app, on this device or any other device.
>
> Restoring completed transactions creates a new transaction for every completed transaction the user made, essentially replaying history for your transaction queue observer.
See the **Receipt Verification** section below for how to restore previous purchases using the receipt.
This section shows how to restore completed transactions with the `restorePurchases` method instead. When successful, the method returns all non-consumable purchases, as well as all auto-renewable subscription purchases, **regardless of whether they are expired or not**.
* **Atomic**: to be used when the content is delivered immediately.
```swift
SwiftyStoreKit.restorePurchases(atomically: true) { results in
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
}
else if results.restoredPurchases.count > 0 {
print("Restore Success: \(results.restoredPurchases)")
}
else {
print("Nothing to Restore")
}
}
```
* **Non-Atomic**: to be used when the content is delivered by the server.
```swift
SwiftyStoreKit.restorePurchases(atomically: false) { results in
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
}
else if results.restoredPurchases.count > 0 {
for purchase in results.restoredPurchases {
// fetch content from your server, then:
if purchase.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
}
print("Restore Success: \(results.restoredPurchases)")
}
else {
print("Nothing to Restore")
}
}
```
#### What does atomic / non-atomic mean?
For more information about atomic vs. non-atomic restorations, [view the Wiki page here](https://github.com/bizz84/SwiftyStoreKit/wiki/Restoring#what-does-atomic--non-atomic-mean).
### Downloading content hosted with Apple
More information about downloading hosted content is [available on the Wiki](https://github.com/bizz84/SwiftyStoreKit/wiki/Downloading-Content).
To start downloads (this can be done in `purchaseProduct()`, `completeTransactions()` or `restorePurchases()`):
```swift
SwiftyStoreKit.purchaseProduct("com.musevisions.SwiftyStoreKit.Purchase1", quantity: 1, atomically: false) { result in
switch result {
case .success(let product):
let downloads = purchase.transaction.downloads
if !downloads.isEmpty {
SwiftyStoreKit.start(downloads)
}
case .error(let error):
print("\(error)")
}
}
```
To check the updated downloads, setup a `updatedDownloadsHandler` block in your AppDelegate:
```swift
SwiftyStoreKit.updatedDownloadsHandler = { downloads in
// contentURL is not nil if downloadState == .finished
let contentURLs = downloads.flatMap { $0.contentURL }
if contentURLs.count == downloads.count {
// process all downloaded files, then finish the transaction
SwiftyStoreKit.finishTransaction(downloads[0].transaction)
}
}
```
To control the state of the downloads, SwiftyStoreKit offers `start()`, `pause()`, `resume()`, `cancel()` methods.
## Receipt verification
This helper can be used to retrieve the (encrypted) local receipt data:
```swift
let receiptData = SwiftyStoreKit.localReceiptData
let receiptString = receiptData.base64EncodedString(options: [])
// do your receipt validation here
```
However, the receipt file may be missing or outdated. Use this method to get the updated receipt:
```swift
SwiftyStoreKit.fetchReceipt(forceRefresh: true) { result in
switch result {
case .success(let receiptData):
let encryptedReceipt = receiptData.base64EncodedString(options: [])
print("Fetch receipt success:\n\(encryptedReceipt)")
case .error(let error):
print("Fetch receipt failed: \(error)")
}
}
```
Use this method to (optionally) refresh the receipt and perform validation in one step.
```swift
let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
switch result {
case .success(let receipt):
print("Verify receipt success: \(receipt)")
case .error(let error):
print("Verify receipt failed: \(error)")
}
}
```
Additional details about receipt verification are [available on the wiki](https://github.com/bizz84/SwiftyStoreKit/wiki/Verify-Receipt).
## Verifying purchases and subscriptions
Once you have retrieved the receipt using the `verifyReceipt` method, you can verify your purchases and subscriptions by product identifier.
### Verify Purchase
```swift
let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
switch result {
case .success(let receipt):
let productId = "com.musevisions.SwiftyStoreKit.Purchase1"
// Verify the purchase of Consumable or NonConsumable
let purchaseResult = SwiftyStoreKit.verifyPurchase(
productId: productId,
inReceipt: receipt)
switch purchaseResult {
case .purchased(let receiptItem):
print("\(productId) is purchased: \(receiptItem)")
case .notPurchased:
print("The user has never purchased \(productId)")
}
case .error(let error):
print("Receipt verification failed: \(error)")
}
}
```
### Verify Subscription
This can be used to check if a subscription was previously purchased, and whether it is still active or if it's expired.
From [Apple - Working with Subscriptions](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/Subscriptions.html#//apple_ref/doc/uid/TP40008267-CH7-SW6):
> Keep a record of the date that each piece of content is published. Read the Original Purchase Date and Subscription Expiration Date field from each receipt entry to determine the start and end dates of the subscription.
When one or more subscriptions are found for a given product id, they are returned as a `ReceiptItem` array ordered by `expiryDate`, with the first one being the newest.
```swift
let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
switch result {
case .success(let receipt):
let productId = "com.musevisions.SwiftyStoreKit.Subscription"
// Verify the purchase of a Subscription
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable, // or .nonRenewing (see below)
productId: productId,
inReceipt: receipt)
switch purchaseResult {
case .purchased(let expiryDate, let items):
print("\(productId) is valid until \(expiryDate)\n\(items)\n")
case .expired(let expiryDate, let items):
print("\(productId) is expired since \(expiryDate)\n\(items)\n")
case .notPurchased:
print("The user has never purchased \(productId)")
}
case .error(let error):
print("Receipt verification failed: \(error)")
}
}
```
Further documentation on verifying subscriptions is [available on the wiki](https://github.com/bizz84/SwiftyStoreKit/wiki/Verify-Subscription).
### Subscription Groups
From [Apple Docs - Offering Subscriptions](https://developer.apple.com/app-store/subscriptions/):
> A subscription group is a set of in-app purchases that you can create to provide users with a range of content offerings, service levels, or durations to best meet their needs. Users can only buy one subscription within a subscription group at a time. If users would want to buy more that one type of subscription — for example, to subscribe to more than one channel in a streaming app — you can put these in-app purchases in different subscription groups.
You can verify all subscriptions within the same group with the `verifySubscriptions` method. [Learn more on the wiki](https://github.com/bizz84/SwiftyStoreKit/wiki/Subscription-Groups).
## Notes
The framework provides a simple block based API with robust error handling on top of the existing StoreKit framework. It does **NOT** persist in app purchases data locally. It is up to clients to do this with a storage solution of choice (i.e. NSUserDefaults, CoreData, Keychain).
## Change Log
See the [Releases Page](https://github.com/bizz84/SwiftyStoreKit/releases).
## Sample Code
The project includes demo apps [for iOS](https://github.com/bizz84/SwiftyStoreKit/blob/master/SwiftyStoreKit-iOS-Demo/ViewController.swift) [and macOS](https://github.com/bizz84/SwiftyStoreKit/blob/master/SwiftyStoreKit-macOS-Demo/ViewController.swift) showing how to use SwiftyStoreKit.
Note that the pre-registered in app purchases in the demo apps are for illustration purposes only and may not work as iTunes Connect may invalidate them.
## Essential Reading
* [Apple - WWDC16, Session 702: Using Store Kit for In-app Purchases with Swift 3](https://developer.apple.com/videos/play/wwdc2016/702/)
* [Apple - TN2387: In-App Purchase Best Practices](https://developer.apple.com/library/content/technotes/tn2387/_index.html)
* [Apple - TN2413: In-App Purchase FAQ](https://developer.apple.com/library/content/technotes/tn2413/_index.html) (also see [Cannot connect to iTunes Store](https://developer.apple.com/library/content/technotes/tn2413/_index.html#//apple_ref/doc/uid/DTS40016228-CH1-ERROR_MESSAGES-CANNOT_CONNECT_TO_ITUNES_STORE))
* [Apple - TN2259: Adding In-App Purchase to Your Applications](https://developer.apple.com/library/content/technotes/tn2259/_index.html)
* [iTunes Connect Developer Help - Workflow for configuring in-app purchases](https://help.apple.com/itunes-connect/developer/#/devb57be10e7)
* [Apple - About Receipt Validation](https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Introduction.html)
* [Apple - Receipt Validation Programming Guide](https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1)
* [Apple - Validating Receipts Locally](https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html)
* [Apple - Working with Subscriptions](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/Subscriptions.html#//apple_ref/doc/uid/TP40008267-CH7-SW6)
* [Apple - Offering Subscriptions](https://developer.apple.com/app-store/subscriptions/)
* [Apple - Restoring Purchased Products](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/Restoring.html#//apple_ref/doc/uid/TP40008267-CH8-SW9)
* [Apple - Testing In-App Purchase Products](https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/TestingInAppPurchases.html): includes info on duration of subscriptions in sandbox mode
* [objc.io - Receipt Validation](https://www.objc.io/issues/17-security/receipt-validation/)
I have also written about building SwiftyStoreKit on Medium:
* [How I got 1000 ⭐️ on my GitHub Project](https://medium.com/ios-os-x-development/how-i-got-1000-%EF%B8%8F-on-my-github-project-654d3d394ca6#.1idp27olf)
* [Maintaining a Growing Open Source Project](https://medium.com/@biz84/maintaining-a-growing-open-source-project-1d385ca84c5#.4cv2g7tdc)
### Troubleshooting
* [Apple TN 2413 - Why are my product identifiers being returned in the invalidProductIdentifiers array?](https://developer.apple.com/library/content/technotes/tn2413/_index.html#//apple_ref/doc/uid/DTS40016228-CH1-TROUBLESHOOTING-WHY_ARE_MY_PRODUCT_IDENTIFIERS_BEING_RETURNED_IN_THE_INVALIDPRODUCTIDENTIFIERS_ARRAY_)
* [Invalid Product IDs](http://troybrant.net/blog/2010/01/invalid-product-ids/): Checklist of common mistakes
* [Testing Auto-Renewable Subscriptions on iOS](http://davidbarnard.com/post/164337147440/testing-auto-renewable-subscriptions-on-ios)
* [Apple forums - iOS 11 beta sandbox - cannot connect to App Store](https://forums.developer.apple.com/message/261428#261428)
## Video Tutorials
#### Jared Davidson: In App Purchases! (Swift 3 in Xcode : Swifty Store Kit)
#### [@rebeloper](https://github.com/rebeloper): Ultimate In-app Purchases Guide
## Written Tutorials
* [In App Purchase (IAP) made simple with SwiftyStoreKit](https://levelup.gitconnected.com/beginner-ios-dev-in-app-purchase-iap-made-simple-with-swiftystorekit-3add60e9065d)
## Credits
Many thanks to [phimage](https://github.com/phimage) for adding macOS support and receipt verification.
## Apps using SwiftyStoreKit
It would be great to showcase apps using SwiftyStoreKit here. Pull requests welcome :)
* [Every Plant, Ever](https://itunes.apple.com/us/app/every-plant-ever/id1433967019) - The sticker pack of every plant, ever.
* [Countdown](https://countdowns.download/ssk) - Countdown the days until your next vacation, deadline, or event
* [MDacne](https://itunes.apple.com/app/id1044050208) - Acne analysis and treatment
* [Pixel Picker](https://itunes.apple.com/app/id930804327) - Image Color Picker
* [KType](https://itunes.apple.com/app/id1037000234) - Space shooter game
* [iPic](https://itunes.apple.com/app/id1101244278) - Automatically upload images and save Markdown links
* [iHosts](https://itunes.apple.com/app/id1102004240) - Perfect for editing /etc/hosts
* [Arise](http://www.abnehm-app.de/) - Calorie counter
* [Truth Truth Lie](https://itunes.apple.com/app/id1130832864) - iMessage game, featured by Apple
* [Tactus Music Player](https://itunes.apple.com/app/id557446352) - Alternative music player app
* [Drops](https://itunes.apple.com/app/id939540371) - Language learning app
* [Fresh Snow](https://itunes.apple.com/app/id1063000470) - Colorado Ski Report
* [Zmeu Grand Canyon](http://grandcanyon.zmeu.guide/) - Interactive hiking map & planner
* [OB Monitor](https://itunes.apple.com/app/id1073398446) - The app for Texas Longhorns athletics fans
* [Talk Dim Sum](https://itunes.apple.com/us/app/talk-dim-sum/id953929066) - Your dim sum companion
* [Sluggard](https://itunes.apple.com/app/id1160131071) - Perform simple exercises to reduce the risks of sedentary lifestyle
* [Debts iOS](https://debts.ivanvorobei.by/ios) & [Debts macOS](https://debts.ivanvorobei.by/macos) - Track amounts owed
* [Botcher](https://itunes.apple.com/us/app/id1522337788) - Good for finding something to do
* [Hashr](https://apps.apple.com/app/id1166499829) - Generate unique password hashes based on website and master password
* [QRFi](https://apps.apple.com/app/id1535761355) - Create stylish QR Codes for WiFi
A full list of apps is published [on AppSight](https://www.appsight.io/sdk/574154).
================================================
FILE: Sources/SwiftyStoreKit/AppleReceiptValidator.swift
================================================
//
// InAppReceipt.swift
// SwiftyStoreKit
//
// Created by phimage on 22/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
// https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
public class AppleReceiptValidator: ReceiptValidator {
public enum VerifyReceiptURLType: String {
case production = "https://buy.itunes.apple.com/verifyReceipt"
case sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
}
/// You should always verify your receipt first with the `production` service
/// Note: will auto change to `.sandbox` and validate again if received a 21007 status code from Apple
public var service: VerifyReceiptURLType
private let sharedSecret: String?
/**
* Reference Apple Receipt Validator
* - Parameter service: Either .production or .sandbox
* - Parameter sharedSecret: Only used for receipts that contain auto-renewable subscriptions. Your app’s shared secret (a hexadecimal string).
*/
public init(service: VerifyReceiptURLType = .production, sharedSecret: String? = nil) {
self.service = service
self.sharedSecret = sharedSecret
}
public func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void) {
let storeURL = URL(string: service.rawValue)! // safe (until no more)
let storeRequest = NSMutableURLRequest(url: storeURL)
storeRequest.httpMethod = "POST"
let receipt = receiptData.base64EncodedString(options: [])
let requestContents: NSMutableDictionary = [ "receipt-data": receipt ]
// password if defined
if let password = sharedSecret {
requestContents.setValue(password, forKey: "password")
}
// Encore request body
do {
storeRequest.httpBody = try JSONSerialization.data(withJSONObject: requestContents, options: [])
} catch let e {
completion(.error(error: .requestBodyEncodeError(error: e)))
return
}
// Remote task
let task = URLSession.shared.dataTask(with: storeRequest as URLRequest) { data, _, error -> Void in
// there is an error
if let networkError = error {
completion(.error(error: .networkError(error: networkError)))
return
}
// there is no data
guard let safeData = data else {
completion(.error(error: .noRemoteData))
return
}
// cannot decode data
guard let receiptInfo = try? JSONSerialization.jsonObject(with: safeData, options: .mutableLeaves) as? ReceiptInfo ?? [:] else {
let jsonStr = String(data: safeData, encoding: String.Encoding.utf8)
completion(.error(error: .jsonDecodeError(string: jsonStr)))
return
}
// get status from info
if let status = receiptInfo["status"] as? Int {
/*
* http://stackoverflow.com/questions/16187231/how-do-i-know-if-an-in-app-purchase-receipt-comes-from-the-sandbox
* How do I verify my receipt (iOS)?
* Always verify your receipt first with the production URL; proceed to verify
* with the sandbox URL if you receive a 21007 status code. Following this
* approach ensures that you do not have to switch between URLs while your
* application is being tested or reviewed in the sandbox or is live in the
* App Store.
* Note: The 21007 status code indicates that this receipt is a sandbox receipt,
* but it was sent to the production service for verification.
*/
let receiptStatus = ReceiptStatus(rawValue: status) ?? ReceiptStatus.unknown
if case .testReceipt = receiptStatus {
self.service = .sandbox
self.validate(receiptData: receiptData, completion: completion)
} else {
if receiptStatus.isValid {
completion(.success(receipt: receiptInfo))
} else {
completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: receiptStatus)))
}
}
} else {
completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: ReceiptStatus.none)))
}
}
task.resume()
}
}
================================================
FILE: Sources/SwiftyStoreKit/CompleteTransactionsController.swift
================================================
//
// CompleteTransactionsController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
import StoreKit
struct CompleteTransactions {
let atomically: Bool
let callback: ([Purchase]) -> Void
init(atomically: Bool, callback: @escaping ([Purchase]) -> Void) {
self.atomically = atomically
self.callback = callback
}
}
class CompleteTransactionsController: TransactionController {
var completeTransactions: CompleteTransactions?
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
guard let completeTransactions = completeTransactions else {
print("SwiftyStoreKit.completeTransactions() should be called once when the app launches.")
return transactions
}
var unhandledTransactions: [SKPaymentTransaction] = []
var purchases: [Purchase] = []
for transaction in transactions {
let transactionState = transaction.transactionState
if transactionState != .purchasing {
let willFinishTransaction = completeTransactions.atomically || transactionState == .failed
let purchase = Purchase(productId: transaction.payment.productIdentifier, quantity: transaction.payment.quantity, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !willFinishTransaction)
purchases.append(purchase)
if willFinishTransaction {
print("Finishing transaction for payment \"\(transaction.payment.productIdentifier)\" with state: \(transactionState.debugDescription)")
paymentQueue.finishTransaction(transaction)
}
} else {
unhandledTransactions.append(transaction)
}
}
if purchases.count > 0 {
completeTransactions.callback(purchases)
}
return unhandledTransactions
}
}
================================================
FILE: Sources/SwiftyStoreKit/InAppProductQueryRequest.swift
================================================
//
// InAppPurchaseProductRequest.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
typealias InAppProductRequestCallback = (RetrieveResults) -> Void
public protocol InAppRequest: AnyObject {
func start()
func cancel()
}
protocol InAppProductRequest: InAppRequest {
var hasCompleted: Bool { get }
var cachedResults: RetrieveResults? { get }
}
class InAppProductQueryRequest: NSObject, InAppProductRequest, SKProductsRequestDelegate {
private let callback: InAppProductRequestCallback
private let request: SKProductsRequest
private(set) var cachedResults: RetrieveResults?
var hasCompleted: Bool { cachedResults != nil }
deinit {
request.delegate = nil
}
init(productIds: Set, callback: @escaping InAppProductRequestCallback) {
self.callback = callback
request = SKProductsRequest(productIdentifiers: productIds)
super.init()
request.delegate = self
}
func start() {
request.start()
}
func cancel() {
request.cancel()
}
// MARK: SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let retrievedProducts = Set(response.products)
let invalidProductIDs = Set(response.invalidProductIdentifiers)
let results = RetrieveResults(
retrievedProducts: retrievedProducts,
invalidProductIDs: invalidProductIDs, error: nil
)
self.cachedResults = results
performCallback(results)
}
func requestDidFinish(_ request: SKRequest) {
}
func request(_ request: SKRequest, didFailWithError error: Error) {
performCallback(RetrieveResults(retrievedProducts: Set(), invalidProductIDs: Set(), error: error))
}
private func performCallback(_ results: RetrieveResults) {
DispatchQueue.main.async {
self.callback(results)
}
}
}
================================================
FILE: Sources/SwiftyStoreKit/InAppReceipt.swift
================================================
//
// InAppReceipt.swift
// SwiftyStoreKit
//
// Created by phimage on 22/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 Date {
init?(millisecondsSince1970: String) {
guard let millisecondsNumber = Double(millisecondsSince1970) else {
return nil
}
self = Date(timeIntervalSince1970: millisecondsNumber / 1000)
}
}
extension ReceiptItem {
public init?(receiptInfo: ReceiptInfo) {
guard
let productId = receiptInfo["product_id"] as? String,
let quantityString = receiptInfo["quantity"] as? String,
let quantity = Int(quantityString),
let transactionId = receiptInfo["transaction_id"] as? String,
let originalTransactionId = receiptInfo["original_transaction_id"] as? String,
let purchaseDate = ReceiptItem.parseDate(from: receiptInfo, key: "purchase_date_ms"),
let originalPurchaseDate = ReceiptItem.parseDate(from: receiptInfo, key: "original_purchase_date_ms")
else {
print("could not parse receipt item: \(receiptInfo). Skipping...")
return nil
}
self.productId = productId
self.quantity = quantity
self.transactionId = transactionId
self.originalTransactionId = originalTransactionId
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.webOrderLineItemId = receiptInfo["web_order_line_item_id"] as? String
self.subscriptionExpirationDate = ReceiptItem.parseDate(from: receiptInfo, key: "expires_date_ms")
self.cancellationDate = ReceiptItem.parseDate(from: receiptInfo, key: "cancellation_date_ms")
if let isTrialPeriod = receiptInfo["is_trial_period"] as? String {
self.isTrialPeriod = Bool(isTrialPeriod) ?? false
} else {
self.isTrialPeriod = false
}
if let isInIntroOfferPeriod = receiptInfo["is_in_intro_offer_period"] as? String {
self.isInIntroOfferPeriod = Bool(isInIntroOfferPeriod) ?? false
} else {
self.isInIntroOfferPeriod = false
}
self.isUpgraded = receiptInfo["is_upgraded"] as? Bool ?? false
}
private static func parseDate(from receiptInfo: ReceiptInfo, key: String) -> Date? {
guard
let requestDateString = receiptInfo[key] as? String,
let requestDateMs = Double(requestDateString) else {
return nil
}
return Date(timeIntervalSince1970: requestDateMs / 1000)
}
}
// MARK: - receipt mangement
internal class InAppReceipt {
/**
* Verify the purchase of a Consumable or NonConsumable product in a receipt
* - Parameter productId: the product id of the purchase to verify
* - Parameter inReceipt: the receipt to use for looking up the purchase
* - return: either notPurchased or purchased
*/
class func verifyPurchase(
productId: String,
inReceipt receipt: ReceiptInfo
) -> VerifyPurchaseResult {
// Get receipts info for the product
let receipts = getInAppReceipts(receipt: receipt)
let filteredReceiptsInfo = filterReceiptsInfo(receipts: receipts, withProductIds: [productId])
let nonCancelledReceiptsInfo = filteredReceiptsInfo.filter { receipt in receipt["cancellation_date"] == nil }
#if swift(>=4.1)
let receiptItems = nonCancelledReceiptsInfo.compactMap { ReceiptItem(receiptInfo: $0) }
#else
let receiptItems = nonCancelledReceiptsInfo.flatMap { ReceiptItem(receiptInfo: $0) }
#endif
// Verify that at least one receipt has the right product id
if let firstItem = receiptItems.first {
return .purchased(item: firstItem)
}
return .notPurchased
}
/**
* Verify the validity of a set of subscriptions in a receipt.
*
* This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity.
* - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
* - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter productIds: The product ids of the subscriptions to verify.
* - Parameter receipt: The receipt to use for looking up the subscriptions
* - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt.
* - return: Either .notPurchased or .purchased / .expired with the expiry date found in the receipt.
*/
class func verifySubscriptions(
ofType type: SubscriptionType,
productIds: Set,
inReceipt receipt: ReceiptInfo,
validUntil date: Date = Date()
) -> VerifySubscriptionResult {
// The values of the latest_receipt and latest_receipt_info keys are useful when checking whether an auto-renewable subscription is currently active. By providing any transaction receipt for the subscription and checking these values, you can get information about the currently-active subscription period. If the receipt being validated is for the latest renewal, the value for latest_receipt is the same as receipt-data (in the request) and the value for latest_receipt_info is the same as receipt.
let (receipts, duration) = getReceiptsAndDuration(for: type, inReceipt: receipt)
let receiptsInfo = filterReceiptsInfo(receipts: receipts, withProductIds: productIds)
let nonCancelledReceiptsInfo = receiptsInfo.filter { receipt in receipt["cancellation_date"] == nil }
if nonCancelledReceiptsInfo.count == 0 {
return .notPurchased
}
let receiptDate = getReceiptRequestDate(inReceipt: receipt) ?? date
#if swift(>=4.1)
let receiptItems = nonCancelledReceiptsInfo.compactMap { ReceiptItem(receiptInfo: $0) }
#else
let receiptItems = nonCancelledReceiptsInfo.flatMap { ReceiptItem(receiptInfo: $0) }
#endif
if nonCancelledReceiptsInfo.count > receiptItems.count {
print("receipt has \(nonCancelledReceiptsInfo.count) items, but only \(receiptItems.count) were parsed")
}
let sortedExpiryDatesAndItems = expiryDatesAndItems(receiptItems: receiptItems, duration: duration).sorted { a, b in
return a.0 > b.0
}
guard let firstExpiryDateItemPair = sortedExpiryDatesAndItems.first else {
return .notPurchased
}
let sortedReceiptItems = sortedExpiryDatesAndItems.map { $0.1 }
if firstExpiryDateItemPair.0 > receiptDate {
return .purchased(expiryDate: firstExpiryDateItemPair.0, items: sortedReceiptItems)
} else {
return .expired(expiryDate: firstExpiryDateItemPair.0, items: sortedReceiptItems)
}
}
/**
* Get the distinct product identifiers from receipt.
*
* This Method extracts all product identifiers. (Including cancelled ones).
* - Note: You can use this method to get all unique product identifiers from receipt.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter receipt: The receipt to use for looking up the product identifiers.
* - return: Either Set or nil.
*/
class func getDistinctPurchaseIds(
ofType type: SubscriptionType,
inReceipt receipt: ReceiptInfo
) -> Set? {
// Get receipts array from receipt
guard let receipts = getReceipts(for: type, inReceipt: receipt) else {
return nil
}
#if swift(>=4.1)
let receiptIds = receipts.compactMap { ReceiptItem(receiptInfo: $0)?.productId }
#else
let receiptIds = receipts.flatMap { ReceiptItem(receiptInfo: $0)?.productId }
#endif
if receiptIds.isEmpty {
return nil
}
return Set(receiptIds)
}
private class func expiryDatesAndItems(receiptItems: [ReceiptItem], duration: TimeInterval?) -> [(Date, ReceiptItem)] {
if let duration = duration {
return receiptItems.map {
let expirationDate = Date(timeIntervalSince1970: $0.originalPurchaseDate.timeIntervalSince1970 + duration)
return (expirationDate, $0)
}
} else {
#if swift(>=4.1)
return receiptItems.compactMap {
if let expirationDate = $0.subscriptionExpirationDate {
return (expirationDate, $0)
}
return nil
}
#else
return receiptItems.flatMap {
if let expirationDate = $0.subscriptionExpirationDate {
return (expirationDate, $0)
}
return nil
}
#endif
}
}
private class func getReceipts(for subscriptionType: SubscriptionType, inReceipt receipt: ReceiptInfo) -> [ReceiptInfo]? {
switch subscriptionType {
case .autoRenewable:
return receipt["latest_receipt_info"] as? [ReceiptInfo]
case .nonRenewing:
return getInAppReceipts(receipt: receipt)
}
}
private class func getReceiptsAndDuration(for subscriptionType: SubscriptionType, inReceipt receipt: ReceiptInfo) -> ([ReceiptInfo]?, TimeInterval?) {
switch subscriptionType {
case .autoRenewable:
return (receipt["latest_receipt_info"] as? [ReceiptInfo], nil)
case .nonRenewing(let duration):
return (getInAppReceipts(receipt: receipt), duration)
}
}
private class func getReceiptRequestDate(inReceipt receipt: ReceiptInfo) -> Date? {
guard let receiptInfo = receipt["receipt"] as? ReceiptInfo,
let requestDateString = receiptInfo["request_date_ms"] as? String else {
return nil
}
return Date(millisecondsSince1970: requestDateString)
}
private class func getInAppReceipts(receipt: ReceiptInfo) -> [ReceiptInfo]? {
let appReceipt = receipt["receipt"] as? ReceiptInfo
return appReceipt?["in_app"] as? [ReceiptInfo]
}
/**
* Get all the receipts info for a specific product
* - Parameter receipts: the receipts array to grab info from
* - Parameter productId: the product id
*/
private class func filterReceiptsInfo(receipts: [ReceiptInfo]?, withProductIds productIds: Set) -> [ReceiptInfo] {
guard let receipts = receipts else {
return []
}
// Filter receipts with matching product ids
let receiptsMatchingProductIds = receipts
.filter { (receipt) -> Bool in
if let productId = receipt["product_id"] as? String {
return productIds.contains(productId)
}
return false
}
return receiptsMatchingProductIds
}
}
================================================
FILE: Sources/SwiftyStoreKit/InAppReceiptRefreshRequest.swift
================================================
//
// InAppReceiptRefreshRequest.swift
// SwiftyStoreKit
//
// Created by phimage on 23/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
import Foundation
class InAppReceiptRefreshRequest: NSObject, SKRequestDelegate, InAppRequest {
enum ResultType {
case success
case error(e: Error)
}
typealias RequestCallback = (ResultType) -> Void
typealias ReceiptRefresh = (_ receiptProperties: [String: Any]?, _ callback: @escaping RequestCallback) -> InAppReceiptRefreshRequest
class func refresh(_ receiptProperties: [String: Any]? = nil, callback: @escaping RequestCallback) -> InAppReceiptRefreshRequest {
let request = InAppReceiptRefreshRequest(receiptProperties: receiptProperties, callback: callback)
request.start()
return request
}
let refreshReceiptRequest: SKReceiptRefreshRequest
let callback: RequestCallback
deinit {
refreshReceiptRequest.delegate = nil
}
init(receiptProperties: [String: Any]? = nil, callback: @escaping RequestCallback) {
self.callback = callback
self.refreshReceiptRequest = SKReceiptRefreshRequest(receiptProperties: receiptProperties)
super.init()
self.refreshReceiptRequest.delegate = self
}
func start() {
self.refreshReceiptRequest.start()
}
func cancel() {
self.refreshReceiptRequest.cancel()
}
func requestDidFinish(_ request: SKRequest) {
/*if let resoreRequest = request as? SKReceiptRefreshRequest {
let receiptProperties = resoreRequest.receiptProperties ?? [:]
for (k, v) in receiptProperties {
print("\(k): \(v)")
}
}*/
performCallback(.success)
}
func request(_ request: SKRequest, didFailWithError error: Error) {
// XXX could here check domain and error code to return typed exception
performCallback(.error(e: error))
}
private func performCallback(_ result: ResultType) {
DispatchQueue.main.async {
self.callback(result)
}
}
}
================================================
FILE: Sources/SwiftyStoreKit/InAppReceiptVerificator.swift
================================================
//
// InAppReceiptVerificator.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 16/05/2017.
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
class InAppReceiptVerificator: NSObject {
let appStoreReceiptURL: URL?
init(appStoreReceiptURL: URL? = Bundle.main.appStoreReceiptURL) {
self.appStoreReceiptURL = appStoreReceiptURL
}
var appStoreReceiptData: Data? {
guard let receiptDataURL = appStoreReceiptURL,
let data = try? Data(contentsOf: receiptDataURL) else {
return nil
}
return data
}
private var receiptRefreshRequest: InAppReceiptRefreshRequest?
/**
* Verify application receipt.
* - Parameter validator: Validator to check the encrypted receipt and return the receipt in readable format
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter refresh: closure to perform receipt refresh (this is made explicit for testability)
* - Parameter completion: handler for result
*/
@discardableResult
public func verifyReceipt(using validator: ReceiptValidator,
forceRefresh: Bool,
refresh: InAppReceiptRefreshRequest.ReceiptRefresh = InAppReceiptRefreshRequest.refresh,
completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
return fetchReceipt(forceRefresh: forceRefresh, refresh: refresh) { result in
switch result {
case .success(let receiptData):
self.verify(receiptData: receiptData, using: validator, completion: completion)
case .error(let error):
completion(.error(error: error))
}
}
}
/**
* Fetch application receipt. This method does two things:
* * If the receipt is missing, refresh it
* * If the receipt is available or is refreshed, validate it
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter refresh: closure to perform receipt refresh (this is made explicit for testability)
* - Parameter completion: handler for result
*/
@discardableResult
public func fetchReceipt(forceRefresh: Bool,
refresh: InAppReceiptRefreshRequest.ReceiptRefresh = InAppReceiptRefreshRequest.refresh,
completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
if let receiptData = appStoreReceiptData, forceRefresh == false {
completion(.success(receiptData: receiptData))
return nil
} else {
receiptRefreshRequest = refresh(nil) { result in
self.receiptRefreshRequest = nil
switch result {
case .success:
if let receiptData = self.appStoreReceiptData {
completion(.success(receiptData: receiptData))
} else {
completion(.error(error: .noReceiptData))
}
case .error(let e):
completion(.error(error: .networkError(error: e)))
}
}
return receiptRefreshRequest
}
}
/**
* - Parameter receiptData: encrypted receipt data
* - Parameter validator: Validator to check the encrypted receipt and return the receipt in readable format
* - Parameter completion: handler for result
*/
private func verify(receiptData: Data, using validator: ReceiptValidator, completion: @escaping (VerifyReceiptResult) -> Void) {
validator.validate(receiptData: receiptData) { result in
DispatchQueue.main.async {
completion(result)
}
}
}
}
================================================
FILE: Sources/SwiftyStoreKit/OS.swift
================================================
//
// OS.swift
// SwiftyStoreKit
//
// Copyright (c) 2020 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
// MARK: - Missing SKMutablePayment init with product on macOS
#if os(OSX)
extension SKMutablePayment {
convenience init(product: SKProduct) {
self.init()
self.productIdentifier = product.productIdentifier
}
}
#endif
// MARK: - Missing SKError on watchOS
#if os(watchOS) && swift(<5.3)
public struct SKError: Error {
public typealias Code = SKErrorCode
let _nsError: NSError
init(_nsError: NSError) {
self._nsError = _nsError
}
public var code: Code {
return Code(rawValue: _nsError.code) ?? .unknown
}
static var unknown: Code = .unknown
static var paymentInvalid: Code = .paymentInvalid
}
#endif
================================================
FILE: Sources/SwiftyStoreKit/PaymentQueueController.swift
================================================
//
// PaymentQueueController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
import StoreKit
protocol TransactionController {
/// Process the supplied transactions on a given queue.
/// - parameter transactions: transactions to process
/// - parameter paymentQueue: payment queue for finishing transactions
/// - returns: array of unhandled transactions
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction]
}
public enum TransactionResult {
case purchased(purchase: PurchaseDetails)
case restored(purchase: Purchase)
case deferred(purchase: PurchaseDetails)
case failed(error: SKError)
}
public protocol PaymentQueue: AnyObject {
func add(_ observer: SKPaymentTransactionObserver)
func remove(_ observer: SKPaymentTransactionObserver)
func add(_ payment: SKPayment)
func start(_ downloads: [SKDownload])
func pause(_ downloads: [SKDownload])
func resume(_ downloads: [SKDownload])
func cancel(_ downloads: [SKDownload])
func restoreCompletedTransactions(withApplicationUsername username: String?)
func finishTransaction(_ transaction: SKPaymentTransaction)
}
extension SKPaymentQueue: PaymentQueue {
#if os(watchOS) && swift(<5.3)
public func resume(_ downloads: [SKDownload]) {
resumeDownloads(downloads)
}
#endif
}
extension SKPaymentTransaction {
open override var debugDescription: String {
let transactionId = transactionIdentifier ?? "null"
return "productId: \(payment.productIdentifier), transactionId: \(transactionId), state: \(transactionState), date: \(String(describing: transactionDate))"
}
}
extension SKPaymentTransactionState: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .purchasing: return "purchasing"
case .purchased: return "purchased"
case .failed: return "failed"
case .restored: return "restored"
case .deferred: return "deferred"
@unknown default: return "default"
}
}
}
struct EntitlementRevocation {
let callback: ([String]) -> Void
init(callback: @escaping ([String]) -> Void) {
self.callback = callback
}
}
class PaymentQueueController: NSObject, SKPaymentTransactionObserver {
private let paymentsController: PaymentsController
private let restorePurchasesController: RestorePurchasesController
private let completeTransactionsController: CompleteTransactionsController
unowned let paymentQueue: PaymentQueue
private var entitlementRevocation: EntitlementRevocation?
deinit {
paymentQueue.remove(self)
}
init(paymentQueue: PaymentQueue = SKPaymentQueue.default(),
paymentsController: PaymentsController = PaymentsController(),
restorePurchasesController: RestorePurchasesController = RestorePurchasesController(),
completeTransactionsController: CompleteTransactionsController = CompleteTransactionsController()) {
self.paymentQueue = paymentQueue
self.paymentsController = paymentsController
self.restorePurchasesController = restorePurchasesController
self.completeTransactionsController = completeTransactionsController
super.init()
paymentQueue.add(self)
}
private func assertCompleteTransactionsWasCalled() {
let message = "SwiftyStoreKit.completeTransactions() must be called when the app launches."
assert(completeTransactionsController.completeTransactions != nil, message)
}
func startPayment(_ payment: Payment) {
assertCompleteTransactionsWasCalled()
let skPayment = SKMutablePayment(product: payment.product)
skPayment.applicationUsername = payment.applicationUsername
skPayment.quantity = payment.quantity
if #available(iOS 12.2, tvOS 12.2, OSX 10.14.4, watchOS 6.2, *) {
if let discount = payment.paymentDiscount?.discount as? SKPaymentDiscount {
skPayment.paymentDiscount = discount
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
if #available(iOS 8.3, watchOS 6.2, *) {
skPayment.simulatesAskToBuyInSandbox = payment.simulatesAskToBuyInSandbox
}
#endif
paymentQueue.add(skPayment)
paymentsController.append(payment)
}
func onEntitlementRevocation(_ revocation: EntitlementRevocation) {
guard entitlementRevocation == nil else {
print("SwiftyStoreKit.onEntitlementRevocation() should only be called once when the app launches. Ignoring this call")
return
}
self.entitlementRevocation = revocation
}
func restorePurchases(_ restorePurchases: RestorePurchases) {
assertCompleteTransactionsWasCalled()
if restorePurchasesController.restorePurchases != nil {
return
}
paymentQueue.restoreCompletedTransactions(withApplicationUsername: restorePurchases.applicationUsername)
restorePurchasesController.restorePurchases = restorePurchases
}
func completeTransactions(_ completeTransactions: CompleteTransactions) {
guard completeTransactionsController.completeTransactions == nil else {
print("SwiftyStoreKit.completeTransactions() should only be called once when the app launches. Ignoring this call")
return
}
completeTransactionsController.completeTransactions = completeTransactions
}
func finishTransaction(_ transaction: PaymentTransaction) {
guard let skTransaction = transaction as? SKPaymentTransaction else {
print("Object is not a SKPaymentTransaction: \(transaction)")
return
}
paymentQueue.finishTransaction(skTransaction)
}
func start(_ downloads: [SKDownload]) {
paymentQueue.start(downloads)
}
func pause(_ downloads: [SKDownload]) {
paymentQueue.pause(downloads)
}
func resume(_ downloads: [SKDownload]) {
paymentQueue.resume(downloads)
}
func cancel(_ downloads: [SKDownload]) {
paymentQueue.cancel(downloads)
}
var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler?
var updatedDownloadsHandler: UpdatedDownloadsHandler?
// MARK: - SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
/*
* Some notes about how requests are processed by SKPaymentQueue:
*
* SKPaymentQueue is used to queue payments or restore purchases requests.
* Payments are processed serially and in-order and require user interaction.
* Restore purchases requests don't require user interaction and can jump ahead of the queue.
* SKPaymentQueue rejects multiple restore purchases calls.
* Having one payment queue observer for each request causes extra processing
* Failed transactions only ever belong to queued payment requests.
* restoreCompletedTransactionsFailedWithError is always called when a restore purchases request fails.
* paymentQueueRestoreCompletedTransactionsFinished is always called following 0 or more update transactions when a restore purchases request succeeds.
* A complete transactions handler is required to catch any transactions that are updated when the app is not running.
* Registering a complete transactions handler when the app launches ensures that any pending transactions can be cleared.
* If a complete transactions handler is missing, pending transactions can be mis-attributed to any new incoming payments or restore purchases.
*
* The order in which transaction updates are processed is:
* 1. payments (transactionState: .purchased and .failed for matching product identifiers)
* 2. restore purchases (transactionState: .restored, or restoreCompletedTransactionsFailedWithError, or paymentQueueRestoreCompletedTransactionsFinished)
* 3. complete transactions (transactionState: .purchased, .failed, .restored, .deferred)
* Any transactions where state == .purchasing are ignored.
*/
var unhandledTransactions = transactions.filter { $0.transactionState != .purchasing }
if unhandledTransactions.count > 0 {
unhandledTransactions = paymentsController.processTransactions(transactions, on: paymentQueue)
unhandledTransactions = restorePurchasesController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = completeTransactionsController.processTransactions(unhandledTransactions, on: paymentQueue)
if unhandledTransactions.count > 0 {
let strings = unhandledTransactions.map { $0.debugDescription }.joined(separator: "\n")
print("unhandledTransactions:\n\(strings)")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) {
self.entitlementRevocation?.callback(productIdentifiers)
}
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
restorePurchasesController.restoreCompletedTransactionsFinished()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
updatedDownloadsHandler?(downloads)
}
#if !os(watchOS)
func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
return shouldAddStorePaymentHandler?(payment, product) ?? false
}
#endif
}
================================================
FILE: Sources/SwiftyStoreKit/PaymentsController.swift
================================================
//
// PaymentsController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
import StoreKit
struct Payment: Hashable {
let product: SKProduct
let paymentDiscount: PaymentDiscount?
let quantity: Int
let atomically: Bool
let applicationUsername: String
let simulatesAskToBuyInSandbox: Bool
let callback: (TransactionResult) -> Void
func hash(into hasher: inout Hasher) {
hasher.combine(product)
hasher.combine(quantity)
hasher.combine(atomically)
hasher.combine(applicationUsername)
hasher.combine(simulatesAskToBuyInSandbox)
}
static func == (lhs: Payment, rhs: Payment) -> Bool {
return lhs.product.productIdentifier == rhs.product.productIdentifier
}
}
public struct PaymentDiscount {
let discount: AnyObject?
@available(iOS 12.2, tvOS 12.2, OSX 10.14.4, watchOS 6.2, macCatalyst 13.0, *)
public init(discount: SKPaymentDiscount) {
self.discount = discount
}
private init() {
self.discount = nil
}
}
class PaymentsController: TransactionController {
private var payments: [Payment] = []
private func findPaymentIndex(withProductIdentifier identifier: String) -> Int? {
for payment in payments where payment.product.productIdentifier == identifier {
return payments.firstIndex(of: payment)
}
return nil
}
func hasPayment(_ payment: Payment) -> Bool {
return findPaymentIndex(withProductIdentifier: payment.product.productIdentifier) != nil
}
func append(_ payment: Payment) {
payments.append(payment)
}
func processTransaction(_ transaction: SKPaymentTransaction, on paymentQueue: PaymentQueue) -> Bool {
let transactionProductIdentifier = transaction.payment.productIdentifier
guard let paymentIndex = findPaymentIndex(withProductIdentifier: transactionProductIdentifier) else {
return false
}
let payment = payments[paymentIndex]
let transactionState = transaction.transactionState
if transactionState == .purchased {
let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically)
payment.callback(.purchased(purchase: purchase))
if payment.atomically {
paymentQueue.finishTransaction(transaction)
}
payments.remove(at: paymentIndex)
return true
}
if transactionState == .restored {
print("Unexpected restored transaction for payment \(transactionProductIdentifier)")
let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically)
payment.callback(.purchased(purchase: purchase))
if payment.atomically {
paymentQueue.finishTransaction(transaction)
}
payments.remove(at: paymentIndex)
return true
}
if transactionState == .failed {
payment.callback(.failed(error: transactionError(for: transaction.error as NSError?)))
paymentQueue.finishTransaction(transaction)
payments.remove(at: paymentIndex)
return true
}
if transactionState == .deferred {
let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically)
payment.callback(.deferred(purchase: purchase))
payments.remove(at: paymentIndex)
return true
}
return false
}
func transactionError(for error: NSError?) -> SKError {
let message = "Unknown error"
let altError = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: [ NSLocalizedDescriptionKey: message ])
let nsError = error ?? altError
return SKError(_nsError: nsError)
}
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
return transactions.filter { !processTransaction($0, on: paymentQueue) }
}
}
================================================
FILE: Sources/SwiftyStoreKit/Platforms/Info-iOS.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
FMWK
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
NSPrincipalClass
================================================
FILE: Sources/SwiftyStoreKit/Platforms/Info-macOS.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
FMWK
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
NSHumanReadableCopyright
Copyright © 2015 musevisions. All rights reserved.
NSPrincipalClass
================================================
FILE: Sources/SwiftyStoreKit/Platforms/Info-tvOS.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
FMWK
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
NSPrincipalClass
================================================
FILE: Sources/SwiftyStoreKit/Platforms/Info-watchOS.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
FMWK
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
NSPrincipalClass
================================================
FILE: Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-iOS.h
================================================
//
// SwiftyStoreKit-iOS.h
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
//! Project version number for SwiftyStoreKit.
FOUNDATION_EXPORT double SwiftyStoreKitVersionNumber;
//! Project version string for SwiftyStoreKit.
FOUNDATION_EXPORT const unsigned char SwiftyStoreKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import
================================================
FILE: Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-macOS.h
================================================
//
// SwiftyStoreKit-macOS.h
// SwiftyStoreKit
//
// Created by phimage on 19/12/15.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
//! Project version number for SwiftyStoreKit.
FOUNDATION_EXPORT double SwiftyStoreKitVersionNumber;
//! Project version string for SwiftyStoreKit.
FOUNDATION_EXPORT const unsigned char SwiftyStoreKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import
================================================
FILE: Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-tvOS.h
================================================
//
// SwiftyStoreKit-tvOS.h
// SwiftyStoreKit
//
// Created by Florian Weich on 26.05.16.
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
//! Project version number for SwiftyStoreKit.
FOUNDATION_EXPORT double SwiftyStoreKitVersionNumber;
//! Project version string for SwiftyStoreKit.
FOUNDATION_EXPORT const unsigned char SwiftyStoreKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import
================================================
FILE: Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-watchOS.h
================================================
//
// SwiftyStoreKit-watchOS.h
// SwiftyStoreKit
//
// Created by Sam Spencer on 5/29/20.
// Copyright © 2020 Sam Spencer. All rights reserved.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
#import
#import
//! Project version number for SwiftyStoreKit.
FOUNDATION_EXPORT double SwiftyStoreKitVersionNumber;
//! Project version string for SwiftyStoreKit.
FOUNDATION_EXPORT const unsigned char SwiftyStoreKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import
================================================
FILE: Sources/SwiftyStoreKit/ProductsInfoController.swift
================================================
//
// ProductsInfoController.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
import StoreKit
protocol InAppProductRequestBuilder: AnyObject {
func request(productIds: Set, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest
}
class InAppProductQueryRequestBuilder: InAppProductRequestBuilder {
func request(productIds: Set, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest {
return InAppProductQueryRequest(productIds: productIds, callback: callback)
}
}
class ProductsInfoController: NSObject {
struct InAppProductQuery {
let request: InAppProductRequest
var completionHandlers: [InAppProductRequestCallback]
}
let inAppProductRequestBuilder: InAppProductRequestBuilder
init(inAppProductRequestBuilder: InAppProductRequestBuilder = InAppProductQueryRequestBuilder()) {
self.inAppProductRequestBuilder = inAppProductRequestBuilder
}
// As we can have multiple inflight requests, we store them in a dictionary by product ids
private var inflightRequests: [Set: InAppProductQuery] = [:]
@discardableResult
func retrieveProductsInfo(_ productIds: Set, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
if inflightRequests[productIds] == nil {
let request = inAppProductRequestBuilder.request(productIds: productIds) { results in
if let query = self.inflightRequests[productIds] {
for completion in query.completionHandlers {
completion(results)
}
self.inflightRequests[productIds] = nil
} else {
// should not get here, but if it does it seems reasonable to call the outer completion block
completion(results)
}
}
inflightRequests[productIds] = InAppProductQuery(request: request, completionHandlers: [completion])
request.start()
return request
} else {
inflightRequests[productIds]!.completionHandlers.append(completion)
let query = inflightRequests[productIds]!
if query.request.hasCompleted {
query.completionHandlers.forEach {
$0(query.request.cachedResults!)
}
}
return inflightRequests[productIds]!.request
}
}
}
================================================
FILE: Sources/SwiftyStoreKit/RestorePurchasesController.swift
================================================
//
// RestorePurchasesController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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
import StoreKit
struct RestorePurchases {
let atomically: Bool
let applicationUsername: String?
let callback: ([TransactionResult]) -> Void
init(atomically: Bool, applicationUsername: String? = nil, callback: @escaping ([TransactionResult]) -> Void) {
self.atomically = atomically
self.applicationUsername = applicationUsername
self.callback = callback
}
}
class RestorePurchasesController: TransactionController {
public var restorePurchases: RestorePurchases?
private var restoredPurchases: [TransactionResult] = []
func processTransaction(_ transaction: SKPaymentTransaction, atomically: Bool, on paymentQueue: PaymentQueue) -> Purchase? {
let transactionState = transaction.transactionState
if transactionState == .restored {
let transactionProductIdentifier = transaction.payment.productIdentifier
let purchase = Purchase(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !atomically)
if atomically {
paymentQueue.finishTransaction(transaction)
}
return purchase
}
return nil
}
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
guard let restorePurchases = restorePurchases else {
return transactions
}
var unhandledTransactions: [SKPaymentTransaction] = []
for transaction in transactions {
if let restoredPurchase = processTransaction(transaction, atomically: restorePurchases.atomically, on: paymentQueue) {
restoredPurchases.append(.restored(purchase: restoredPurchase))
} else {
unhandledTransactions.append(transaction)
}
}
return unhandledTransactions
}
func restoreCompletedTransactionsFailed(withError error: Error) {
guard let restorePurchases = restorePurchases else {
print("Callback already called. Returning")
return
}
restoredPurchases.append(.failed(error: SKError(_nsError: error as NSError)))
restorePurchases.callback(restoredPurchases)
// Reset state after error received
restoredPurchases = []
self.restorePurchases = nil
}
func restoreCompletedTransactionsFinished() {
guard let restorePurchases = restorePurchases else {
print("Callback already called. Returning")
return
}
restorePurchases.callback(restoredPurchases)
// Reset state after error transactions finished
restoredPurchases = []
self.restorePurchases = nil
}
}
================================================
FILE: Sources/SwiftyStoreKit/SKProduct+LocalizedPrice.swift
================================================
//
// SKProduct+LocalizedPrice.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 19/10/2016.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
public extension SKProduct {
var localizedPrice: String? {
return priceFormatter(locale: priceLocale).string(from: price)
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
@available(iOSApplicationExtension 11.2, iOS 11.2, OSX 10.13.2, tvOS 11.2, watchOS 6.2, macCatalyst 13.0, *)
var localizedSubscriptionPeriod: String {
guard let subscriptionPeriod = self.subscriptionPeriod else { return "" }
let dateComponents: DateComponents
switch subscriptionPeriod.unit {
case .day: dateComponents = DateComponents(day: subscriptionPeriod.numberOfUnits)
case .week: dateComponents = DateComponents(weekOfMonth: subscriptionPeriod.numberOfUnits)
case .month: dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
case .year: dateComponents = DateComponents(year: subscriptionPeriod.numberOfUnits)
@unknown default:
print("WARNING: SwiftyStoreKit localizedSubscriptionPeriod does not handle all SKProduct.PeriodUnit cases.")
// Default to month units in the unlikely event a different unit type is added to a future OS version
dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
}
return DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: .short) ?? ""
}
}
================================================
FILE: Sources/SwiftyStoreKit/SKProductDiscount+LocalizedPrice.swift
================================================
//
// SKProductDiscount+LocalizedPrice.swift
// SwiftyStoreKit
//
// Created by Sam Spencer on 5/29/20.
// Copyright © 2020 Sam Spencer. All rights reserved.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
@available(iOSApplicationExtension 11.2, iOS 11.2, OSX 10.13.2, tvOS 11.2, watchOS 4.2, macCatalyst 13.0, *)
public extension SKProductDiscount {
/// The formatted discount price of the product using the local currency.
var localizedPrice: String? {
return priceFormatter(locale: priceLocale).string(from: price)
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
/// The formatted, localized period / date for the product discount.
/// - note: The subscription period for the discount is independent of the product's regular subscription period, and does not have to match in units or duration.
var localizedSubscriptionPeriod: String {
let dateComponents: DateComponents
switch subscriptionPeriod.unit {
case .day: dateComponents = DateComponents(day: subscriptionPeriod.numberOfUnits)
case .week: dateComponents = DateComponents(weekOfMonth: subscriptionPeriod.numberOfUnits)
case .month: dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
case .year: dateComponents = DateComponents(year: subscriptionPeriod.numberOfUnits)
@unknown default:
print("WARNING: SwiftyStoreKit localizedSubscriptionPeriod does not handle all SKProduct.PeriodUnit cases.")
// Default to month units in the unlikely event a different unit type is added to a future OS version
dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
}
return DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: .full) ?? ""
}
}
================================================
FILE: Sources/SwiftyStoreKit/SwiftyStoreKit+Types.swift
================================================
//
// SwiftyStoreKit+Types.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
// MARK: Purchases
/// The Purchased protocol allows different purchase flows to be handled by common code in simple cases
///
/// For example you could route through to
///
/// func didPurchase(item:P) { ... }
///
/// for example
/// - SwiftyStoreKit.completeTransactions (in .purchased and .restored cases)
/// - SwiftyStoreKit.restorePurchases (for results.restoredPurchases)
/// - SwiftyStoreKit.purchaseProducd (in .success case)
public protocol Purchased {
var productId: String { get }
var quantity: Int { get }
var originalPurchaseDate: Date { get }
}
extension Purchase: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
extension PurchaseDetails: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
// Restored product
public struct Purchase {
public let productId: String
public let quantity: Int
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Purchased product
public struct PurchaseDetails {
public let productId: String
public let quantity: Int
public let product: SKProduct
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, product: SKProduct, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.product = product
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Conform to this protocol to provide custom receipt validator
public protocol ReceiptValidator {
func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void)
}
/// Payment transaction
public protocol PaymentTransaction {
var transactionDate: Date? { get }
var transactionState: SKPaymentTransactionState { get }
var transactionIdentifier: String? { get }
var downloads: [SKDownload] { get }
}
/// Add PaymentTransaction conformance to SKPaymentTransaction
extension SKPaymentTransaction: PaymentTransaction { }
/// Products information
public struct RetrieveResults {
public let retrievedProducts: Set
public let invalidProductIDs: Set
public let error: Error?
public init(retrievedProducts: Set, invalidProductIDs: Set, error: Error?) {
self.retrievedProducts = retrievedProducts
self.invalidProductIDs = invalidProductIDs
self.error = error
}
}
/// Purchase result
public enum PurchaseResult {
case success(purchase: PurchaseDetails)
case deferred(purchase: PurchaseDetails)
case error(error: SKError)
}
/// Restore purchase results
public struct RestoreResults {
public let restoredPurchases: [Purchase]
public let restoreFailedPurchases: [(SKError, String?)]
public init(restoredPurchases: [Purchase], restoreFailedPurchases: [(SKError, String?)]) {
self.restoredPurchases = restoredPurchases
self.restoreFailedPurchases = restoreFailedPurchases
}
}
public typealias ShouldAddStorePaymentHandler = (_ payment: SKPayment, _ product: SKProduct) -> Bool
public typealias UpdatedDownloadsHandler = (_ downloads: [SKDownload]) -> Void
// MARK: Receipt verification
/// Info for receipt returned by server
public typealias ReceiptInfo = [String: AnyObject]
/// Fetch receipt result
public enum FetchReceiptResult {
case success(receiptData: Data)
case error(error: ReceiptError)
}
/// Verify receipt result
public enum VerifyReceiptResult {
case success(receipt: ReceiptInfo)
case error(error: ReceiptError)
}
/// Result for Consumable and NonConsumable
public enum VerifyPurchaseResult {
case purchased(item: ReceiptItem)
case notPurchased
}
/// Verify subscription result
public enum VerifySubscriptionResult {
case purchased(expiryDate: Date, items: [ReceiptItem])
case expired(expiryDate: Date, items: [ReceiptItem])
case notPurchased
}
public enum SubscriptionType: Hashable {
case autoRenewable
case nonRenewing(validDuration: TimeInterval)
}
public struct ReceiptItem: Purchased, Codable {
/// The product identifier of the item that was purchased. This value corresponds to the `productIdentifier` property of the `SKPayment` object stored in the transaction’s payment property.
public var productId: String
/// The number of items purchased. This value corresponds to the `quantity` property of the `SKPayment` object stored in the transaction’s payment property.
public var quantity: Int
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s `transactionIdentifier` property.
public var transactionId: String
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction.
///
/// Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s `transactionIdentifier` property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
public var originalTransactionId: String
/// The date and time that the item was purchased. This value corresponds to the transaction’s `transactionDate` property.
public var purchaseDate: Date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s `transactionDate` property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
public var originalPurchaseDate: Date
/// The primary key for identifying subscription purchases.
public var webOrderLineItemId: String?
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is **only** present for **auto-renewable** subscription receipts.
public var subscriptionExpirationDate: Date?
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation.
///
/// Treat a canceled receipt the same as if no purchase had ever been made.
public var cancellationDate: Date?
/// Indicates whether or not the subscription item is currently within a given trial period.
public var isTrialPeriod: Bool
/// Indicates whether or not the subscription item is currently within an intro offer period.
public var isInIntroOfferPeriod: Bool
/// An indicator that a subscription has been canceled due to an upgrade. This field is only present for upgrade transactions.
public var isUpgraded: Bool
public init(productId: String, quantity: Int, transactionId: String, originalTransactionId: String, purchaseDate: Date, originalPurchaseDate: Date, webOrderLineItemId: String?, subscriptionExpirationDate: Date?, cancellationDate: Date?, isTrialPeriod: Bool, isInIntroOfferPeriod: Bool, isUpgraded: Bool) {
self.productId = productId
self.quantity = quantity
self.transactionId = transactionId
self.originalTransactionId = originalTransactionId
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.webOrderLineItemId = webOrderLineItemId
self.subscriptionExpirationDate = subscriptionExpirationDate
self.cancellationDate = cancellationDate
self.isTrialPeriod = isTrialPeriod
self.isInIntroOfferPeriod = isInIntroOfferPeriod
self.isUpgraded = isUpgraded
}
}
/// Error when managing receipt
public enum ReceiptError: Swift.Error {
/// No receipt data
case noReceiptData
/// No data received
case noRemoteData
/// Error when encoding HTTP body into JSON
case requestBodyEncodeError(error: Swift.Error)
/// Error when proceeding request
case networkError(error: Swift.Error)
/// Error when decoding response
case jsonDecodeError(string: String?)
/// Receive invalid - bad status returned
case receiptInvalid(receipt: ReceiptInfo, status: ReceiptStatus)
}
/// Status code returned by remote server
///
/// See Table 2-1 Status codes
public enum ReceiptStatus: Int {
/// Not decodable status
case unknown = -2
/// No status returned
case none = -1
/// valid statua
case valid = 0
/// The App Store could not read the JSON object you provided.
case jsonNotReadable = 21000
/// The data in the receipt-data property was malformed or missing.
case malformedOrMissingData = 21002
/// The receipt could not be authenticated.
case receiptCouldNotBeAuthenticated = 21003
/// The shared secret you provided does not match the shared secret on file for your account.
case secretNotMatching = 21004
/// The receipt server is not currently available.
case receiptServerUnavailable = 21005
/// This receipt is valid but the subscription has expired. When this status code is returned to your server, the receipt data is also decoded and returned as part of the response.
case subscriptionExpired = 21006
/// This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.
case testReceipt = 21007
/// This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.
case productionEnvironment = 21008
var isValid: Bool { return self == .valid}
}
// Receipt field as defined in : https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1
public enum ReceiptInfoField: String {
/// Bundle Identifier. This corresponds to the value of CFBundleIdentifier in the Info.plist file.
case bundle_id
/// The app’s version number.This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist.
case application_version
/// The version of the app that was originally purchased. This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist file when the purchase was originally made.
case original_application_version
/// The date when the app receipt was created.
case creation_date
/// The date that the app receipt expires. This key is present only for apps purchased through the Volume Purchase Program.
case expiration_date
/// The receipt for an in-app purchase.
case in_app
public enum InApp: String {
/// The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property.
case quantity
/// The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the SKPayment object stored in the transaction’s payment property.
case product_id
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s transactionIdentifier property.
case transaction_id
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction. Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s transactionIdentifier property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
case original_transaction_id
/// The date and time that the item was purchased. This value corresponds to the transaction’s transactionDate property.
case purchase_date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s transactionDate property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
case original_purchase_date
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is only present for auto-renewable subscription receipts.
case expires_date
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation. Treat a canceled receipt the same as if no purchase had ever been made.
case cancellation_date
#if os(iOS) || os(tvOS)
/// A string that the App Store uses to uniquely identify the application that created the transaction. If your server supports multiple applications, you can use this value to differentiate between them. Apps are assigned an identifier only in the production environment, so this key is not present for receipts created in the test environment. This field is not present for Mac apps. See also Bundle Identifier.
case app_item_id
#endif
/// An arbitrary number that uniquely identifies a revision of your application. This key is not present for receipts created in the test environment.
case version_external_identifier
/// The primary key for identifying subscription purchases.
case web_order_line_item_id
}
}
#if os(OSX)
public enum ReceiptExitCode: Int32 {
/// If validation fails in OS X, call exit with a status of 173. This exit status notifies the system that your application has determined that its receipt is invalid. At this point, the system attempts to obtain a valid receipt and may prompt for the user’s iTunes credentials
case notValid = 173
}
#endif
================================================
FILE: Sources/SwiftyStoreKit/SwiftyStoreKit.swift
================================================
//
// SwiftyStoreKit.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
public class SwiftyStoreKit {
private let productsInfoController: ProductsInfoController
fileprivate let paymentQueueController: PaymentQueueController
fileprivate let receiptVerificator: InAppReceiptVerificator
init(productsInfoController: ProductsInfoController = ProductsInfoController(),
paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()),
receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) {
self.productsInfoController = productsInfoController
self.paymentQueueController = paymentQueueController
self.receiptVerificator = receiptVerificator
}
// MARK: private methods
fileprivate func retrieveProductsInfo(_ productIds: Set, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
return productsInfoController.retrieveProductsInfo(productIds, completion: completion)
}
fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) -> InAppProductRequest {
return retrieveProductsInfo(Set([productId])) { result -> Void in
if let product = result.retrievedProducts.first {
self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
} else if let error = result.error {
completion(.error(error: SKError(_nsError: error as NSError)))
} else if let invalidProductId = result.invalidProductIDs.first {
let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ]
let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo)
completion(.error(error: SKError(_nsError: error)))
} else {
let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil)
completion(.error(error: SKError(_nsError: error)))
}
}
}
fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping (PurchaseResult) -> Void) {
paymentQueueController.startPayment(Payment(product: product, paymentDiscount: paymentDiscount, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in
completion(self.processPurchaseResult(result))
})
}
fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in
let results = self.processRestoreResults(results)
completion(results)
})
}
fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion))
}
fileprivate func onEntitlementRevocation(completion: @escaping ([String]) -> Void) {
paymentQueueController.onEntitlementRevocation(EntitlementRevocation(callback: completion))
}
fileprivate func finishTransaction(_ transaction: PaymentTransaction) {
paymentQueueController.finishTransaction(transaction)
}
private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult {
switch result {
case .purchased(let purchase):
return .success(purchase: purchase)
case .deferred(let purchase):
return .deferred(purchase: purchase)
case .failed(let error):
return .error(error: error)
case .restored(let purchase):
return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path"))
}
}
private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults {
var restoredPurchases: [Purchase] = []
var restoreFailedPurchases: [(SKError, String?)] = []
for result in results {
switch result {
case .purchased(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .deferred(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .failed(let error):
restoreFailedPurchases.append((error, nil))
case .restored(let purchase):
restoredPurchases.append(purchase)
}
}
return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases)
}
private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError {
let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ])
return SKError(_nsError: error)
}
}
extension SwiftyStoreKit {
// MARK: Singleton
fileprivate static let sharedInstance = SwiftyStoreKit()
// MARK: Public methods - Purchases
/// Check if the current device can make payments.
/// - returns: `false` if this device is not able or allowed to make payments
public class var canMakePayments: Bool {
return SKPaymentQueue.canMakePayments()
}
/// Retrieve products information
/// - Parameter productIds: The set of product identifiers to retrieve corresponding products for
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func retrieveProductsInfo(_ productIds: Set, completion: @escaping (RetrieveResults) -> Void) -> InAppRequest {
return sharedInstance.retrieveProductsInfo(productIds, completion: completion)
}
/// Purchase a product
/// - Parameter productId: productId as specified in App Store Connect
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) -> InAppRequest {
return sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
}
/// Purchase a product
/// - Parameter product: product to be purchased
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter product: optional discount to be applied. Must be of `SKProductPayment` type
/// - Parameter completion: handler for result
public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping ( PurchaseResult) -> Void) {
sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, paymentDiscount: paymentDiscount, completion: completion)
}
/// Restore purchases
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion)
}
/// Complete transactions
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter completion: handler for result
public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
sharedInstance.completeTransactions(atomically: atomically, completion: completion)
}
/// Entitlement revocation notification
/// - Parameter completion: handler for result (list of product identifiers revoked)
@available(iOS 14, tvOS 14, OSX 11, watchOS 7, macCatalyst 14, *)
public class func onEntitlementRevocation(completion: @escaping ([String]) -> Void) {
sharedInstance.onEntitlementRevocation(completion: completion)
}
/// Finish a transaction
///
/// Once the content has been delivered, call this method to finish a transaction that was performed non-atomically
/// - Parameter transaction: transaction to finish
public class func finishTransaction(_ transaction: PaymentTransaction) {
sharedInstance.finishTransaction(transaction)
}
/// Register a handler for `SKPaymentQueue.shouldAddStorePayment` delegate method.
/// - requires: iOS 11.0+
public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? {
didSet {
sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler
}
}
/// Register a handler for `paymentQueue(_:updatedDownloads:)`
/// - seealso: `paymentQueue(_:updatedDownloads:)`
public static var updatedDownloadsHandler: UpdatedDownloadsHandler? {
didSet {
sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler
}
}
public class func start(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.start(downloads)
}
public class func pause(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.pause(downloads)
}
public class func resume(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.resume(downloads)
}
public class func cancel(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.cancel(downloads)
}
}
extension SwiftyStoreKit {
// MARK: Public methods - Receipt verification
/// Return receipt data from the application bundle. This is read from `Bundle.main.appStoreReceiptURL`.
public static var localReceiptData: Data? {
return sharedInstance.receiptVerificator.appStoreReceiptData
}
/// Verify application receipt
/// - Parameter validator: receipt validator to use
/// - Parameter forceRefresh: If `true`, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion)
}
/// Fetch application receipt
/// - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion)
}
/// Verify the purchase of a Consumable or NonConsumable product in a receipt
/// - Parameter productId: the product id of the purchase to verify
/// - Parameter inReceipt: the receipt to use for looking up the purchase
/// - returns: A `VerifyPurchaseResult`, which may be either `notPurchased` or `purchased`.
public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult {
return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt)
}
/**
* Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt.
*
* This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity.
* - Parameter type: `.autoRenewable` or `.nonRenewing`.
* - Parameter productId: The product id of the subscription to verify.
* - Parameter receipt: The receipt to use for looking up the subscription.
* - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date)
}
/**
* Verify the validity of a set of subscriptions in a receipt.
*
* This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity.
* - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
* - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results.
* - Parameter type: `.autoRenewable` or `.nonRenewing`.
* - Parameter productIds: The product IDs of the subscriptions to verify.
* - Parameter receipt: The receipt to use for looking up the subscriptions
* - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date)
}
/// Get the distinct product identifiers from receipt.
///
/// This Method extracts all product identifiers. (Including cancelled ones).
/// - Note: You can use this method to get all unique product identifiers from receipt.
/// - Parameter type: `.autoRenewable` or `.nonRenewing`.
/// - Parameter receipt: The receipt to use for looking up product identifiers.
/// - returns: Either `Set` or `nil`.
public class func getDistinctPurchaseIds(ofType type: SubscriptionType = .autoRenewable, inReceipt receipt: ReceiptInfo) -> Set? {
return InAppReceipt.getDistinctPurchaseIds(ofType: type, inReceipt: receipt)
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/AppDelegate.swift
================================================
//
// AppDelegate.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 03/09/2015.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 UIKit
import SwiftyStoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
setupIAP()
return true
}
func setupIAP() {
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
let downloads = purchase.transaction.downloads
if !downloads.isEmpty {
SwiftyStoreKit.start(downloads)
} else if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("\(purchase.transaction.transactionState.debugDescription): \(purchase.productId)")
case .failed, .purchasing, .deferred:
break // do nothing
@unknown default:
break // do nothing
}
}
}
SwiftyStoreKit.updatedDownloadsHandler = { downloads in
// contentURL is not nil if downloadState == .finished
let contentURLs = downloads.compactMap { $0.contentURL }
if contentURLs.count == downloads.count {
print("Saving: \(contentURLs)")
SwiftyStoreKit.finishTransaction(downloads[0].transaction)
}
}
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/Assets.xcassets/Background.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "universal",
"filename" : "Background.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/Assets.xcassets/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/Base.lproj/LaunchScreen.storyboard
================================================
================================================
FILE: SwiftyStoreKit-iOS-Demo/Base.lproj/Main.storyboard
================================================
================================================
FILE: SwiftyStoreKit-iOS-Demo/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
1
LSRequiresIPhoneOS
UILaunchStoryboardName
LaunchScreen
UIMainStoryboardFile
Main
UIRequiredDeviceCapabilities
armv7
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIViewControllerBasedStatusBarAppearance
================================================
FILE: SwiftyStoreKit-iOS-Demo/NetworkActivityIndicatorManager.swift
================================================
//
// NetworkActivityIndicatorManager.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 28/09/2015.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 UIKit
class NetworkActivityIndicatorManager: NSObject {
private static var loadingCount = 0
class func networkOperationStarted() {
#if os(iOS)
if loadingCount == 0 {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
loadingCount += 1
#endif
}
class func networkOperationFinished() {
#if os(iOS)
if loadingCount > 0 {
loadingCount -= 1
}
if loadingCount == 0 {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
#endif
}
}
================================================
FILE: SwiftyStoreKit-iOS-Demo/ViewController.swift
================================================
//
// ViewController.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 03/09/2015.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 UIKit
import StoreKit
import SwiftyStoreKit
enum RegisteredPurchase: String {
case purchase1
case purchase2
case nonConsumablePurchase
case consumablePurchase
case nonRenewingPurchase
case autoRenewableWeekly
case autoRenewableMonthly
case autoRenewableYearly
}
class ViewController: UIViewController {
let appBundleId = "com.musevisions.iOS.SwiftyStoreKit"
#if os(iOS)
// UISwitch is unavailable on tvOS
@IBOutlet var nonConsumableAtomicSwitch: UISwitch!
@IBOutlet var consumableAtomicSwitch: UISwitch!
@IBOutlet var nonRenewingAtomicSwitch: UISwitch!
@IBOutlet var autoRenewableAtomicSwitch: UISwitch!
var nonConsumableIsAtomic: Bool { return nonConsumableAtomicSwitch.isOn }
var consumableIsAtomic: Bool { return consumableAtomicSwitch.isOn }
var nonRenewingIsAtomic: Bool { return nonRenewingAtomicSwitch.isOn }
var autoRenewableIsAtomic: Bool { return autoRenewableAtomicSwitch.isOn }
#else
let nonConsumableIsAtomic = true
let consumableIsAtomic = true
let nonRenewingIsAtomic = true
let autoRenewableIsAtomic = true
#endif
// MARK: non consumable
@IBAction func nonConsumableGetInfo() {
getInfo(.nonConsumablePurchase)
}
@IBAction func nonConsumablePurchase() {
purchase(.nonConsumablePurchase, atomically: nonConsumableIsAtomic)
}
@IBAction func nonConsumableVerifyPurchase() {
verifyPurchase(.nonConsumablePurchase)
}
// MARK: consumable
@IBAction func consumableGetInfo() {
getInfo(.consumablePurchase)
}
@IBAction func consumablePurchase() {
purchase(.consumablePurchase, atomically: consumableIsAtomic)
}
@IBAction func consumableVerifyPurchase() {
verifyPurchase(.consumablePurchase)
}
// MARK: non renewing
@IBAction func nonRenewingGetInfo() {
getInfo(.nonRenewingPurchase)
}
@IBAction func nonRenewingPurchase() {
purchase(.nonRenewingPurchase, atomically: nonRenewingIsAtomic)
}
@IBAction func nonRenewingVerifyPurchase() {
verifyPurchase(.nonRenewingPurchase)
}
// MARK: auto renewable
#if os(iOS)
@IBOutlet var autoRenewableSubscriptionSegmentedControl: UISegmentedControl!
var autoRenewableSubscription: RegisteredPurchase {
switch autoRenewableSubscriptionSegmentedControl.selectedSegmentIndex {
case 0: return .autoRenewableWeekly
case 1: return .autoRenewableMonthly
case 2: return .autoRenewableYearly
default: return .autoRenewableWeekly
}
}
#else
let autoRenewableSubscription = RegisteredPurchase.autoRenewableWeekly
#endif
@IBAction func autoRenewableGetInfo() {
getInfo(autoRenewableSubscription)
}
@IBAction func autoRenewablePurchase() {
purchase(autoRenewableSubscription, atomically: autoRenewableIsAtomic)
}
@IBAction func autoRenewableVerifyPurchase() {
verifySubscriptions([.autoRenewableWeekly, .autoRenewableMonthly, .autoRenewableYearly])
}
func getInfo(_ purchase: RegisteredPurchase) {
NetworkActivityIndicatorManager.networkOperationStarted()
SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
NetworkActivityIndicatorManager.networkOperationFinished()
self.showAlert(self.alertForProductRetrievalInfo(result))
}
}
func purchase(_ purchase: RegisteredPurchase, atomically: Bool) {
NetworkActivityIndicatorManager.networkOperationStarted()
SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: atomically) { result in
NetworkActivityIndicatorManager.networkOperationFinished()
if case .success(let purchase) = result {
let downloads = purchase.transaction.downloads
if !downloads.isEmpty {
SwiftyStoreKit.start(downloads)
}
// Deliver content from server, then:
if purchase.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
}
if let alert = self.alertForPurchaseResult(result) {
self.showAlert(alert)
}
}
}
@IBAction func restorePurchases() {
NetworkActivityIndicatorManager.networkOperationStarted()
SwiftyStoreKit.restorePurchases(atomically: true) { results in
NetworkActivityIndicatorManager.networkOperationFinished()
for purchase in results.restoredPurchases {
let downloads = purchase.transaction.downloads
if !downloads.isEmpty {
SwiftyStoreKit.start(downloads)
} else if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
}
self.showAlert(self.alertForRestorePurchases(results))
}
}
@IBAction func verifyReceipt() {
NetworkActivityIndicatorManager.networkOperationStarted()
verifyReceipt { result in
NetworkActivityIndicatorManager.networkOperationFinished()
self.showAlert(self.alertForVerifyReceipt(result))
}
}
func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) {
let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: completion)
}
func verifyPurchase(_ purchase: RegisteredPurchase) {
NetworkActivityIndicatorManager.networkOperationStarted()
verifyReceipt { result in
NetworkActivityIndicatorManager.networkOperationFinished()
switch result {
case .success(let receipt):
let productId = self.appBundleId + "." + purchase.rawValue
switch purchase {
case .autoRenewableWeekly, .autoRenewableMonthly, .autoRenewableYearly:
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable,
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: [productId]))
case .nonRenewingPurchase:
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .nonRenewing(validDuration: 60),
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: [productId]))
default:
let purchaseResult = SwiftyStoreKit.verifyPurchase(
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifyPurchase(purchaseResult, productId: productId))
}
case .error:
self.showAlert(self.alertForVerifyReceipt(result))
}
}
}
func verifySubscriptions(_ purchases: Set) {
NetworkActivityIndicatorManager.networkOperationStarted()
verifyReceipt { result in
NetworkActivityIndicatorManager.networkOperationFinished()
switch result {
case .success(let receipt):
let productIds = Set(purchases.map { self.appBundleId + "." + $0.rawValue })
let purchaseResult = SwiftyStoreKit.verifySubscriptions(productIds: productIds, inReceipt: receipt)
self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: productIds))
case .error:
self.showAlert(self.alertForVerifyReceipt(result))
}
}
}
#if os(iOS)
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
#endif
}
// MARK: User facing alerts
extension ViewController {
func alertWithTitle(_ title: String, message: String) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
return alert
}
func showAlert(_ alert: UIAlertController) {
guard self.presentedViewController != nil else {
self.present(alert, animated: true, completion: nil)
return
}
}
func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController {
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
} else if let invalidProductId = result.invalidProductIDs.first {
return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
} else {
let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
return alertWithTitle("Could not retrieve product info", message: errorString)
}
}
// swiftlint:disable cyclomatic_complexity
func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? {
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
return nil
case .error(let error):
print("Purchase Failed: \(error)")
switch error.code {
case .unknown: return alertWithTitle("Purchase failed", message: error.localizedDescription)
case .clientInvalid: // client is not allowed to issue the request, etc.
return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
case .paymentCancelled: // user cancelled the request, etc.
return nil
case .paymentInvalid: // purchase identifier was invalid, etc.
return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
case .paymentNotAllowed: // this device is not allowed to make the payment
return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
case .storeProductNotAvailable: // Product is not available in the current storefront
return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront")
case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
return alertWithTitle("Purchase failed", message: "Could not connect to the network")
case .cloudServiceRevoked: // user has revoked permission to use this cloud service
return alertWithTitle("Purchase failed", message: "Cloud service was revoked")
default:
return alertWithTitle("Purchase failed", message: (error as NSError).localizedDescription)
}
}
}
func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
} else if results.restoredPurchases.count > 0 {
print("Restore Success: \(results.restoredPurchases)")
return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
} else {
print("Nothing to Restore")
return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
}
}
func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
switch result {
case .success(let receipt):
print("Verify receipt Success: \(receipt)")
return alertWithTitle("Receipt verified", message: "Receipt verified remotely")
case .error(let error):
print("Verify receipt Failed: \(error)")
switch error {
case .noReceiptData:
return alertWithTitle("Receipt verification", message: "No receipt data. Try again.")
case .networkError(let error):
return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
default:
return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
}
}
}
func alertForVerifySubscriptions(_ result: VerifySubscriptionResult, productIds: Set) -> UIAlertController {
switch result {
case .purchased(let expiryDate, let items):
print("\(productIds) is valid until \(expiryDate)\n\(items)\n")
return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)")
case .expired(let expiryDate, let items):
print("\(productIds) is expired since \(expiryDate)\n\(items)\n")
return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)")
case .notPurchased:
print("\(productIds) has never been purchased")
return alertWithTitle("Not purchased", message: "This product has never been purchased")
}
}
func alertForVerifyPurchase(_ result: VerifyPurchaseResult, productId: String) -> UIAlertController {
switch result {
case .purchased:
print("\(productId) is purchased")
return alertWithTitle("Product is purchased", message: "Product will not expire")
case .notPurchased:
print("\(productId) has never been purchased")
return alertWithTitle("Not purchased", message: "This product has never been purchased")
}
}
}
================================================
FILE: SwiftyStoreKit-macOS-Demo/AppDelegate.swift
================================================
//
// AppDelegate.swift
// SwiftStoreOSXDemo
//
// Created by phimage on 22/12/15.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 Cocoa
import SwiftyStoreKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
completeIAPTransactions()
}
func completeIAPTransactions() {
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("\(purchase.transaction.transactionState.debugDescription): \(purchase.productId)")
case .failed, .purchasing, .deferred:
break // do nothing
@unknown default:
break // do nothing
}
}
}
}
}
================================================
FILE: SwiftyStoreKit-macOS-Demo/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-macOS-Demo/Assets.xcassets/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-macOS-Demo/Base.lproj/Main.storyboard
================================================
================================================
FILE: SwiftyStoreKit-macOS-Demo/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIconFile
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
1
LSMinimumSystemVersion
$(MACOSX_DEPLOYMENT_TARGET)
NSHumanReadableCopyright
Copyright © 2015 musevisions. All rights reserved.
NSMainStoryboardFile
Main
NSPrincipalClass
NSApplication
================================================
FILE: SwiftyStoreKit-macOS-Demo/ViewController.swift
================================================
//
// ViewController.swift
// SwiftStoreOSXDemo
//
// Created by phimage on 22/12/15.
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 Cocoa
import StoreKit
import SwiftyStoreKit
enum RegisteredPurchase: String {
case purchase1
case purchase2
case nonConsumablePurchase
case consumablePurchase
case autoRenewablePurchase
case nonRenewingPurchase
}
class ViewController: NSViewController {
let appBundleId = "com.musevisions.MacOS.SwiftyStoreKitDemo"
let purchase1Suffix = RegisteredPurchase.purchase1
let purchase2Suffix = RegisteredPurchase.autoRenewablePurchase
// MARK: actions
@IBAction func getInfo1(_ sender: Any?) {
getInfo(purchase1Suffix)
}
@IBAction func purchase1(_ sender: Any?) {
purchase(purchase1Suffix)
}
@IBAction func verifyPurchase1(_ sender: Any?) {
verifyPurchase(purchase1Suffix)
}
@IBAction func getInfo2(_ sender: Any?) {
getInfo(purchase2Suffix)
}
@IBAction func purchase2(_ sender: Any?) {
purchase(purchase2Suffix)
}
@IBAction func verifyPurchase2(_ sender: Any?) {
verifyPurchase(purchase2Suffix)
}
func getInfo(_ purchase: RegisteredPurchase) {
SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
self.showAlert(self.alertForProductRetrievalInfo(result))
}
}
func purchase(_ purchase: RegisteredPurchase) {
SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: true) { result in
if case .success(let purchase) = result {
// Deliver content from server, then:
if purchase.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
}
if let errorAlert = self.alertForPurchaseResult(result) {
self.showAlert(errorAlert)
}
}
}
@IBAction func restorePurchases(_ sender: Any?) {
SwiftyStoreKit.restorePurchases(atomically: true) { results in
for purchase in results.restoredPurchases where purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
self.showAlert(self.alertForRestorePurchases(results))
}
}
@IBAction func verifyReceipt(_ sender: Any?) {
verifyReceipt(completion: { result in
self.showAlert(self.alertForVerifyReceipt(result))
})
}
func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) {
let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: completion)
}
func verifyPurchase(_ purchase: RegisteredPurchase) {
verifyReceipt { result in
switch result {
case .success(let receipt):
let productId = self.appBundleId + "." + purchase.rawValue
switch purchase {
case .autoRenewablePurchase:
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable,
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifySubscription(purchaseResult))
case .nonRenewingPurchase:
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .nonRenewing(validDuration: 60),
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifySubscription(purchaseResult))
default:
let purchaseResult = SwiftyStoreKit.verifyPurchase(
productId: productId,
inReceipt: receipt)
self.showAlert(self.alertForVerifyPurchase(purchaseResult))
}
case .error:
self.showAlert(self.alertForVerifyReceipt(result))
}
}
}
}
// MARK: User facing alerts
extension ViewController {
func alertWithTitle(_ title: String, message: String) -> NSAlert {
let alert: NSAlert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.alertStyle = .informational
return alert
}
func showAlert(_ alert: NSAlert, handler: ((NSApplication.ModalResponse) -> Void)? = nil) {
if let window = NSApplication.shared.keyWindow {
alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in
handler?(response)
}
} else {
let response = alert.runModal()
handler?(response)
}
}
func alertForProductRetrievalInfo(_ result: RetrieveResults) -> NSAlert {
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
} else if let invalidProductId = result.invalidProductIDs.first {
return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
} else {
let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
return alertWithTitle("Could not retrieve product info", message: errorString)
}
}
func alertForPurchaseResult(_ result: PurchaseResult) -> NSAlert? {
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
return alertWithTitle("Thank You", message: "Purchase completed")
case .error(let error):
print("Purchase Failed: \(error)")
switch error.code {
case .unknown: return alertWithTitle("Purchase failed", message: error.localizedDescription)
case .clientInvalid: // client is not allowed to issue the request, etc.
return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
case .paymentCancelled: // user cancelled the request, etc.
return nil
case .paymentInvalid: // purchase identifier was invalid, etc.
return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
case .paymentNotAllowed: // this device is not allowed to make the payment
return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
default:
return alertWithTitle("Purchase failed", message: (error as NSError).localizedDescription)
}
}
}
func alertForRestorePurchases(_ results: RestoreResults) -> NSAlert {
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
} else if results.restoredPurchases.count > 0 {
print("Restore Success: \(results.restoredPurchases)")
return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
} else {
print("Nothing to Restore")
return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
}
}
func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> NSAlert {
switch result {
case .success(let receipt):
print("Verify receipt Success: \(receipt)")
return self.alertWithTitle("Receipt verified", message: "Receipt verified remotely")
case .error(let error):
print("Verify receipt Failed: \(error)")
switch error {
case .noReceiptData:
return alertWithTitle("Receipt verification", message: "No receipt data. Try again.")
case .networkError(let error):
return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
default:
return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
}
}
}
func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> NSAlert {
switch result {
case .purchased(let expiryDate):
print("Product is valid until \(expiryDate)")
return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)")
case .expired(let expiryDate):
print("Product is expired since \(expiryDate)")
return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)")
case .notPurchased:
print("This product has never been purchased")
return alertWithTitle("Not purchased", message: "This product has never been purchased")
}
}
func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> NSAlert {
switch result {
case .purchased:
print("Product is purchased")
return alertWithTitle("Product is purchased", message: "Product will not expire")
case .notPurchased:
print("This product has never been purchased")
return alertWithTitle("Not purchased", message: "This product has never been purchased")
}
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Back.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Back.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Contents.json
================================================
{
"layers" : [
{
"filename" : "Front.imagestacklayer"
},
{
"filename" : "Middle.imagestacklayer"
},
{
"filename" : "Back.imagestacklayer"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Front.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Front.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Large.imagestack/Middle.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Back.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Back.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Contents.json
================================================
{
"layers" : [
{
"filename" : "Front.imagestacklayer"
},
{
"filename" : "Middle.imagestacklayer"
},
{
"filename" : "Back.imagestacklayer"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Front.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Front.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Middle.imagestacklayer/Content.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/App Icon - Small.imagestack/Middle.imagestacklayer/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Contents.json
================================================
{
"assets" : [
{
"size" : "1280x768",
"idiom" : "tv",
"filename" : "App Icon - Large.imagestack",
"role" : "primary-app-icon"
},
{
"size" : "400x240",
"idiom" : "tv",
"filename" : "App Icon - Small.imagestack",
"role" : "primary-app-icon"
},
{
"size" : "2320x720",
"idiom" : "tv",
"filename" : "Top Shelf Image Wide.imageset",
"role" : "top-shelf-image-wide"
},
{
"size" : "1920x720",
"idiom" : "tv",
"filename" : "Top Shelf Image.imageset",
"role" : "top-shelf-image"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image Wide.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/App Icon & Top Shelf Image.brandassets/Top Shelf Image.imageset/Contents.json
================================================
{
"images" : [
{
"idiom" : "tv",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Assets.xcassets/LaunchImage.launchimage/Contents.json
================================================
{
"images" : [
{
"orientation" : "landscape",
"idiom" : "tv",
"extent" : "full-screen",
"minimum-system-version" : "9.0",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Base.lproj/Main.storyboard
================================================
================================================
FILE: SwiftyStoreKit-tvOS-Demo/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleVersion
1
LSRequiresIPhoneOS
UIMainStoryboardFile
Main
UIRequiredDeviceCapabilities
arm64
UIUserInterfaceStyle
Automatic
================================================
FILE: SwiftyStoreKit.podspec
================================================
Pod::Spec.new do |s|
s.name = 'SwiftyStoreKit'
s.version = '0.16.4'
s.summary = 'Lightweight In App Purchases Swift framework for iOS, tvOS, watchOS, macOS and Mac Catalyst.'
s.license = 'MIT'
s.homepage = 'https://github.com/bizz84/SwiftyStoreKit'
s.author = { 'Andrea Bizzotto' => 'bizz84@gmail.com' }
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '6.2'
s.swift_version = '5.0'
s.source = { :git => "https://github.com/bizz84/SwiftyStoreKit.git", :tag => s.version }
s.source_files = 'Sources/SwiftyStoreKit/*.{swift}'
s.screenshots = ["https://github.com/bizz84/SwiftyStoreKit/raw/master/Screenshots/Preview.jpg"]
s.requires_arc = true
end
================================================
FILE: SwiftyStoreKit.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
2F2B8B3024A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */; };
2F2B8B3124A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */; };
2F2B8B3224A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */; };
2F2B8B3324A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */; };
2F2B8B3424A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */; };
2F2B8B3524A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */; };
2F2B8B3624A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */; };
2F2B8B3724A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */; };
2F2B8B3824A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */; };
2F2B8B3924A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */; };
2F2B8B3A24A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */; };
2F2B8B3B24A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */; };
2F2B8B3C24A64CC100CEF088 /* InAppReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */; };
2F2B8B3D24A64CC100CEF088 /* InAppReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */; };
2F2B8B3E24A64CC100CEF088 /* InAppReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */; };
2F2B8B3F24A64CC100CEF088 /* InAppReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */; };
2F2B8B4024A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */; };
2F2B8B4124A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */; };
2F2B8B4224A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */; };
2F2B8B4324A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */; };
2F2B8B4424A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */; };
2F2B8B4524A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */; };
2F2B8B4624A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */; };
2F2B8B4724A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */; };
2F2B8B4824A64CC100CEF088 /* PaymentQueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */; };
2F2B8B4924A64CC100CEF088 /* PaymentQueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */; };
2F2B8B4A24A64CC100CEF088 /* PaymentQueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */; };
2F2B8B4B24A64CC100CEF088 /* PaymentQueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */; };
2F2B8B4C24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */; };
2F2B8B4D24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */; };
2F2B8B4E24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */; };
2F2B8B4F24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */; };
2F2B8B5024A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */; };
2F2B8B5124A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */; };
2F2B8B5224A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */; };
2F2B8B5324A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */; };
2F2B8B5424A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */; };
2F2B8B5524A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */; };
2F2B8B5624A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */; };
2F2B8B5724A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */; };
2F2B8B5824A64CC100CEF088 /* ProductsInfoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */; };
2F2B8B5924A64CC100CEF088 /* ProductsInfoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */; };
2F2B8B5A24A64CC100CEF088 /* ProductsInfoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */; };
2F2B8B5B24A64CC100CEF088 /* ProductsInfoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */; };
2F2B8B5C24A64CC100CEF088 /* OS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2C24A64CC100CEF088 /* OS.swift */; };
2F2B8B5D24A64CC100CEF088 /* OS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2C24A64CC100CEF088 /* OS.swift */; };
2F2B8B5E24A64CC100CEF088 /* OS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2C24A64CC100CEF088 /* OS.swift */; };
2F2B8B5F24A64CC100CEF088 /* OS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2C24A64CC100CEF088 /* OS.swift */; };
2F2B8B6024A64CC100CEF088 /* PaymentsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */; };
2F2B8B6124A64CC100CEF088 /* PaymentsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */; };
2F2B8B6224A64CC100CEF088 /* PaymentsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */; };
2F2B8B6324A64CC100CEF088 /* PaymentsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */; };
2F2B8B6424A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */; };
2F2B8B6524A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */; };
2F2B8B6624A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */; };
2F2B8B6724A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */; };
2F2B8B6824A64CC100CEF088 /* RestorePurchasesController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */; };
2F2B8B6924A64CC100CEF088 /* RestorePurchasesController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */; };
2F2B8B6A24A64CC100CEF088 /* RestorePurchasesController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */; };
2F2B8B6B24A64CC100CEF088 /* RestorePurchasesController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */; };
2F2B8B7424A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */; };
2F2B8B7524A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */; };
2F2B8B7624A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */; };
2F2B8B7724A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */; };
2F2B8B8424A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */; };
2F2B8B8524A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */; };
2F2B8B8624A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */; };
2F2B8B8724A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */; };
2F2B8B8824A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */; };
2F2B8B8924A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */; };
2F2B8B8A24A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */; };
2F2B8B8B24A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */; };
2F2B8B8C24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */; };
2F2B8B8D24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */; };
2F2B8B8E24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */; };
2F2B8B8F24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */; };
2F2B8BA024A64DE600CEF088 /* PaymentQueueControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9424A64DE600CEF088 /* PaymentQueueControllerTests.swift */; };
2F2B8BA124A64DE600CEF088 /* PaymentTransactionObserverFake.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9524A64DE600CEF088 /* PaymentTransactionObserverFake.swift */; };
2F2B8BA224A64DE600CEF088 /* ProductsInfoControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9624A64DE600CEF088 /* ProductsInfoControllerTests.swift */; };
2F2B8BA324A64DE600CEF088 /* TestPaymentTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9724A64DE600CEF088 /* TestPaymentTransaction.swift */; };
2F2B8BA424A64DE600CEF088 /* TestProduct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9824A64DE600CEF088 /* TestProduct.swift */; };
2F2B8BA524A64DE600CEF088 /* RestorePurchasesControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9924A64DE600CEF088 /* RestorePurchasesControllerTests.swift */; };
2F2B8BA624A64DE600CEF088 /* CompleteTransactionsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9A24A64DE600CEF088 /* CompleteTransactionsControllerTests.swift */; };
2F2B8BA724A64DE600CEF088 /* InAppReceiptVerificatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9B24A64DE600CEF088 /* InAppReceiptVerificatorTests.swift */; };
2F2B8BA824A64DE600CEF088 /* InAppReceiptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9C24A64DE600CEF088 /* InAppReceiptTests.swift */; };
2F2B8BA924A64DE600CEF088 /* PaymentsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9D24A64DE600CEF088 /* PaymentsControllerTests.swift */; };
2F2B8BAB24A64DE600CEF088 /* PaymentQueueSpy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F2B8B9F24A64DE600CEF088 /* PaymentQueueSpy.swift */; };
654287F61E79F5A000F61800 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 654287F41E79F5A000F61800 /* Main.storyboard */; };
654287F81E79F5A000F61800 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 654287F71E79F5A000F61800 /* Assets.xcassets */; };
654287FD1E79F75000F61800 /* SwiftyStoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 54C0D52C1CF7404500F90BCE /* SwiftyStoreKit.framework */; };
654287FE1E79F75000F61800 /* SwiftyStoreKit.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 54C0D52C1CF7404500F90BCE /* SwiftyStoreKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
654288021E7B34E500F61800 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF701DCD4DF000835D30 /* ViewController.swift */; };
654288061E7B3A8800F61800 /* NetworkActivityIndicatorManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF6F1DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift */; };
654288071E7B3E1500F61800 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF681DCD4DF000835D30 /* AppDelegate.swift */; };
658A08431E2EC5120074A98F /* SwiftyStoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */; };
65F7DF711DCD4DF000835D30 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF681DCD4DF000835D30 /* AppDelegate.swift */; };
65F7DF721DCD4DF000835D30 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 65F7DF691DCD4DF000835D30 /* Assets.xcassets */; };
65F7DF731DCD4DF000835D30 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 65F7DF6A1DCD4DF000835D30 /* LaunchScreen.storyboard */; };
65F7DF741DCD4DF000835D30 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 65F7DF6C1DCD4DF000835D30 /* Main.storyboard */; };
65F7DF761DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF6F1DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift */; };
65F7DF771DCD4DF000835D30 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF701DCD4DF000835D30 /* ViewController.swift */; };
65F7DF841DCD4FC500835D30 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF7E1DCD4FC500835D30 /* AppDelegate.swift */; };
65F7DF851DCD4FC500835D30 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 65F7DF7F1DCD4FC500835D30 /* Assets.xcassets */; };
65F7DF861DCD4FC500835D30 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 65F7DF801DCD4FC500835D30 /* Main.storyboard */; };
65F7DF881DCD4FC500835D30 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F7DF831DCD4FC500835D30 /* ViewController.swift */; };
65F7DF8E1DCD524300835D30 /* SwiftyStoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */; };
65F7DF8F1DCD524300835D30 /* SwiftyStoreKit.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
C4FD3A101C2954CD0035CFF3 /* SwiftyStoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C4D74BBB1C24CEC90071AD3E /* SwiftyStoreKit.framework */; };
C4FD3A111C2954CD0035CFF3 /* SwiftyStoreKit.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = C4D74BBB1C24CEC90071AD3E /* SwiftyStoreKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
654287FF1E79F75000F61800 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6502F5F61B985833004E342D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 54C0D52B1CF7404500F90BCE;
remoteInfo = SwiftyStoreKit_tvOS;
};
658A08441E2EC5120074A98F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6502F5F61B985833004E342D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 6502F62C1B985C40004E342D;
remoteInfo = SwiftyStoreKit_iOS;
};
658A084D1E2EC83F0074A98F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6502F5F61B985833004E342D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 6502F5FD1B985833004E342D;
remoteInfo = SwiftyStoreKit_iOSDemo;
};
65F7DF901DCD524300835D30 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6502F5F61B985833004E342D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 6502F62C1B985C40004E342D;
remoteInfo = SwiftyStoreKit_iOS;
};
C4FD3A121C2954CD0035CFF3 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6502F5F61B985833004E342D /* Project object */;
proxyType = 1;
remoteGlobalIDString = C4D74BBA1C24CEC90071AD3E;
remoteInfo = SwiftyStoreKitOSX;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
654288011E79F75100F61800 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
654287FE1E79F75000F61800 /* SwiftyStoreKit.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
65F7DF921DCD524300835D30 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
65F7DF8F1DCD524300835D30 /* SwiftyStoreKit.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
C4FD3A141C2954CD0035CFF3 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
C4FD3A111C2954CD0035CFF3 /* SwiftyStoreKit.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "SKProductDiscount+LocalizedPrice.swift"; path = "Sources/SwiftyStoreKit/SKProductDiscount+LocalizedPrice.swift"; sourceTree = SOURCE_ROOT; };
2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AppleReceiptValidator.swift; path = Sources/SwiftyStoreKit/AppleReceiptValidator.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 4; lastKnownFileType = sourcecode.swift; name = InAppProductQueryRequest.swift; path = Sources/SwiftyStoreKit/InAppProductQueryRequest.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InAppReceipt.swift; path = Sources/SwiftyStoreKit/InAppReceipt.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "SwiftyStoreKit+Types.swift"; path = "Sources/SwiftyStoreKit/SwiftyStoreKit+Types.swift"; sourceTree = SOURCE_ROOT; };
2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CompleteTransactionsController.swift; path = Sources/SwiftyStoreKit/CompleteTransactionsController.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentQueueController.swift; path = Sources/SwiftyStoreKit/PaymentQueueController.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InAppReceiptRefreshRequest.swift; path = Sources/SwiftyStoreKit/InAppReceiptRefreshRequest.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InAppReceiptVerificator.swift; path = Sources/SwiftyStoreKit/InAppReceiptVerificator.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "SKProduct+LocalizedPrice.swift"; path = "Sources/SwiftyStoreKit/SKProduct+LocalizedPrice.swift"; sourceTree = SOURCE_ROOT; };
2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 4; lastKnownFileType = sourcecode.swift; name = ProductsInfoController.swift; path = Sources/SwiftyStoreKit/ProductsInfoController.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2C24A64CC100CEF088 /* OS.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OS.swift; path = Sources/SwiftyStoreKit/OS.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentsController.swift; path = Sources/SwiftyStoreKit/PaymentsController.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftyStoreKit.swift; path = Sources/SwiftyStoreKit/SwiftyStoreKit.swift; sourceTree = SOURCE_ROOT; };
2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RestorePurchasesController.swift; path = Sources/SwiftyStoreKit/RestorePurchasesController.swift; sourceTree = SOURCE_ROOT; };
2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "SwiftyStoreKit-watchOS.h"; path = "Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-watchOS.h"; sourceTree = SOURCE_ROOT; };
2F2B8B6D24A64CD700CEF088 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; name = "Info-macOS.plist"; path = "Sources/SwiftyStoreKit/Platforms/Info-macOS.plist"; sourceTree = SOURCE_ROOT; };
2F2B8B6E24A64CD700CEF088 /* Info-watchOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; name = "Info-watchOS.plist"; path = "Sources/SwiftyStoreKit/Platforms/Info-watchOS.plist"; sourceTree = SOURCE_ROOT; };
2F2B8B6F24A64CD700CEF088 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; name = "Info-iOS.plist"; path = "Sources/SwiftyStoreKit/Platforms/Info-iOS.plist"; sourceTree = SOURCE_ROOT; };
2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "SwiftyStoreKit-tvOS.h"; path = "Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-tvOS.h"; sourceTree = SOURCE_ROOT; };
2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "SwiftyStoreKit-iOS.h"; path = "Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-iOS.h"; sourceTree = SOURCE_ROOT; };
2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "SwiftyStoreKit-macOS.h"; path = "Sources/SwiftyStoreKit/Platforms/SwiftyStoreKit-macOS.h"; sourceTree = SOURCE_ROOT; };
2F2B8B7324A64CD700CEF088 /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; name = "Info-tvOS.plist"; path = "Sources/SwiftyStoreKit/Platforms/Info-tvOS.plist"; sourceTree = SOURCE_ROOT; };
2F2B8B9424A64DE600CEF088 /* PaymentQueueControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentQueueControllerTests.swift; path = Tests/SwiftyStoreKitTests/PaymentQueueControllerTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9524A64DE600CEF088 /* PaymentTransactionObserverFake.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentTransactionObserverFake.swift; path = Tests/SwiftyStoreKitTests/PaymentTransactionObserverFake.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9624A64DE600CEF088 /* ProductsInfoControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ProductsInfoControllerTests.swift; path = Tests/SwiftyStoreKitTests/ProductsInfoControllerTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9724A64DE600CEF088 /* TestPaymentTransaction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TestPaymentTransaction.swift; path = Tests/SwiftyStoreKitTests/TestPaymentTransaction.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9824A64DE600CEF088 /* TestProduct.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TestProduct.swift; path = Tests/SwiftyStoreKitTests/TestProduct.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9924A64DE600CEF088 /* RestorePurchasesControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RestorePurchasesControllerTests.swift; path = Tests/SwiftyStoreKitTests/RestorePurchasesControllerTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9A24A64DE600CEF088 /* CompleteTransactionsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CompleteTransactionsControllerTests.swift; path = Tests/SwiftyStoreKitTests/CompleteTransactionsControllerTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9B24A64DE600CEF088 /* InAppReceiptVerificatorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InAppReceiptVerificatorTests.swift; path = Tests/SwiftyStoreKitTests/InAppReceiptVerificatorTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9C24A64DE600CEF088 /* InAppReceiptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = InAppReceiptTests.swift; path = Tests/SwiftyStoreKitTests/InAppReceiptTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9D24A64DE600CEF088 /* PaymentsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentsControllerTests.swift; path = Tests/SwiftyStoreKitTests/PaymentsControllerTests.swift; sourceTree = SOURCE_ROOT; };
2F2B8B9E24A64DE600CEF088 /* Info-Tests.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "Info-Tests.plist"; path = "Tests/SwiftyStoreKitTests/Info-Tests.plist"; sourceTree = SOURCE_ROOT; };
2F2B8B9F24A64DE600CEF088 /* PaymentQueueSpy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PaymentQueueSpy.swift; path = Tests/SwiftyStoreKitTests/PaymentQueueSpy.swift; sourceTree = SOURCE_ROOT; };
54C0D52C1CF7404500F90BCE /* SwiftyStoreKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyStoreKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
6502F5FE1B985833004E342D /* SwiftyStoreKit_iOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftyStoreKit_iOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyStoreKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
654287EE1E79F5A000F61800 /* SwiftyStoreKit_tvOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftyStoreKit_tvOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
654287F51E79F5A000F61800 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
654287F71E79F5A000F61800 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
654287F91E79F5A000F61800 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
658A083E1E2EC5120074A98F /* SwiftyStoreKitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwiftyStoreKitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
65F7DF681DCD4DF000835D30 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
65F7DF691DCD4DF000835D30 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
65F7DF6B1DCD4DF000835D30 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; };
65F7DF6D1DCD4DF000835D30 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
65F7DF6E1DCD4DF000835D30 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
65F7DF6F1DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkActivityIndicatorManager.swift; sourceTree = ""; };
65F7DF701DCD4DF000835D30 /* ViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
65F7DF7E1DCD4FC500835D30 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
65F7DF7F1DCD4FC500835D30 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
65F7DF811DCD4FC500835D30 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
65F7DF821DCD4FC500835D30 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
65F7DF831DCD4FC500835D30 /* ViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
A61BF4DD2481F4970017D9BC /* SwiftyStoreKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyStoreKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C4D74BBB1C24CEC90071AD3E /* SwiftyStoreKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyStoreKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C4FD3A011C2954C10035CFF3 /* SwiftyStoreKit_macOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftyStoreKit_macOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
54C0D5281CF7404500F90BCE /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F5FB1B985833004E342D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
65F7DF8E1DCD524300835D30 /* SwiftyStoreKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F6291B985C40004E342D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
654287EB1E79F5A000F61800 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
654287FD1E79F75000F61800 /* SwiftyStoreKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
658A083B1E2EC5120074A98F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
658A08431E2EC5120074A98F /* SwiftyStoreKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A61BF4D52481F4970017D9BC /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C4D74BB71C24CEC90071AD3E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C4FD39FE1C2954C10035CFF3 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C4FD3A101C2954CD0035CFF3 /* SwiftyStoreKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
6502F5F51B985833004E342D = {
isa = PBXGroup;
children = (
6502F6001B985833004E342D /* SwiftyStoreKit */,
65F7DF671DCD4DF000835D30 /* SwiftyStoreKit-iOS-Demo */,
65F7DF7D1DCD4FC500835D30 /* SwiftyStoreKit-macOS-Demo */,
654287EF1E79F5A000F61800 /* SwiftyStoreKit-tvOS-Demo */,
658A083F1E2EC5120074A98F /* SwiftyStoreKitTests */,
6502F5FF1B985833004E342D /* Products */,
);
sourceTree = "";
};
6502F5FF1B985833004E342D /* Products */ = {
isa = PBXGroup;
children = (
6502F5FE1B985833004E342D /* SwiftyStoreKit_iOSDemo.app */,
6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */,
C4D74BBB1C24CEC90071AD3E /* SwiftyStoreKit.framework */,
C4FD3A011C2954C10035CFF3 /* SwiftyStoreKit_macOSDemo.app */,
54C0D52C1CF7404500F90BCE /* SwiftyStoreKit.framework */,
658A083E1E2EC5120074A98F /* SwiftyStoreKitTests.xctest */,
654287EE1E79F5A000F61800 /* SwiftyStoreKit_tvOSDemo.app */,
A61BF4DD2481F4970017D9BC /* SwiftyStoreKit.framework */,
);
name = Products;
sourceTree = "";
};
6502F6001B985833004E342D /* SwiftyStoreKit */ = {
isa = PBXGroup;
children = (
2F2B8B2224A64CC000CEF088 /* AppleReceiptValidator.swift */,
2F2B8B2624A64CC000CEF088 /* CompleteTransactionsController.swift */,
2F2B8B2324A64CC000CEF088 /* InAppProductQueryRequest.swift */,
2F2B8B2424A64CC000CEF088 /* InAppReceipt.swift */,
2F2B8B2824A64CC000CEF088 /* InAppReceiptRefreshRequest.swift */,
2F2B8B2924A64CC100CEF088 /* InAppReceiptVerificator.swift */,
2F2B8B2C24A64CC100CEF088 /* OS.swift */,
2F2B8B2724A64CC000CEF088 /* PaymentQueueController.swift */,
2F2B8B2D24A64CC100CEF088 /* PaymentsController.swift */,
2F2B8B2B24A64CC100CEF088 /* ProductsInfoController.swift */,
2F2B8B2F24A64CC100CEF088 /* RestorePurchasesController.swift */,
2F2B8B2A24A64CC100CEF088 /* SKProduct+LocalizedPrice.swift */,
2F2B8B2124A64CC000CEF088 /* SKProductDiscount+LocalizedPrice.swift */,
2F2B8B2E24A64CC100CEF088 /* SwiftyStoreKit.swift */,
2F2B8B2524A64CC000CEF088 /* SwiftyStoreKit+Types.swift */,
65F7DF931DCD536100835D30 /* Platforms */,
);
path = SwiftyStoreKit;
sourceTree = "";
};
654287EF1E79F5A000F61800 /* SwiftyStoreKit-tvOS-Demo */ = {
isa = PBXGroup;
children = (
654287F41E79F5A000F61800 /* Main.storyboard */,
654287F71E79F5A000F61800 /* Assets.xcassets */,
654287F91E79F5A000F61800 /* Info.plist */,
);
path = "SwiftyStoreKit-tvOS-Demo";
sourceTree = "";
};
658A083F1E2EC5120074A98F /* SwiftyStoreKitTests */ = {
isa = PBXGroup;
children = (
2F2B8B9A24A64DE600CEF088 /* CompleteTransactionsControllerTests.swift */,
2F2B8B9C24A64DE600CEF088 /* InAppReceiptTests.swift */,
2F2B8B9B24A64DE600CEF088 /* InAppReceiptVerificatorTests.swift */,
2F2B8B9E24A64DE600CEF088 /* Info-Tests.plist */,
2F2B8B9424A64DE600CEF088 /* PaymentQueueControllerTests.swift */,
2F2B8B9F24A64DE600CEF088 /* PaymentQueueSpy.swift */,
2F2B8B9D24A64DE600CEF088 /* PaymentsControllerTests.swift */,
2F2B8B9524A64DE600CEF088 /* PaymentTransactionObserverFake.swift */,
2F2B8B9624A64DE600CEF088 /* ProductsInfoControllerTests.swift */,
2F2B8B9924A64DE600CEF088 /* RestorePurchasesControllerTests.swift */,
2F2B8B9724A64DE600CEF088 /* TestPaymentTransaction.swift */,
2F2B8B9824A64DE600CEF088 /* TestProduct.swift */,
);
path = SwiftyStoreKitTests;
sourceTree = "";
};
65F7DF671DCD4DF000835D30 /* SwiftyStoreKit-iOS-Demo */ = {
isa = PBXGroup;
children = (
65F7DF681DCD4DF000835D30 /* AppDelegate.swift */,
65F7DF691DCD4DF000835D30 /* Assets.xcassets */,
65F7DF6A1DCD4DF000835D30 /* LaunchScreen.storyboard */,
65F7DF6C1DCD4DF000835D30 /* Main.storyboard */,
65F7DF6E1DCD4DF000835D30 /* Info.plist */,
65F7DF6F1DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift */,
65F7DF701DCD4DF000835D30 /* ViewController.swift */,
);
path = "SwiftyStoreKit-iOS-Demo";
sourceTree = "";
};
65F7DF7D1DCD4FC500835D30 /* SwiftyStoreKit-macOS-Demo */ = {
isa = PBXGroup;
children = (
65F7DF7E1DCD4FC500835D30 /* AppDelegate.swift */,
65F7DF7F1DCD4FC500835D30 /* Assets.xcassets */,
65F7DF801DCD4FC500835D30 /* Main.storyboard */,
65F7DF821DCD4FC500835D30 /* Info.plist */,
65F7DF831DCD4FC500835D30 /* ViewController.swift */,
);
path = "SwiftyStoreKit-macOS-Demo";
sourceTree = "";
};
65F7DF931DCD536100835D30 /* Platforms */ = {
isa = PBXGroup;
children = (
2F2B8B6F24A64CD700CEF088 /* Info-iOS.plist */,
2F2B8B6D24A64CD700CEF088 /* Info-macOS.plist */,
2F2B8B7324A64CD700CEF088 /* Info-tvOS.plist */,
2F2B8B6E24A64CD700CEF088 /* Info-watchOS.plist */,
2F2B8B7124A64CD700CEF088 /* SwiftyStoreKit-iOS.h */,
2F2B8B7224A64CD700CEF088 /* SwiftyStoreKit-macOS.h */,
2F2B8B7024A64CD700CEF088 /* SwiftyStoreKit-tvOS.h */,
2F2B8B6C24A64CD700CEF088 /* SwiftyStoreKit-watchOS.h */,
);
path = Platforms;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
54C0D5291CF7404500F90BCE /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B8A24A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */,
2F2B8B7624A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */,
2F2B8B8624A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */,
2F2B8B8E24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F62A1B985C40004E342D /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B8824A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */,
2F2B8B7424A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */,
2F2B8B8424A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */,
2F2B8B8C24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A61BF4D62481F4970017D9BC /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B8B24A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */,
2F2B8B7724A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */,
2F2B8B8724A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */,
2F2B8B8F24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C4D74BB81C24CEC90071AD3E /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B8924A64CD700CEF088 /* SwiftyStoreKit-iOS.h in Headers */,
2F2B8B7524A64CD700CEF088 /* SwiftyStoreKit-watchOS.h in Headers */,
2F2B8B8524A64CD700CEF088 /* SwiftyStoreKit-tvOS.h in Headers */,
2F2B8B8D24A64CD700CEF088 /* SwiftyStoreKit-macOS.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
54C0D52B1CF7404500F90BCE /* SwiftyStoreKit_tvOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 54C0D5331CF7404500F90BCE /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_tvOS" */;
buildPhases = (
54C0D5271CF7404500F90BCE /* Sources */,
54C0D5281CF7404500F90BCE /* Frameworks */,
54C0D5291CF7404500F90BCE /* Headers */,
54C0D52A1CF7404500F90BCE /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = SwiftyStoreKit_tvOS;
productName = SwiftyStoreKitTV;
productReference = 54C0D52C1CF7404500F90BCE /* SwiftyStoreKit.framework */;
productType = "com.apple.product-type.framework";
};
6502F5FD1B985833004E342D /* SwiftyStoreKit_iOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 6502F6101B985833004E342D /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_iOSDemo" */;
buildPhases = (
6502F5FA1B985833004E342D /* Sources */,
6502F5FB1B985833004E342D /* Frameworks */,
6502F5FC1B985833004E342D /* Resources */,
65F7DF921DCD524300835D30 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
65F7DF911DCD524300835D30 /* PBXTargetDependency */,
);
name = SwiftyStoreKit_iOSDemo;
productName = SwiftyStoreKit;
productReference = 6502F5FE1B985833004E342D /* SwiftyStoreKit_iOSDemo.app */;
productType = "com.apple.product-type.application";
};
6502F62C1B985C40004E342D /* SwiftyStoreKit_iOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 6502F6361B985C40004E342D /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_iOS" */;
buildPhases = (
6502F6281B985C40004E342D /* Sources */,
6502F6291B985C40004E342D /* Frameworks */,
6502F62A1B985C40004E342D /* Headers */,
6502F62B1B985C40004E342D /* Resources */,
C4B298351E5C25E5007C87C2 /* swiftlint */,
);
buildRules = (
);
dependencies = (
);
name = SwiftyStoreKit_iOS;
productName = SwiftyStoreKit;
productReference = 6502F62D1B985C40004E342D /* SwiftyStoreKit.framework */;
productType = "com.apple.product-type.framework";
};
654287ED1E79F5A000F61800 /* SwiftyStoreKit_tvOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 654287FC1E79F5A000F61800 /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_tvOSDemo" */;
buildPhases = (
654287EA1E79F5A000F61800 /* Sources */,
654287EB1E79F5A000F61800 /* Frameworks */,
654287EC1E79F5A000F61800 /* Resources */,
654288011E79F75100F61800 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
654288001E79F75000F61800 /* PBXTargetDependency */,
);
name = SwiftyStoreKit_tvOSDemo;
productName = "SwiftyStoreKit-tvOS-Demo";
productReference = 654287EE1E79F5A000F61800 /* SwiftyStoreKit_tvOSDemo.app */;
productType = "com.apple.product-type.application";
};
658A083D1E2EC5120074A98F /* SwiftyStoreKitTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 658A08461E2EC5120074A98F /* Build configuration list for PBXNativeTarget "SwiftyStoreKitTests" */;
buildPhases = (
658A083A1E2EC5120074A98F /* Sources */,
658A083B1E2EC5120074A98F /* Frameworks */,
658A083C1E2EC5120074A98F /* Resources */,
);
buildRules = (
);
dependencies = (
658A08451E2EC5120074A98F /* PBXTargetDependency */,
658A084E1E2EC83F0074A98F /* PBXTargetDependency */,
);
name = SwiftyStoreKitTests;
productName = SwiftyStoreKitTests;
productReference = 658A083E1E2EC5120074A98F /* SwiftyStoreKitTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
A61BF4C42481F4970017D9BC /* SwiftyStoreKit_watchOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = A61BF4DA2481F4970017D9BC /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_watchOS" */;
buildPhases = (
A61BF4C52481F4970017D9BC /* Sources */,
A61BF4D62481F4970017D9BC /* Headers */,
A61BF4D52481F4970017D9BC /* Frameworks */,
A61BF4D82481F4970017D9BC /* Resources */,
A61BF4D92481F4970017D9BC /* swiftlint */,
);
buildRules = (
);
dependencies = (
);
name = SwiftyStoreKit_watchOS;
productName = SwiftyStoreKit;
productReference = A61BF4DD2481F4970017D9BC /* SwiftyStoreKit.framework */;
productType = "com.apple.product-type.framework";
};
C4D74BBA1C24CEC90071AD3E /* SwiftyStoreKit_macOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = C4D74BC21C24CECA0071AD3E /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_macOS" */;
buildPhases = (
C4D74BB61C24CEC90071AD3E /* Sources */,
C4D74BB71C24CEC90071AD3E /* Frameworks */,
C4D74BB81C24CEC90071AD3E /* Headers */,
C4D74BB91C24CEC90071AD3E /* Resources */,
C4B298341E5C25DD007C87C2 /* swiftlint */,
);
buildRules = (
);
dependencies = (
);
name = SwiftyStoreKit_macOS;
productName = SwiftyStoreKitOSX;
productReference = C4D74BBB1C24CEC90071AD3E /* SwiftyStoreKit.framework */;
productType = "com.apple.product-type.framework";
};
C4FD3A001C2954C10035CFF3 /* SwiftyStoreKit_macOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C4FD3A0D1C2954C10035CFF3 /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_macOSDemo" */;
buildPhases = (
C4FD39FD1C2954C10035CFF3 /* Sources */,
C4FD39FE1C2954C10035CFF3 /* Frameworks */,
C4FD39FF1C2954C10035CFF3 /* Resources */,
C4FD3A141C2954CD0035CFF3 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
C4FD3A131C2954CD0035CFF3 /* PBXTargetDependency */,
);
name = SwiftyStoreKit_macOSDemo;
productName = SwiftyStoreOSXDemo;
productReference = C4FD3A011C2954C10035CFF3 /* SwiftyStoreKit_macOSDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
6502F5F61B985833004E342D /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0820;
LastUpgradeCheck = 1160;
ORGANIZATIONNAME = musevisions;
TargetAttributes = {
54C0D52B1CF7404500F90BCE = {
CreatedOnToolsVersion = 7.3.1;
DevelopmentTeam = M54ZVB688G;
LastSwiftMigration = 1150;
};
6502F5FD1B985833004E342D = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 0800;
ProvisioningStyle = Automatic;
};
6502F62C1B985C40004E342D = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 1150;
};
654287ED1E79F5A000F61800 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
};
658A083D1E2EC5120074A98F = {
CreatedOnToolsVersion = 8.2.1;
LastSwiftMigration = 1150;
ProvisioningStyle = Automatic;
TestTargetID = 6502F5FD1B985833004E342D;
};
A61BF4C42481F4970017D9BC = {
LastSwiftMigration = 1150;
};
C4D74BBA1C24CEC90071AD3E = {
CreatedOnToolsVersion = 7.2;
LastSwiftMigration = 1150;
};
C4FD3A001C2954C10035CFF3 = {
CreatedOnToolsVersion = 7.2;
LastSwiftMigration = 0800;
};
};
};
buildConfigurationList = 6502F5F91B985833004E342D /* Build configuration list for PBXProject "SwiftyStoreKit" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 6502F5F51B985833004E342D;
productRefGroup = 6502F5FF1B985833004E342D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
6502F62C1B985C40004E342D /* SwiftyStoreKit_iOS */,
C4D74BBA1C24CEC90071AD3E /* SwiftyStoreKit_macOS */,
54C0D52B1CF7404500F90BCE /* SwiftyStoreKit_tvOS */,
A61BF4C42481F4970017D9BC /* SwiftyStoreKit_watchOS */,
6502F5FD1B985833004E342D /* SwiftyStoreKit_iOSDemo */,
C4FD3A001C2954C10035CFF3 /* SwiftyStoreKit_macOSDemo */,
654287ED1E79F5A000F61800 /* SwiftyStoreKit_tvOSDemo */,
658A083D1E2EC5120074A98F /* SwiftyStoreKitTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
54C0D52A1CF7404500F90BCE /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F5FC1B985833004E342D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
65F7DF721DCD4DF000835D30 /* Assets.xcassets in Resources */,
65F7DF741DCD4DF000835D30 /* Main.storyboard in Resources */,
65F7DF731DCD4DF000835D30 /* LaunchScreen.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F62B1B985C40004E342D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
654287EC1E79F5A000F61800 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
654287F81E79F5A000F61800 /* Assets.xcassets in Resources */,
654287F61E79F5A000F61800 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
658A083C1E2EC5120074A98F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
A61BF4D82481F4970017D9BC /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C4D74BB91C24CEC90071AD3E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C4FD39FF1C2954C10035CFF3 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
65F7DF851DCD4FC500835D30 /* Assets.xcassets in Resources */,
65F7DF861DCD4FC500835D30 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
A61BF4D92481F4970017D9BC /* swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = swiftlint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\nswiftlint\nelse\necho \"SwiftLint does not exist, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
C4B298341E5C25DD007C87C2 /* swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = swiftlint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\nswiftlint\nelse\necho \"SwiftLint does not exist, download from https://github.com/realm/SwiftLint\"\nfi";
};
C4B298351E5C25E5007C87C2 /* swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = swiftlint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\nswiftlint\nelse\necho \"SwiftLint does not exist, download from https://github.com/realm/SwiftLint\"\nfi";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
54C0D5271CF7404500F90BCE /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B3A24A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */,
2F2B8B6224A64CC100CEF088 /* PaymentsController.swift in Sources */,
2F2B8B5624A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */,
2F2B8B3E24A64CC100CEF088 /* InAppReceipt.swift in Sources */,
2F2B8B3624A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */,
2F2B8B6A24A64CC100CEF088 /* RestorePurchasesController.swift in Sources */,
2F2B8B4624A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */,
2F2B8B5E24A64CC100CEF088 /* OS.swift in Sources */,
2F2B8B5224A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */,
2F2B8B6624A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */,
2F2B8B4A24A64CC100CEF088 /* PaymentQueueController.swift in Sources */,
2F2B8B4224A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */,
2F2B8B4E24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */,
2F2B8B3224A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */,
2F2B8B5A24A64CC100CEF088 /* ProductsInfoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F5FA1B985833004E342D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
65F7DF771DCD4DF000835D30 /* ViewController.swift in Sources */,
65F7DF711DCD4DF000835D30 /* AppDelegate.swift in Sources */,
65F7DF761DCD4DF000835D30 /* NetworkActivityIndicatorManager.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6502F6281B985C40004E342D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B3824A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */,
2F2B8B6024A64CC100CEF088 /* PaymentsController.swift in Sources */,
2F2B8B5424A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */,
2F2B8B3C24A64CC100CEF088 /* InAppReceipt.swift in Sources */,
2F2B8B3424A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */,
2F2B8B6824A64CC100CEF088 /* RestorePurchasesController.swift in Sources */,
2F2B8B4424A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */,
2F2B8B5C24A64CC100CEF088 /* OS.swift in Sources */,
2F2B8B5024A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */,
2F2B8B6424A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */,
2F2B8B4824A64CC100CEF088 /* PaymentQueueController.swift in Sources */,
2F2B8B4024A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */,
2F2B8B4C24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */,
2F2B8B3024A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */,
2F2B8B5824A64CC100CEF088 /* ProductsInfoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
654287EA1E79F5A000F61800 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
654288071E7B3E1500F61800 /* AppDelegate.swift in Sources */,
654288021E7B34E500F61800 /* ViewController.swift in Sources */,
654288061E7B3A8800F61800 /* NetworkActivityIndicatorManager.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
658A083A1E2EC5120074A98F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8BA924A64DE600CEF088 /* PaymentsControllerTests.swift in Sources */,
2F2B8BA224A64DE600CEF088 /* ProductsInfoControllerTests.swift in Sources */,
2F2B8BA524A64DE600CEF088 /* RestorePurchasesControllerTests.swift in Sources */,
2F2B8BA724A64DE600CEF088 /* InAppReceiptVerificatorTests.swift in Sources */,
2F2B8BA124A64DE600CEF088 /* PaymentTransactionObserverFake.swift in Sources */,
2F2B8BAB24A64DE600CEF088 /* PaymentQueueSpy.swift in Sources */,
2F2B8BA624A64DE600CEF088 /* CompleteTransactionsControllerTests.swift in Sources */,
2F2B8BA024A64DE600CEF088 /* PaymentQueueControllerTests.swift in Sources */,
2F2B8BA324A64DE600CEF088 /* TestPaymentTransaction.swift in Sources */,
2F2B8BA424A64DE600CEF088 /* TestProduct.swift in Sources */,
2F2B8BA824A64DE600CEF088 /* InAppReceiptTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A61BF4C52481F4970017D9BC /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B3B24A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */,
2F2B8B6324A64CC100CEF088 /* PaymentsController.swift in Sources */,
2F2B8B5724A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */,
2F2B8B3F24A64CC100CEF088 /* InAppReceipt.swift in Sources */,
2F2B8B3724A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */,
2F2B8B6B24A64CC100CEF088 /* RestorePurchasesController.swift in Sources */,
2F2B8B4724A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */,
2F2B8B5F24A64CC100CEF088 /* OS.swift in Sources */,
2F2B8B5324A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */,
2F2B8B6724A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */,
2F2B8B4B24A64CC100CEF088 /* PaymentQueueController.swift in Sources */,
2F2B8B4324A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */,
2F2B8B4F24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */,
2F2B8B3324A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */,
2F2B8B5B24A64CC100CEF088 /* ProductsInfoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C4D74BB61C24CEC90071AD3E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2F2B8B3924A64CC100CEF088 /* InAppProductQueryRequest.swift in Sources */,
2F2B8B6124A64CC100CEF088 /* PaymentsController.swift in Sources */,
2F2B8B5524A64CC100CEF088 /* SKProduct+LocalizedPrice.swift in Sources */,
2F2B8B3D24A64CC100CEF088 /* InAppReceipt.swift in Sources */,
2F2B8B3524A64CC100CEF088 /* AppleReceiptValidator.swift in Sources */,
2F2B8B6924A64CC100CEF088 /* RestorePurchasesController.swift in Sources */,
2F2B8B4524A64CC100CEF088 /* CompleteTransactionsController.swift in Sources */,
2F2B8B5D24A64CC100CEF088 /* OS.swift in Sources */,
2F2B8B5124A64CC100CEF088 /* InAppReceiptVerificator.swift in Sources */,
2F2B8B6524A64CC100CEF088 /* SwiftyStoreKit.swift in Sources */,
2F2B8B4924A64CC100CEF088 /* PaymentQueueController.swift in Sources */,
2F2B8B4124A64CC100CEF088 /* SwiftyStoreKit+Types.swift in Sources */,
2F2B8B4D24A64CC100CEF088 /* InAppReceiptRefreshRequest.swift in Sources */,
2F2B8B3124A64CC100CEF088 /* SKProductDiscount+LocalizedPrice.swift in Sources */,
2F2B8B5924A64CC100CEF088 /* ProductsInfoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C4FD39FD1C2954C10035CFF3 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
65F7DF841DCD4FC500835D30 /* AppDelegate.swift in Sources */,
65F7DF881DCD4FC500835D30 /* ViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
654288001E79F75000F61800 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 54C0D52B1CF7404500F90BCE /* SwiftyStoreKit_tvOS */;
targetProxy = 654287FF1E79F75000F61800 /* PBXContainerItemProxy */;
};
658A08451E2EC5120074A98F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 6502F62C1B985C40004E342D /* SwiftyStoreKit_iOS */;
targetProxy = 658A08441E2EC5120074A98F /* PBXContainerItemProxy */;
};
658A084E1E2EC83F0074A98F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 6502F5FD1B985833004E342D /* SwiftyStoreKit_iOSDemo */;
targetProxy = 658A084D1E2EC83F0074A98F /* PBXContainerItemProxy */;
};
65F7DF911DCD524300835D30 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 6502F62C1B985C40004E342D /* SwiftyStoreKit_iOS */;
targetProxy = 65F7DF901DCD524300835D30 /* PBXContainerItemProxy */;
};
C4FD3A131C2954CD0035CFF3 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = C4D74BBA1C24CEC90071AD3E /* SwiftyStoreKit_macOS */;
targetProxy = C4FD3A121C2954CD0035CFF3 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
654287F41E79F5A000F61800 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
654287F51E79F5A000F61800 /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
65F7DF6A1DCD4DF000835D30 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
65F7DF6B1DCD4DF000835D30 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "";
};
65F7DF6C1DCD4DF000835D30 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
65F7DF6D1DCD4DF000835D30 /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
65F7DF801DCD4FC500835D30 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
65F7DF811DCD4FC500835D30 /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
54C0D5311CF7404500F90BCE /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ANALYZER_NONNULL = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = M54ZVB688G;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-tvOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.tvOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
54C0D5321CF7404500F90BCE /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ANALYZER_NONNULL = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = M54ZVB688G;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-tvOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.tvOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
6502F60E1B985833004E342D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
6502F60F1B985833004E342D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
6502F6111B985833004E342D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "$(SRCROOT)/SwiftyStoreKit-iOS-Demo/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
TARGETED_DEVICE_FAMILY = 1;
};
name = Debug;
};
6502F6121B985833004E342D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "$(SRCROOT)/SwiftyStoreKit-iOS-Demo/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = 1;
};
name = Release;
};
6502F6371B985C40004E342D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-iOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
6502F6381B985C40004E342D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-iOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
654287FA1E79F5A000F61800 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "SwiftyStoreKit-tvOS-Demo/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Debug;
};
654287FB1E79F5A000F61800 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "SwiftyStoreKit-tvOS-Demo/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Release;
};
658A08471E2EC5120074A98F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ENABLE_MODULES = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
INFOPLIST_FILE = "Tests/SwiftyStoreKitTests/Info-Tests.plist";
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKitTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwiftyStoreKit_iOSDemo.app/SwiftyStoreKit_iOSDemo";
};
name = Debug;
};
658A08481E2EC5120074A98F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ENABLE_MODULES = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
INFOPLIST_FILE = "Tests/SwiftyStoreKitTests/Info-Tests.plist";
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKitTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwiftyStoreKit_iOSDemo.app/SwiftyStoreKit_iOSDemo";
};
name = Release;
};
A61BF4DB2481F4970017D9BC /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-watchOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = watchos;
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 4;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
A61BF4DC2481F4970017D9BC /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-watchOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.iOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = watchos;
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 4;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
C4D74BC01C24CECA0071AD3E /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "-";
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-macOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.macOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
C4D74BC11C24CECA0071AD3E /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "-";
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftyStoreKit/Platforms/Info-macOS.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.macOS.SwiftyStoreKit;
PRODUCT_NAME = SwiftyStoreKit;
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
C4FD3A0E1C2954C10035CFF3 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "-";
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = "$(SRCROOT)/SwiftyStoreKit-macOS-Demo/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.OSX.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
};
name = Debug;
};
C4FD3A0F1C2954C10035CFF3 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "-";
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = "$(SRCROOT)/SwiftyStoreKit-macOS-Demo/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.musevisions.OSX.SwiftyStoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
54C0D5331CF7404500F90BCE /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_tvOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
54C0D5311CF7404500F90BCE /* Debug */,
54C0D5321CF7404500F90BCE /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6502F5F91B985833004E342D /* Build configuration list for PBXProject "SwiftyStoreKit" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6502F60E1B985833004E342D /* Debug */,
6502F60F1B985833004E342D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6502F6101B985833004E342D /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_iOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6502F6111B985833004E342D /* Debug */,
6502F6121B985833004E342D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6502F6361B985C40004E342D /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_iOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6502F6371B985C40004E342D /* Debug */,
6502F6381B985C40004E342D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
654287FC1E79F5A000F61800 /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_tvOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
654287FA1E79F5A000F61800 /* Debug */,
654287FB1E79F5A000F61800 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
658A08461E2EC5120074A98F /* Build configuration list for PBXNativeTarget "SwiftyStoreKitTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
658A08471E2EC5120074A98F /* Debug */,
658A08481E2EC5120074A98F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A61BF4DA2481F4970017D9BC /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_watchOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A61BF4DB2481F4970017D9BC /* Debug */,
A61BF4DC2481F4970017D9BC /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C4D74BC21C24CECA0071AD3E /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_macOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C4D74BC01C24CECA0071AD3E /* Debug */,
C4D74BC11C24CECA0071AD3E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C4FD3A0D1C2954C10035CFF3 /* Build configuration list for PBXNativeTarget "SwiftyStoreKit_macOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C4FD3A0E1C2954C10035CFF3 /* Debug */,
C4FD3A0F1C2954C10035CFF3 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 6502F5F61B985833004E342D /* Project object */;
}
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-iOS-Demo.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-iOS.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-macOS-Demo.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-macOS.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-tvOS-Demo.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit-tvOS.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKitTests.xcscheme
================================================
================================================
FILE: SwiftyStoreKit.xcodeproj/xcshareddata/xcschemes/SwiftyStoreKit_watchOS.xcscheme
================================================
================================================
FILE: Tests/SwiftyStoreKitTests/CompleteTransactionsControllerTests.swift
================================================
//
// CompleteTransactionsControllerTests.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
import StoreKit
@testable import SwiftyStoreKit
class CompleteTransactionsControllerTests: XCTestCase {
func testProcessTransactions_when_atomically_oneRestoredTransaction_then_finishesTransaction_callsCallback_noRemainingTransactions() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .restored)
var callbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { purchases in
callbackCalled = true
XCTAssertEqual(purchases.count, 1)
let purchase = purchases.first!
XCTAssertEqual(purchase.productId, productIdentifier)
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransactions_when_atomically_oneFailedTransaction_then_finishesTransaction_callsCallback_noRemainingTransactions_noNeedsFinishTransactions() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .failed)
var callbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { purchases in
callbackCalled = true
XCTAssertEqual(purchases.count, 1)
let purchase = purchases.first!
XCTAssertFalse(purchase.needsFinishTransaction)
XCTAssertEqual(purchase.productId, productIdentifier)
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransactions_when_notAtomically_oneFailedTransaction_then_finishesTransaction_callsCallback_noRemainingTransactions_noNeedsFinishTransactions() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .failed)
var callbackCalled = false
let completeTransactions = CompleteTransactions(atomically: false) { purchases in
callbackCalled = true
XCTAssertEqual(purchases.count, 1)
let purchase = purchases.first!
XCTAssertFalse(purchase.needsFinishTransaction)
XCTAssertEqual(purchase.productId, productIdentifier)
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransactions_when_atomically_oneTransactionForEachState_then_finishesTransactions_callsCallback_onePurchasingTransactionRemaining() {
let transactions = [
makeTestPaymentTransaction(productIdentifier: "com.SwiftyStoreKit.product1", transactionState: .purchased),
makeTestPaymentTransaction(productIdentifier: "com.SwiftyStoreKit.product2", transactionState: .failed),
makeTestPaymentTransaction(productIdentifier: "com.SwiftyStoreKit.product3", transactionState: .restored),
makeTestPaymentTransaction(productIdentifier: "com.SwiftyStoreKit.product4", transactionState: .deferred),
makeTestPaymentTransaction(productIdentifier: "com.SwiftyStoreKit.product5", transactionState: .purchasing)
]
var callbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { purchases in
callbackCalled = true
XCTAssertEqual(purchases.count, 4)
for i in 0..<4 {
XCTAssertEqual(purchases[i].productId, transactions[i].payment.productIdentifier)
}
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions(transactions, on: spy)
XCTAssertEqual(remainingTransactions.count, 1)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 4)
}
func testProcessTransactions_when_atomically_zeroTransactions_then_noFinishedTransactions_noCallback_noTransactionsRemaining() {
let transactions: [TestPaymentTransaction] = []
let completeTransactions = CompleteTransactions(atomically: true) { _ in
XCTFail("Callback should not be called")
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions(transactions, on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertEqual(spy.finishTransactionCalledCount, 0)
}
func testProcessTransactions_when_atomically_onePurchasingTransaction_then_noFinishedTransactions_noCallback_oneTransactionsRemaining() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .purchasing)
let completeTransactions = CompleteTransactions(atomically: true) { _ in
XCTFail("Callback should not be called")
}
let completeTransactionsController = makeCompleteTransactionsController(completeTransactions: completeTransactions)
let spy = PaymentQueueSpy()
let remainingTransactions = completeTransactionsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 1)
XCTAssertEqual(spy.finishTransactionCalledCount, 0)
}
func makeTestPaymentTransaction(productIdentifier: String, transactionState: SKPaymentTransactionState) -> TestPaymentTransaction {
let testProduct = TestProduct(productIdentifier: productIdentifier)
return TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: transactionState)
}
func makeCompleteTransactionsController(completeTransactions: CompleteTransactions?) -> CompleteTransactionsController {
let completeTransactionsController = CompleteTransactionsController()
completeTransactionsController.completeTransactions = completeTransactions
return completeTransactionsController
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/InAppReceiptTests.swift
================================================
//
// InAppReceiptTests.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 08/05/2017.
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
import SwiftyStoreKit
private extension TimeInterval {
var millisecondsNSString: NSString {
return String(format: "%.0f", self * 1000) as NSString
}
}
extension ReceiptItem: Equatable {
init(productId: String, purchaseDate: Date, subscriptionExpirationDate: Date? = nil, cancellationDate: Date? = nil, isTrialPeriod: Bool = false, isInIntroOfferPeriod: Bool = false, isUpgraded: Bool = false) {
self.init(productId: productId, quantity: 1, transactionId: UUID().uuidString, originalTransactionId: UUID().uuidString, purchaseDate: purchaseDate, originalPurchaseDate: purchaseDate, webOrderLineItemId: UUID().uuidString, subscriptionExpirationDate: subscriptionExpirationDate, cancellationDate: cancellationDate, isTrialPeriod: isTrialPeriod, isInIntroOfferPeriod: isInIntroOfferPeriod, isUpgraded: isUpgraded)
self.productId = productId
self.quantity = 1
self.purchaseDate = purchaseDate
self.originalPurchaseDate = purchaseDate
self.subscriptionExpirationDate = subscriptionExpirationDate
self.cancellationDate = cancellationDate
self.transactionId = UUID().uuidString
self.originalTransactionId = UUID().uuidString
self.webOrderLineItemId = UUID().uuidString
self.isTrialPeriod = isTrialPeriod
self.isInIntroOfferPeriod = isInIntroOfferPeriod
self.isUpgraded = isUpgraded
}
var receiptInfo: NSDictionary {
var result: [String: AnyObject] = [
"product_id": productId as NSString,
"quantity": String(quantity) as NSString,
"purchase_date_ms": purchaseDate.timeIntervalSince1970.millisecondsNSString,
"original_purchase_date_ms": originalPurchaseDate.timeIntervalSince1970.millisecondsNSString,
"is_trial_period": (isTrialPeriod ? "1" : "0") as NSString,
"transaction_id": transactionId as NSString,
"original_transaction_id": originalTransactionId as NSString
]
if let subscriptionExpirationDate = subscriptionExpirationDate {
result["expires_date_ms"] = subscriptionExpirationDate.timeIntervalSince1970.millisecondsNSString
}
if let cancellationDate = cancellationDate {
result["cancellation_date_ms"] = cancellationDate.timeIntervalSince1970.millisecondsNSString
result["cancellation_date"] = cancellationDate as NSDate
}
return NSDictionary(dictionary: result)
}
public static func == (lhs: ReceiptItem, rhs: ReceiptItem) -> Bool {
return
lhs.productId == rhs.productId &&
lhs.quantity == rhs.quantity &&
lhs.purchaseDate == rhs.purchaseDate &&
lhs.originalPurchaseDate == rhs.originalPurchaseDate &&
lhs.subscriptionExpirationDate == rhs.subscriptionExpirationDate &&
lhs.cancellationDate == rhs.cancellationDate &&
lhs.isTrialPeriod == rhs.isTrialPeriod
}
}
extension VerifySubscriptionResult: Equatable {
public static func == (lhs: VerifySubscriptionResult, rhs: VerifySubscriptionResult) -> Bool {
switch (lhs, rhs) {
case (.notPurchased, .notPurchased): return true
case (.purchased(let lhsExpiryDate, let lhsReceiptItem), .purchased(let rhsExpiryDate, let rhsReceiptItem)):
return lhsExpiryDate == rhsExpiryDate && lhsReceiptItem == rhsReceiptItem
case (.expired(let lhsExpiryDate, let lhsReceiptItem), .expired(let rhsExpiryDate, let rhsReceiptItem)):
return lhsExpiryDate == rhsExpiryDate && lhsReceiptItem == rhsReceiptItem
default: return false
}
}
}
extension VerifyPurchaseResult: Equatable {
public static func == (lhs: VerifyPurchaseResult, rhs: VerifyPurchaseResult) -> Bool {
switch (lhs, rhs) {
case (.notPurchased, .notPurchased): return true
case (.purchased(let lhsReceiptItem), .purchased(let rhsReceiptItem)):
return lhsReceiptItem == rhsReceiptItem
default: return false
}
}
}
// swiftlint: disable file_length
class InAppReceiptTests: XCTestCase {
// MARK: Verify Purchase
func testVerifyPurchase_when_noPurchases_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let receipt = makeReceipt(items: [], requestDate: receiptRequestDate)
let verifyPurchaseResult = SwiftyStoreKit.verifyPurchase(productId: productId, inReceipt: receipt)
XCTAssertEqual(verifyPurchaseResult, .notPurchased)
}
func testVerifyPurchase_when_onePurchase_then_resultIsPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let item = ReceiptItem(productId: productId, purchaseDate: receiptRequestDate, subscriptionExpirationDate: nil, cancellationDate: nil, isTrialPeriod: false)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifyPurchaseResult = SwiftyStoreKit.verifyPurchase(productId: productId, inReceipt: receipt)
XCTAssertEqual(verifyPurchaseResult, .purchased(item: item))
}
func testVerifyPurchase_when_oneCancelledPurchase_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let item = ReceiptItem(productId: productId, purchaseDate: receiptRequestDate, subscriptionExpirationDate: nil, cancellationDate: receiptRequestDate, isTrialPeriod: false)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifyPurchaseResult = SwiftyStoreKit.verifyPurchase(productId: productId, inReceipt: receipt)
XCTAssertEqual(verifyPurchaseResult, .notPurchased)
}
// MARK: Verify Subscription, single receipt item tests
// auto-renewable, not purchased
func testVerifyAutoRenewableSubscription_when_noSubscriptions_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let receipt = makeReceipt(items: [], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.notPurchased
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// auto-renewable, expired
func testVerifyAutoRenewableSubscription_when_oneExpiredSubscription_then_resultIsExpired() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 15)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let expirationDate = purchaseDate.addingTimeInterval(60 * 60)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: expirationDate, cancellationDate: nil, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.expired(expiryDate: expirationDate, items: [item])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// auto-renewable, purchased
func testVerifyAutoRenewableSubscription_when_oneNonExpiredSubscription_then_resultIsPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = receiptRequestDate
let expirationDate = purchaseDate.addingTimeInterval(60 * 60)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: expirationDate, cancellationDate: nil, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.purchased(expiryDate: expirationDate, items: [item])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// auto-renewable, cancelled
func testVerifyAutoRenewableSubscription_when_oneCancelledSubscription_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = receiptRequestDate
let expirationDate = purchaseDate.addingTimeInterval(60 * 60)
let cancelledDate = purchaseDate.addingTimeInterval(30 * 60)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: expirationDate, cancellationDate: cancelledDate, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.notPurchased
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// non-renewing, non purchased
func testVerifyNonRenewingSubscription_when_noSubscriptions_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let receipt = makeReceipt(items: [], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .nonRenewing(validDuration: 60 * 60), productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.notPurchased
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// non-renewing, expired
func testVerifyNonRenewingSubscription_when_oneExpiredSubscription_then_resultIsExpired() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 15)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let duration: TimeInterval = 60 * 60
let expirationDate = purchaseDate.addingTimeInterval(duration)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: nil, cancellationDate: nil, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .nonRenewing(validDuration: duration), productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.expired(expiryDate: expirationDate, items: [item])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// non-renewing, purchased
func testVerifyNonRenewingSubscription_when_oneNonExpiredSubscription_then_resultIsPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = receiptRequestDate
let duration: TimeInterval = 60 * 60
let expirationDate = purchaseDate.addingTimeInterval(duration)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: nil, cancellationDate: nil, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .nonRenewing(validDuration: duration), productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.purchased(expiryDate: expirationDate, items: [item])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// non-renewing, cancelled
func testVerifyNonRenewingSubscription_when_oneCancelledSubscription_then_resultIsNotPurchased() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let purchaseDate = receiptRequestDate
let duration: TimeInterval = 60 * 60
let cancelledDate = purchaseDate.addingTimeInterval(30 * 60)
let item = ReceiptItem(productId: productId, purchaseDate: purchaseDate, subscriptionExpirationDate: nil, cancellationDate: cancelledDate, isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [item], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .nonRenewing(validDuration: duration), productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.notPurchased
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// MARK: Verify Subscription, multiple receipt item tests
func testVerifyAutoRenewableSubscription_when_twoSubscriptions_sameProductId_mostRecentNonExpired_then_resultIsPurchased_itemsSorted() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let olderPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 12)
let olderExpirationDate = olderPurchaseDate.addingTimeInterval(60 * 60)
let olderItem = ReceiptItem(productId: productId,
purchaseDate: olderPurchaseDate,
subscriptionExpirationDate: olderExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let newerPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let newerExpirationDate = newerPurchaseDate.addingTimeInterval(60 * 60)
let newerItem = ReceiptItem(productId: productId,
purchaseDate: newerPurchaseDate,
subscriptionExpirationDate: newerExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [olderItem, newerItem], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.purchased(expiryDate: newerExpirationDate, items: [newerItem, olderItem])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
func testVerifyAutoRenewableSubscription_when_twoSubscriptions_sameProductId_bothExpired_then_resultIsExpired_itemsSorted() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId = "product1"
let isTrialPeriod = false
let olderPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 12)
let olderExpirationDate = olderPurchaseDate.addingTimeInterval(60 * 60)
let olderItem = ReceiptItem(productId: productId,
purchaseDate: olderPurchaseDate,
subscriptionExpirationDate: olderExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let newerPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 13)
let newerExpirationDate = newerPurchaseDate.addingTimeInterval(60 * 60)
let newerItem = ReceiptItem(productId: productId,
purchaseDate: newerPurchaseDate,
subscriptionExpirationDate: newerExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [olderItem, newerItem], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.expired(expiryDate: newerExpirationDate, items: [newerItem, olderItem])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// MARK: Verify Subscriptions, multiple receipt item tests
func testVerifyAutoRenewableSubscriptions_when_threeSubscriptions_twoMatchingProductIds_mostRecentNonExpired_then_resultIsPurchased_itemsSorted() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let productId1 = "product1"
let productId2 = "product2"
let productIds = Set([ productId1, productId2 ])
let isTrialPeriod = false
let olderPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 12)
let olderExpirationDate = olderPurchaseDate.addingTimeInterval(60 * 60)
let olderItem = ReceiptItem(productId: productId1,
purchaseDate: olderPurchaseDate,
subscriptionExpirationDate: olderExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let newerPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let newerExpirationDate = newerPurchaseDate.addingTimeInterval(60 * 60)
let newerItem = ReceiptItem(productId: productId2,
purchaseDate: newerPurchaseDate,
subscriptionExpirationDate: newerExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let otherPurchaseDate = makeDateAtMidnight(year: 2017, month: 5, day: 15)
let otherExpirationDate = otherPurchaseDate.addingTimeInterval(60 * 60)
let otherItem = ReceiptItem(productId: "otherProduct",
purchaseDate: otherPurchaseDate,
subscriptionExpirationDate: otherExpirationDate,
cancellationDate: nil,
isTrialPeriod: isTrialPeriod)
let receipt = makeReceipt(items: [olderItem, newerItem, otherItem], requestDate: receiptRequestDate)
let verifySubscriptionResult = SwiftyStoreKit.verifySubscriptions(ofType: .autoRenewable, productIds: productIds, inReceipt: receipt)
let expectedSubscriptionResult = VerifySubscriptionResult.purchased(expiryDate: newerExpirationDate, items: [newerItem, olderItem])
XCTAssertEqual(verifySubscriptionResult, expectedSubscriptionResult)
}
// MARK: Get Distinct Purchase Identifiers, empty receipt item tests
func testGetDistinctPurchaseIds_when_noReceipt_then_resultIsNil() {
let receiptRequestDate = makeDateAtMidnight(year: 2017, month: 5, day: 14)
let receipt = makeReceipt(items: [], requestDate: receiptRequestDate)
let getdistinctProductIdsResult = SwiftyStoreKit.getDistinctPurchaseIds(ofType: .autoRenewable, inReceipt: receipt)
XCTAssertNil(getdistinctProductIdsResult)
}
// MARK: Get Distinct Purchase Identifiers, multiple receipt item tests
func testGetDistinctPurchaseIds_when_Receipt_then_resultIsNotNil() {
let receiptRequestDateOne = makeDateAtMidnight(year: 2020, month: 2, day: 20)
let purchaseDateOne = makeDateAtMidnight(year: 2020, month: 2, day: 1)
let purchaseDateTwo = makeDateAtMidnight(year: 2020, month: 1, day: 1)
let productId1 = "product1"
let productId2 = "product2"
let product1 = ReceiptItem(productId: productId1, purchaseDate: purchaseDateOne)
let product2 = ReceiptItem(productId: productId2, purchaseDate: purchaseDateTwo)
let receipt = makeReceipt(items: [product1, product2], requestDate: receiptRequestDateOne)
let getdistinctProductIdsResult = SwiftyStoreKit.getDistinctPurchaseIds(ofType: .autoRenewable, inReceipt: receipt)
XCTAssertNotNil(getdistinctProductIdsResult)
}
// MARK: Get Distinct Purchase Identifiers, multiple non unique product identifiers tests
func testGetDistinctPurchaseIds_when_nonUniqueIdentifiers_then_resultIsUnique() {
let receiptRequestDateOne = makeDateAtMidnight(year: 2020, month: 2, day: 20)
let purchaseDateOne = makeDateAtMidnight(year: 2020, month: 2, day: 1)
let purchaseDateTwo = makeDateAtMidnight(year: 2020, month: 2, day: 2)
let purchaseDateThree = makeDateAtMidnight(year: 2020, month: 2, day: 3)
let purchaseDateFour = makeDateAtMidnight(year: 2020, month: 2, day: 4)
let productId1 = "product1"
let productId2 = "product2"
let productId3 = "product1"
let productId4 = "product2"
let product1 = ReceiptItem(productId: productId1, purchaseDate: purchaseDateOne)
let product2 = ReceiptItem(productId: productId2, purchaseDate: purchaseDateTwo)
let product3 = ReceiptItem(productId: productId3, purchaseDate: purchaseDateThree)
let product4 = ReceiptItem(productId: productId4, purchaseDate: purchaseDateFour)
let receipt = makeReceipt(items: [product1, product2, product3, product4], requestDate: receiptRequestDateOne)
let getdistinctProductIdsResult = SwiftyStoreKit.getDistinctPurchaseIds(ofType: .autoRenewable, inReceipt: receipt)
let expectedProductIdsResult = Set([productId1, productId2, productId3, productId4])
XCTAssertEqual(getdistinctProductIdsResult, expectedProductIdsResult)
}
// MARK: Helper methods
func makeReceipt(items: [ReceiptItem], requestDate: Date) -> [String: AnyObject] {
let receiptInfos = items.map { $0.receiptInfo }
// Creating this with NSArray results in __NSSingleObjectArrayI which fails the cast to [String: AnyObject]
let array = NSMutableArray()
array.addObjects(from: receiptInfos)
return [
//"latest_receipt": [:],
"status": "200" as NSString,
"environment": "Sandbox" as NSString,
"receipt": NSDictionary(dictionary: [
"request_date_ms": requestDate.timeIntervalSince1970.millisecondsNSString,
"in_app": array // non renewing
]),
"latest_receipt_info": array // autoRenewable
]
}
func makeDateAtMidnight(year: Int, month: Int, day: Int) -> Date {
var dateComponents = DateComponents()
dateComponents.day = day
dateComponents.month = month
dateComponents.year = year
let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: dateComponents)!
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/InAppReceiptVerificatorTests.swift
================================================
//
// InAppReceiptVerificatorTests.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 17/05/2017.
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
@testable import SwiftyStoreKit
class TestReceiptValidator: ReceiptValidator {
var validateCalled = false
func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void) {
validateCalled = true
completion(.success(receipt: [:]))
}
}
class TestInAppReceiptRefreshRequest: InAppReceiptRefreshRequest {
override func start() {
// do nothing
}
}
extension VerifyReceiptResult: Equatable {
static public func == (lhs: VerifyReceiptResult, rhs: VerifyReceiptResult) -> Bool {
switch (lhs, rhs) {
case (.success, .success): return true
case (.error(let lhsError), .error(let rhsError)): return lhsError == rhsError
default: return false
}
}
}
extension ReceiptError: Equatable {
static public func == (lhs: ReceiptError, rhs: ReceiptError) -> Bool {
switch (lhs, rhs) {
case (.noReceiptData, .noReceiptData): return true
case (.noRemoteData, .noRemoteData): return true
case (.requestBodyEncodeError, .requestBodyEncodeError): return true
case (.networkError, .networkError): return true
case (.jsonDecodeError, .jsonDecodeError): return true
case (.receiptInvalid, .receiptInvalid): return true
default: return false
}
}
}
class InAppReceiptVerificatorTests: XCTestCase {
// MARK: refresh tests (no receipt url or no receipt data)
func testVerifyReceipt_when_appStoreReceiptURLIsNil_then_callsRefresh() {
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: nil)
var refreshCalled = false
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
refreshCalled = true
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { _ in
})
XCTAssertNotNil(request)
XCTAssertTrue(refreshCalled)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNotNil_noReceiptData_then_callsRefresh() {
let testReceiptURL = makeReceiptURL()
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: testReceiptURL)
var refreshCalled = false
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
refreshCalled = true
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { _ in
})
XCTAssertNotNil(request)
XCTAssertTrue(refreshCalled)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNotNil_hasReceiptData_forceRefreshIsTrue_then_callsRefresh() {
let testReceiptURL = makeReceiptURL()
writeReceiptData(to: testReceiptURL)
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: testReceiptURL)
var refreshCalled = false
let request = verificator.verifyReceipt(using: validator, forceRefresh: true, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
refreshCalled = true
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { _ in
})
XCTAssertNotNil(request)
XCTAssertTrue(refreshCalled)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNil_refreshCallbackError_then_errorNetworkError() {
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: nil)
let refreshError = NSError(domain: "", code: 0, userInfo: nil)
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
callback(.error(e: refreshError))
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { result in
XCTAssertEqual(result, VerifyReceiptResult.error(error: ReceiptError.networkError(error: refreshError)))
})
XCTAssertNotNil(request)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNil_refreshCallbackSuccess_receiptDataNotWritten_then_errorNoReceiptData_validateNotCalled() {
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: nil)
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
callback(.success)
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { result in
XCTAssertEqual(result, VerifyReceiptResult.error(error: ReceiptError.noReceiptData))
})
XCTAssertNotNil(request)
XCTAssertFalse(validator.validateCalled)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNil_noReceiptData_refreshCallbackSuccess_receiptDataWritten_then_errorNoReceiptData_validateNotCalled() {
let testReceiptURL = makeReceiptURL()
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: nil)
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
writeReceiptData(to: testReceiptURL)
callback(.success)
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { result in
XCTAssertEqual(result, VerifyReceiptResult.error(error: ReceiptError.noReceiptData))
})
XCTAssertNotNil(request)
XCTAssertFalse(validator.validateCalled)
removeReceiptData(at: testReceiptURL)
}
func testVerifyReceipt_when_appStoreReceiptURLIsNotNil_noReceiptData_refreshCallbackSuccess_receiptDataWritten_then_validateIsCalled() {
let testReceiptURL = makeReceiptURL()
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: testReceiptURL)
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
writeReceiptData(to: testReceiptURL)
callback(.success)
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { _ in
})
XCTAssertNil(request)
XCTAssertTrue(validator.validateCalled)
removeReceiptData(at: testReceiptURL)
}
// MARK: non-refresh tests (receipt url and data are set)
func testVerifyReceipt_when_appStoreReceiptURLIsNotNil_hasReceiptData_forceRefreshIsFalse_then_refreshNotCalled_validateIsCalled() {
let testReceiptURL = makeReceiptURL()
writeReceiptData(to: testReceiptURL)
let validator = TestReceiptValidator()
let verificator = InAppReceiptVerificator(appStoreReceiptURL: testReceiptURL)
let request = verificator.verifyReceipt(using: validator, forceRefresh: false, refresh: { (properties, callback) -> InAppReceiptRefreshRequest in
XCTFail("refresh should not be called if we already have a receipt")
return TestInAppReceiptRefreshRequest(receiptProperties: properties, callback: callback)
}, completion: { _ in
})
XCTAssertNil(request)
XCTAssertTrue(validator.validateCalled)
removeReceiptData(at: testReceiptURL)
}
// MARK: Helpers
func makeReceiptURL() -> URL {
guard let testFolderURL = try? FileManager.default.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false) else {
fatalError("Invalid test folder")
}
return testFolderURL.appendingPathComponent("receipt.data")
}
func writeReceiptData(to url: URL) {
guard let testReceiptData = NSData(base64Encoded: "encrypted-receipt", options: .ignoreUnknownCharacters) else {
fatalError("Invalid receipt data")
}
try? testReceiptData.write(to: url)
}
func removeReceiptData(at url: URL) {
try? FileManager.default.removeItem(at: url)
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/Info-Tests.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
BNDL
CFBundleShortVersionString
1.0
CFBundleVersion
1
================================================
FILE: Tests/SwiftyStoreKitTests/PaymentQueueControllerTests.swift
================================================
//
// PaymentQueueControllerTests.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
// swiftlint:disable function_body_length
import XCTest
import StoreKit
@testable import SwiftyStoreKit
class PaymentQueueControllerTests: XCTestCase {
// MARK: init/deinit
func testInit_registersAsObserver() {
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
XCTAssertTrue(spy.observer === paymentQueueController)
}
func testDeinit_removesObserver() {
let spy = PaymentQueueSpy()
_ = PaymentQueueController(paymentQueue: spy)
XCTAssertNil(spy.observer)
}
// MARK: Start payment
func testStartTransaction_QueuesOnePayment() {
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
let payment = makeTestPayment(productIdentifier: "com.SwiftyStoreKit.product1") { _ in }
paymentQueueController.completeTransactions(CompleteTransactions(atomically: true) { _ in })
paymentQueueController.startPayment(payment)
XCTAssertEqual(spy.payments.count, 1)
}
// MARK: SKPaymentTransactionObserver callbacks
func testPaymentQueue_when_oneTransactionForEachState_onePayment_oneRestorePurchases_oneCompleteTransactions_then_correctCallbacksCalled() {
// setup
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
let purchasedProductIdentifier = "com.SwiftyStoreKit.product1"
let failedProductIdentifier = "com.SwiftyStoreKit.product2"
let restoredProductIdentifier = "com.SwiftyStoreKit.product3"
let deferredProductIdentifier = "com.SwiftyStoreKit.product4"
let purchasingProductIdentifier = "com.SwiftyStoreKit.product5"
let transactions = [
makeTestPaymentTransaction(productIdentifier: purchasedProductIdentifier, transactionState: .purchased),
makeTestPaymentTransaction(productIdentifier: failedProductIdentifier, transactionState: .failed),
makeTestPaymentTransaction(productIdentifier: restoredProductIdentifier, transactionState: .restored),
makeTestPaymentTransaction(productIdentifier: deferredProductIdentifier, transactionState: .deferred),
makeTestPaymentTransaction(productIdentifier: purchasingProductIdentifier, transactionState: .purchasing)
]
var paymentCallbackCalled = false
let testPayment = makeTestPayment(productIdentifier: purchasedProductIdentifier) { result in
paymentCallbackCalled = true
if case .purchased(let product) = result {
XCTAssertEqual(product.productId, purchasedProductIdentifier)
} else {
XCTFail("expected purchased callback with product id")
}
}
var restorePurchasesCallbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
restorePurchasesCallbackCalled = true
XCTAssertEqual(results.count, 1)
let first = results.first!
if case .restored(let restoredPayment) = first {
XCTAssertEqual(restoredPayment.productId, restoredProductIdentifier)
} else {
XCTFail("expected restored callback with product")
}
}
var completeTransactionsCallbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { purchases in
completeTransactionsCallbackCalled = true
XCTAssertEqual(purchases.count, 2)
XCTAssertEqual(purchases[0].productId, failedProductIdentifier)
XCTAssertEqual(purchases[1].productId, deferredProductIdentifier)
}
// run
paymentQueueController.completeTransactions(completeTransactions)
paymentQueueController.startPayment(testPayment)
paymentQueueController.restorePurchases(restorePurchases)
paymentQueueController.paymentQueue(SKPaymentQueue(), updatedTransactions: transactions)
paymentQueueController.paymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue())
// verify
XCTAssertTrue(paymentCallbackCalled)
XCTAssertTrue(restorePurchasesCallbackCalled)
XCTAssertTrue(completeTransactionsCallbackCalled)
}
func testPaymentQueue_when_oneTransactionForEachState_onePayment_noRestorePurchases_oneCompleteTransactions_then_correctCallbacksCalled() {
// setup
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
let purchasedProductIdentifier = "com.SwiftyStoreKit.product1"
let failedProductIdentifier = "com.SwiftyStoreKit.product2"
let restoredProductIdentifier = "com.SwiftyStoreKit.product3"
let deferredProductIdentifier = "com.SwiftyStoreKit.product4"
let purchasingProductIdentifier = "com.SwiftyStoreKit.product5"
let transactions = [
makeTestPaymentTransaction(productIdentifier: purchasedProductIdentifier, transactionState: .purchased),
makeTestPaymentTransaction(productIdentifier: failedProductIdentifier, transactionState: .failed),
makeTestPaymentTransaction(productIdentifier: restoredProductIdentifier, transactionState: .restored),
makeTestPaymentTransaction(productIdentifier: deferredProductIdentifier, transactionState: .deferred),
makeTestPaymentTransaction(productIdentifier: purchasingProductIdentifier, transactionState: .purchasing)
]
var paymentCallbackCalled = false
let testPayment = makeTestPayment(productIdentifier: purchasedProductIdentifier) { result in
paymentCallbackCalled = true
if case .purchased(let payment) = result {
XCTAssertEqual(payment.productId, purchasedProductIdentifier)
} else {
XCTFail("expected purchased callback with product id")
}
}
var completeTransactionsCallbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { payments in
completeTransactionsCallbackCalled = true
XCTAssertEqual(payments.count, 3)
XCTAssertEqual(payments[0].productId, failedProductIdentifier)
XCTAssertEqual(payments[1].productId, restoredProductIdentifier)
XCTAssertEqual(payments[2].productId, deferredProductIdentifier)
}
// run
paymentQueueController.completeTransactions(completeTransactions)
paymentQueueController.startPayment(testPayment)
paymentQueueController.paymentQueue(SKPaymentQueue(), updatedTransactions: transactions)
paymentQueueController.paymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue())
// verify
XCTAssertTrue(paymentCallbackCalled)
XCTAssertTrue(completeTransactionsCallbackCalled)
}
func testPaymentQueue_when_oneTransactionForEachState_noPayments_oneRestorePurchases_oneCompleteTransactions_then_correctCallbacksCalled() {
// setup
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
let purchasedProductIdentifier = "com.SwiftyStoreKit.product1"
let failedProductIdentifier = "com.SwiftyStoreKit.product2"
let restoredProductIdentifier = "com.SwiftyStoreKit.product3"
let deferredProductIdentifier = "com.SwiftyStoreKit.product4"
let purchasingProductIdentifier = "com.SwiftyStoreKit.product5"
let transactions = [
makeTestPaymentTransaction(productIdentifier: purchasedProductIdentifier, transactionState: .purchased),
makeTestPaymentTransaction(productIdentifier: failedProductIdentifier, transactionState: .failed),
makeTestPaymentTransaction(productIdentifier: restoredProductIdentifier, transactionState: .restored),
makeTestPaymentTransaction(productIdentifier: deferredProductIdentifier, transactionState: .deferred),
makeTestPaymentTransaction(productIdentifier: purchasingProductIdentifier, transactionState: .purchasing)
]
var restorePurchasesCallbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
restorePurchasesCallbackCalled = true
XCTAssertEqual(results.count, 1)
let first = results.first!
if case .restored(let restoredPayment) = first {
XCTAssertEqual(restoredPayment.productId, restoredProductIdentifier)
} else {
XCTFail("expected restored callback with product")
}
}
var completeTransactionsCallbackCalled = false
let completeTransactions = CompleteTransactions(atomically: true) { payments in
completeTransactionsCallbackCalled = true
XCTAssertEqual(payments.count, 3)
XCTAssertEqual(payments[0].productId, purchasedProductIdentifier)
XCTAssertEqual(payments[1].productId, failedProductIdentifier)
XCTAssertEqual(payments[2].productId, deferredProductIdentifier)
}
// run
paymentQueueController.completeTransactions(completeTransactions)
paymentQueueController.restorePurchases(restorePurchases)
paymentQueueController.paymentQueue(SKPaymentQueue(), updatedTransactions: transactions)
paymentQueueController.paymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue())
// verify
XCTAssertTrue(restorePurchasesCallbackCalled)
XCTAssertTrue(completeTransactionsCallbackCalled)
}
// MARK: shouldAddStorePayment tests
func testPaymentQueue_when_shouldAddStorePaymentHandlerIsNil_then_shouldAddStorePaymentReturnsFalse() {
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
paymentQueueController.shouldAddStorePaymentHandler = nil
XCTAssertFalse(paymentQueueController.paymentQueue(SKPaymentQueue(), shouldAddStorePayment: SKPayment(), for: SKProduct()))
}
func testPaymentQueue_when_shouldAddStorePaymentHandlerReturnsTrue_then_shouldAddStorePaymentReturnsTrue() {
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
paymentQueueController.shouldAddStorePaymentHandler = { payment, product in
return true
}
XCTAssertTrue(paymentQueueController.paymentQueue(SKPaymentQueue(), shouldAddStorePayment: SKPayment(), for: SKProduct()))
}
func testPaymentQueue_when_shouldAddStorePaymentHandlerReturnsFalse_then_shouldAddStorePaymentReturnsFalse() {
let spy = PaymentQueueSpy()
let paymentQueueController = PaymentQueueController(paymentQueue: spy)
paymentQueueController.shouldAddStorePaymentHandler = { payment, product in
return false
}
XCTAssertFalse(paymentQueueController.paymentQueue(SKPaymentQueue(), shouldAddStorePayment: SKPayment(), for: SKProduct()))
}
// MARK: Helpers
func makeTestPaymentTransaction(productIdentifier: String, transactionState: SKPaymentTransactionState) -> TestPaymentTransaction {
let testProduct = TestProduct(productIdentifier: productIdentifier)
return TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: transactionState)
}
func makeTestPayment(productIdentifier: String, quantity: Int = 1, atomically: Bool = true, callback: @escaping (TransactionResult) -> Void) -> Payment {
let testProduct = TestProduct(productIdentifier: productIdentifier)
return Payment(product: testProduct, paymentDiscount: nil, quantity: quantity, atomically: atomically, applicationUsername: "", simulatesAskToBuyInSandbox: false, callback: callback)
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/PaymentQueueSpy.swift
================================================
//
// PaymentQueueSpy.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 17/01/2017.
// Copyright © 2017 musevisions. All rights reserved.
//
import SwiftyStoreKit
import StoreKit
class PaymentQueueSpy: PaymentQueue {
weak var observer: SKPaymentTransactionObserver?
var payments: [SKPayment] = []
var restoreCompletedTransactionCalledCount = 0
var finishTransactionCalledCount = 0
func add(_ observer: SKPaymentTransactionObserver) {
self.observer = observer
}
func remove(_ observer: SKPaymentTransactionObserver) {
if self.observer === observer {
self.observer = nil
}
}
func add(_ payment: SKPayment) {
payments.append(payment)
}
func restoreCompletedTransactions(withApplicationUsername username: String?) {
restoreCompletedTransactionCalledCount += 1
}
func finishTransaction(_ transaction: SKPaymentTransaction) {
finishTransactionCalledCount += 1
}
func start(_ downloads: [SKDownload]) {
}
func pause(_ downloads: [SKDownload]) {
}
func resume(_ downloads: [SKDownload]) {
}
func cancel(_ downloads: [SKDownload]) {
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/PaymentTransactionObserverFake.swift
================================================
//
// PaymentTransactionObserverFake.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 17/01/2017.
// Copyright © 2017 musevisions. All rights reserved.
//
#if os(iOS)
import UIKit
class PaymentTransactionObserverFake: NSObject {
}
#endif
================================================
FILE: Tests/SwiftyStoreKitTests/PaymentsControllerTests.swift
================================================
//
// PaymentsControllerTests.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
import StoreKit
@testable import SwiftyStoreKit
class PaymentsControllerTests: XCTestCase {
func testInsertPayment_hasPayment() {
let payment = makeTestPayment(productIdentifier: "com.SwiftyStoreKit.product1") { _ in }
let paymentsController = makePaymentsController(appendPayments: [payment])
XCTAssertTrue(paymentsController.hasPayment(payment))
}
func testProcessTransaction_when_onePayment_transactionStatePurchased_then_removesPayment_finishesTransaction_callsCallback() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
var callbackCalled = false
let payment = makeTestPayment(product: testProduct) { result in
callbackCalled = true
if case .purchased(let payment) = result {
XCTAssertEqual(payment.productId, productIdentifier)
XCTAssertEqual(payment.quantity, 1)
} else {
XCTFail("expected purchased callback with product id")
}
}
let paymentsController = makePaymentsController(appendPayments: [payment])
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .purchased)
let spy = PaymentQueueSpy()
let remainingTransactions = paymentsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertFalse(paymentsController.hasPayment(payment))
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransaction_when_onePayment_transactionStateFailed_then_removesPayment_finishesTransaction_callsCallback() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
var callbackCalled = false
let payment = makeTestPayment(product: testProduct) { result in
callbackCalled = true
if case .failed = result {
} else {
XCTFail("expected failed callback with error")
}
}
let paymentsController = makePaymentsController(appendPayments: [payment])
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .failed)
let spy = PaymentQueueSpy()
let remainingTransactions = paymentsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertFalse(paymentsController.hasPayment(payment))
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransaction_when_twoPaymentsSameId_firstTransactionStatePurchased_secondTransactionStateFailed_then_removesPayments_finishesTransactions_callsCallbacks() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct1 = TestProduct(productIdentifier: productIdentifier)
var callback1Called = false
let payment1 = makeTestPayment(product: testProduct1) { result in
callback1Called = true
if case .purchased(let payment) = result {
XCTAssertEqual(payment.productId, productIdentifier)
} else {
XCTFail("expected purchased callback with product id")
}
}
let testProduct2 = TestProduct(productIdentifier: productIdentifier)
var callback2Called = false
let payment2 = makeTestPayment(product: testProduct2) { result in
callback2Called = true
if case .failed = result {
} else {
XCTFail("expected failed callback with error")
}
}
let paymentsController = makePaymentsController(appendPayments: [payment1, payment2])
let transaction1 = TestPaymentTransaction(payment: SKPayment(product: testProduct1), transactionState: .purchased)
let transaction2 = TestPaymentTransaction(payment: SKPayment(product: testProduct2), transactionState: .failed)
let spy = PaymentQueueSpy()
let remainingTransactions = paymentsController.processTransactions([transaction1, transaction2], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertFalse(paymentsController.hasPayment(payment1))
XCTAssertFalse(paymentsController.hasPayment(payment2))
XCTAssertTrue(callback1Called)
XCTAssertTrue(callback2Called)
XCTAssertEqual(spy.finishTransactionCalledCount, 2)
}
func testProcessTransaction_when_twoPaymentsSameId_firstPayment_transactionStatePurchased_then_removesFirstPayment_finishesTransaction_callsCallback() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct1 = TestProduct(productIdentifier: productIdentifier)
var callback1Called = false
let payment1 = makeTestPayment(product: testProduct1) { result in
callback1Called = true
if case .purchased(let payment) = result {
XCTAssertEqual(payment.productId, productIdentifier)
} else {
XCTFail("expected purchased callback with product id")
}
}
let testProduct2 = TestProduct(productIdentifier: productIdentifier)
let payment2 = makeTestPayment(product: testProduct2) { _ in
XCTFail("unexpected callback for second payment")
}
let paymentsController = makePaymentsController(appendPayments: [payment1, payment2])
let transaction1 = TestPaymentTransaction(payment: SKPayment(product: testProduct1), transactionState: .purchased)
let spy = PaymentQueueSpy()
let remainingTransactions = paymentsController.processTransactions([transaction1], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
// First one removed, but second one with same identifier still there
XCTAssertTrue(paymentsController.hasPayment(payment2))
XCTAssertTrue(callback1Called)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransaction_when_onePayment_transactionStatePurchased_quantityIs2_then_removesPayment_finishesTransaction_callsCallback_correctQuantity() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let quantity = 2
let testProduct = TestProduct(productIdentifier: productIdentifier)
var callbackCalled = false
let payment = makeTestPayment(product: testProduct) { result in
callbackCalled = true
if case .purchased(let payment) = result {
XCTAssertEqual(payment.productId, productIdentifier)
XCTAssertEqual(payment.quantity, quantity)
} else {
XCTFail("expected purchased callback with product id")
}
}
let paymentsController = makePaymentsController(appendPayments: [payment])
let skPayment = SKMutablePayment(product: testProduct)
skPayment.quantity = quantity
let transaction = TestPaymentTransaction(payment: skPayment, transactionState: .purchased)
let spy = PaymentQueueSpy()
let remainingTransactions = paymentsController.processTransactions([transaction], on: spy)
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertFalse(paymentsController.hasPayment(payment))
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func makePaymentsController(appendPayments payments: [Payment]) -> PaymentsController {
let paymentsController = PaymentsController()
payments.forEach { paymentsController.append($0) }
return paymentsController
}
func makeTestPayment(product: SKProduct, atomically: Bool = true, callback: @escaping (TransactionResult) -> Void) -> Payment {
return Payment(product: product, paymentDiscount: nil, quantity: 1, atomically: atomically, applicationUsername: "", simulatesAskToBuyInSandbox: false, callback: callback)
}
func makeTestPayment(productIdentifier: String, atomically: Bool = true, callback: @escaping (TransactionResult) -> Void) -> Payment {
let product = TestProduct(productIdentifier: productIdentifier)
return makeTestPayment(product: product, atomically: atomically, callback: callback)
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/ProductsInfoControllerTests.swift
================================================
//
// ProductsInfoControllerTests.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
import Foundation
@testable import SwiftyStoreKit
class TestInAppProductRequest: InAppProductRequest {
var hasCompleted: Bool
var cachedResults: RetrieveResults?
private let productIds: Set
private let callback: InAppProductRequestCallback
init(productIds: Set, callback: @escaping InAppProductRequestCallback) {
self.productIds = productIds
self.callback = callback
self.hasCompleted = false
}
func start() {
}
func cancel() {
}
func fireCallback() {
callback(RetrieveResults(retrievedProducts: [], invalidProductIDs: [], error: nil))
}
}
class TestInAppProductRequestBuilder: InAppProductRequestBuilder {
var requests: [ TestInAppProductRequest ] = []
func request(productIds: Set, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest {
let request = TestInAppProductRequest(productIds: productIds, callback: callback)
requests.append(request)
return request
}
func fireCallbacks() {
requests.forEach {
$0.fireCallback()
}
requests = []
}
}
class ProductsInfoControllerTests: XCTestCase {
let sampleProductIdentifiers: Set = ["com.iap.purchase1"]
// Set of in app purchases to ask in different threads
let testProducts: Set = ["com.iap.purchase01",
"com.iap.purchase02",
"com.iap.purchase03",
"com.iap.purchase04",
"com.iap.purchase05",
"com.iap.purchase06",
"com.iap.purchase07",
"com.iap.purchase08",
"com.iap.purchase09",
"com.iap.purchase10"]
func testRetrieveProductsInfo_when_calledOnce_then_completionCalledOnce() {
let requestBuilder = TestInAppProductRequestBuilder()
let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder)
var completionCount = 0
productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in
completionCount += 1
}
requestBuilder.fireCallbacks()
XCTAssertEqual(completionCount, 1)
}
func testRetrieveProductsInfo_when_calledTwiceConcurrently_then_eachCompletionCalledOnce() {
let requestBuilder = TestInAppProductRequestBuilder()
let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder)
var completionCount = 0
productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in
completionCount += 1
}
productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in
completionCount += 1
}
requestBuilder.fireCallbacks()
XCTAssertEqual(completionCount, 2)
}
func testRetrieveProductsInfo_when_calledTwiceNotConcurrently_then_eachCompletionCalledOnce() {
let requestBuilder = TestInAppProductRequestBuilder()
let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder)
var completionCount = 0
productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in
completionCount += 1
}
requestBuilder.fireCallbacks()
XCTAssertEqual(completionCount, 1)
productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in
completionCount += 1
}
requestBuilder.fireCallbacks()
XCTAssertEqual(completionCount, 2)
}
func testRetrieveProductsInfo_when_calledConcurrentlyInDifferentThreads_then_eachcompletionCalledOnce_noCrashes() {
let requestBuilder = TestInAppProductRequestBuilder()
let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder)
var completionCallbackCount = 0
// Create the expectation not to let the test finishes before the other threads complete
let expectation = XCTestExpectation(description: "Expect downloads of product informations")
// Create the dispatch group to let the test verifies the assert only when
// everything else finishes.
let group = DispatchGroup()
// Dispatch a request for every product in a different thread
for product in testProducts {
DispatchQueue.global().async {
group.enter()
productInfoController.retrieveProductsInfo([product]) { _ in
completionCallbackCount += 1
group.leave()
}
}
}
DispatchQueue.global().asyncAfter(deadline: .now()+0.1) {
requestBuilder.fireCallbacks()
}
// Fullfil the expectation when every thread finishes
group.notify(queue: DispatchQueue.global()) {
XCTAssertEqual(completionCallbackCount, self.testProducts.count)
expectation.fulfill()
}
wait(for: [expectation], timeout: 10.0)
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/RestorePurchasesControllerTests.swift
================================================
//
// RestorePurchasesControllerTests.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 XCTest
import StoreKit
@testable import SwiftyStoreKit
class RestorePurchasesControllerTests: XCTestCase {
func testProcessTransactions_when_oneRestoredTransaction_then_finishesTransaction_callsCallback_noRemainingTransactions() {
let productIdentifier = "com.SwiftyStoreKit.product1"
let testProduct = TestProduct(productIdentifier: productIdentifier)
let transaction = TestPaymentTransaction(payment: SKPayment(product: testProduct), transactionState: .restored)
var callbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
callbackCalled = true
XCTAssertEqual(results.count, 1)
let restored = results.first!
if case .restored(let restoredPurchase) = restored {
XCTAssertEqual(restoredPurchase.productId, productIdentifier)
} else {
XCTFail("expected restored callback with product")
}
}
let restorePurchasesController = makeRestorePurchasesController(restorePurchases: restorePurchases)
let spy = PaymentQueueSpy()
let remainingTransactions = restorePurchasesController.processTransactions([transaction], on: spy)
restorePurchasesController.restoreCompletedTransactionsFinished()
XCTAssertEqual(remainingTransactions.count, 0)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 1)
}
func testProcessTransactions_when_twoRestoredTransactions_oneFailedTransaction_onePurchasedTransaction_then_finishesTwoTransactions_callsCallback_twoRemainingTransaction() {
let productIdentifier1 = "com.SwiftyStoreKit.product1"
let testProduct1 = TestProduct(productIdentifier: productIdentifier1)
let transaction1 = TestPaymentTransaction(payment: SKPayment(product: testProduct1), transactionState: .restored)
let productIdentifier2 = "com.SwiftyStoreKit.product2"
let testProduct2 = TestProduct(productIdentifier: productIdentifier2)
let transaction2 = TestPaymentTransaction(payment: SKPayment(product: testProduct2), transactionState: .restored)
let productIdentifier3 = "com.SwiftyStoreKit.product3"
let testProduct3 = TestProduct(productIdentifier: productIdentifier3)
let transaction3 = TestPaymentTransaction(payment: SKPayment(product: testProduct3), transactionState: .failed)
let productIdentifier4 = "com.SwiftyStoreKit.product4"
let testProduct4 = TestProduct(productIdentifier: productIdentifier4)
let transaction4 = TestPaymentTransaction(payment: SKPayment(product: testProduct4), transactionState: .purchased)
let transactions = [transaction1, transaction2, transaction3, transaction4]
var callbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
callbackCalled = true
XCTAssertEqual(results.count, 2)
let first = results.first!
if case .restored(let restoredPurchase) = first {
XCTAssertEqual(restoredPurchase.productId, productIdentifier1)
} else {
XCTFail("expected restored callback with product")
}
let last = results.last!
if case .restored(let restoredPurchase) = last {
XCTAssertEqual(restoredPurchase.productId, productIdentifier2)
} else {
XCTFail("expected restored callback with product")
}
}
let restorePurchasesController = makeRestorePurchasesController(restorePurchases: restorePurchases)
let spy = PaymentQueueSpy()
let remainingTransactions = restorePurchasesController.processTransactions(transactions, on: spy)
restorePurchasesController.restoreCompletedTransactionsFinished()
XCTAssertEqual(remainingTransactions.count, 2)
XCTAssertTrue(callbackCalled)
XCTAssertEqual(spy.finishTransactionCalledCount, 2)
}
func testRestoreCompletedTransactionsFailed_callsCallbackWithError() {
var callbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
callbackCalled = true
XCTAssertEqual(results.count, 1)
let first = results.first!
if case .failed = first {
} else {
XCTFail("expected failed callback with error")
}
}
let restorePurchasesController = makeRestorePurchasesController(restorePurchases: restorePurchases)
let error = NSError(domain: "SwiftyStoreKit", code: 0, userInfo: nil)
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
XCTAssertTrue(callbackCalled)
}
func testRestoreCompletedTransactionsFinished_callsCallbackWithNoTransactions() {
var callbackCalled = false
let restorePurchases = RestorePurchases(atomically: true) { results in
callbackCalled = true
XCTAssertEqual(results.count, 0)
}
let restorePurchasesController = makeRestorePurchasesController(restorePurchases: restorePurchases)
restorePurchasesController.restoreCompletedTransactionsFinished()
XCTAssertTrue(callbackCalled)
}
func makeRestorePurchasesController(restorePurchases: RestorePurchases?) -> RestorePurchasesController {
let restorePurchasesController = RestorePurchasesController()
restorePurchasesController.restorePurchases = restorePurchases
return restorePurchasesController
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/TestPaymentTransaction.swift
================================================
//
// TestPaymentTransaction.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
// swiftlint:disable variable_name
class TestPaymentTransaction: SKPaymentTransaction {
let _transactionState: SKPaymentTransactionState
let _payment: SKPayment
init(payment: SKPayment, transactionState: SKPaymentTransactionState) {
_transactionState = transactionState
_payment = payment
}
override var payment: SKPayment {
return _payment
}
override var transactionState: SKPaymentTransactionState {
return _transactionState
}
}
================================================
FILE: Tests/SwiftyStoreKitTests/TestProduct.swift
================================================
//
// TestProduct.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 StoreKit
// swiftlint:disable variable_name
class TestProduct: SKProduct {
var _productIdentifier: String = ""
override var productIdentifier: String {
return _productIdentifier
}
init(productIdentifier: String) {
_productIdentifier = productIdentifier
super.init()
}
}
================================================
FILE: scripts/build.sh
================================================
#!/bin/bash
bold=$(tput bold)
normal=$(tput sgr0)
echo "${bold}/*****************************/"
echo "/* Build: SwiftyStoreKit_iOS */"
echo "/*****************************/${normal}"
set -o pipefail && xcodebuild -project SwiftyStoreKit.xcodeproj -target SwiftyStoreKit_iOS | tee xcodebuild.log | xcpretty
echo ""
echo "${bold}/*******************************/"
echo "/* Build: SwiftyStoreKit_macOS */"
echo "/*******************************/${normal}"
set -o pipefail && xcodebuild -project SwiftyStoreKit.xcodeproj -target SwiftyStoreKit_macOS | tee xcodebuild.log | xcpretty
echo ""
echo "${bold}/******************************/"
echo "/* Build: SwiftyStoreKit_tvOS */"
echo "/******************************/${normal}"
set -o pipefail && xcodebuild -project SwiftyStoreKit.xcodeproj -target SwiftyStoreKit_tvOS | tee xcodebuild.log | xcpretty
echo ""
echo "${bold}/******************************/"
echo "/* Build: SwiftyStoreKit_watchOS */"
echo "/******************************/${normal}"
set -o pipefail && xcodebuild -project SwiftyStoreKit.xcodeproj -target SwiftyStoreKit_watchOS | tee xcodebuild.log | xcpretty
echo ""
echo "${bold}/****************************/"
echo "/* Run: SwiftyStoreKitTests */"
echo "/****************************/${normal}"
set -o pipefail && xcodebuild test -project SwiftyStoreKit.xcodeproj -scheme SwiftyStoreKitTests -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 6,OS=12.0' | tee xcodebuild.log | xcpretty
================================================
FILE: scripts/install_swiftlint.sh
================================================
#!/bin/bash
# Installs the SwiftLint package.
# Tries to get the precompiled .pkg file from Github, but if that
# fails just recompiles from source.
set -e
SWIFTLINT_PKG_PATH="/tmp/SwiftLint.pkg"
SWIFTLINT_PKG_URL="https://github.com/realm/SwiftLint/releases/download/0.39.2/SwiftLint.pkg"
wget --output-document=$SWIFTLINT_PKG_PATH $SWIFTLINT_PKG_URL
if [ -f $SWIFTLINT_PKG_PATH ]; then
echo "SwiftLint package exists! Installing it..."
sudo installer -pkg $SWIFTLINT_PKG_PATH -target /
else
echo "SwiftLint package doesn't exist. Compiling from source..." &&
git clone https://github.com/realm/SwiftLint.git /tmp/SwiftLint &&
cd /tmp/SwiftLint &&
git submodule update --init --recursive &&
sudo make install
fi