Giter Club home page Giter Club logo

ios-swift-in-app-purchases-sample's Introduction

iOS Swift In-App-Purchases

I would like to tell how to create a simple application with in-app-purchases using Swift.

First of all you need to create product IDs in iTunes Connect for your application.

alt tag alt tag

Lets create a class InAppPurchase. Inherited from the following protocols:

class InAppPurchase : NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver

InAppPurchase class will be singleton, for easy management of purchases.

class var sharedInstance : InAppPurchase {
    struct Static {
        static var onceToken: dispatch_once_t = 0
        static var instance: InAppPurchase? = nil
    }
    dispatch_once(&Static.onceToken) {
        Static.instance = InAppPurchase()
    }
    return Static.instance!
}

Add some constants for notifications:

let kInAppProductPurchasedNotification = "InAppProductPurchasedNotification"
let kInAppPurchaseFailedNotification   = "InAppPurchaseFailedNotification"
let kInAppProductRestoredNotification  = "InAppProductRestoredNotification"
let kInAppPurchasingErrorNotification  = "InAppPurchasingErrorNotification"

And for product IDs:

let unlockTestInAppPurchase1ProductId = "com.testing.iap1"
let unlockTestInAppPurchase2ProductId = "com.testing.iap2"

In the initialization of class, we need to add a observer:

SKPaymentQueue.defaultQueue().addTransactionObserver(self)

For starting of making purchase, we need to run a product request:

if SKPaymentQueue.canMakePayments() {
    let productID: NSSet = NSSet(object: productIdentifier)
    let productsRequest: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set)
    productsRequest.delegate = self
    productsRequest.start()
}
else {
    print(“Сan’t make purchases”)
}

After that if is it a success, will be called:

func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
    var count: Int = response.products.count
    if count > 0 {
        let validProduct: SKProduct = response.products[0] as! SKProduct
        buyProduct(validProduct)
    }
    else {
        print(“No products”)
    }
}

If error:

func request(request: SKRequest!, didFailWithError error: NSError!) {
    print("Error %@ \(error)")
}

In the buyProduct method we need to add a payment to payment queue:

let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment)

And after that will be called paymentQueue callback:

func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
    for transaction: AnyObject in transactions {
        if let trans: SKPaymentTransaction = transaction as? SKPaymentTransaction {
            switch trans.transactionState {
                case .Purchased:
                    SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                break
 
                case .Failed:
                    SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                break

                case .Restored:
                    SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                break
           
                default:
                break
        }
    }
}

If you did everything right, you should see the similar:

alt tag alt tag alt tag

For testing the app, please use sandbox accounts, which you can create in iTunes Connect.

For updating UI in your application in the example I use notifications, and for checking if already unlocked purchases or not, I use NSUserDefaults.

Please see the full sample in this repository, feel free to use and don’t forget to like the repository :) Thanks for attention.

ios-swift-in-app-purchases-sample's People

Contributors

matthewberryman avatar maximbilan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ios-swift-in-app-purchases-sample's Issues

tvOS

I tried to use this code in an app for the Apple TV (tvOS) but it doesn't work. I don't get any build errors either.
Can someone please make a small tvOS demo?

Check the subscription

which is the best way to check the validity of the subscription in a UIViewController class and to perform an action if the subscription is valid.

`class LoadScreenViewController: UIViewController {
     static let sharedInstance = LoadScreenViewController()
    
    //ActivityIndicator Declarieren
    var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

   // from here check the subscription (InAppPurchase.swift) and do an actionon

        //ActivityIndicator Implementieren um das Ladesymbol anzuzeigen
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white
        view.addSubview(activityIndicator)
        
        activityIndicator.startAnimating()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 12.0) { // Change `2.0` to the desired number of seconds.
            self.activityIndicator.stopAnimating()
            self.selectSubscription // select a subscriptionon
        }
        
    }`

Thank you!

Great!

Dear maximbilan.

Very thanks for your code.

But my product id is invalid.
I hope you check my settings.

BundleID : com.polaris.InAppTest
Product id: com.polaris.InAppTest.inviting

I want to know your email & skype.

Regards.

Makes no sense

Here is my debug output:

than sct data length
Fetching Products
Got the request from Apple
No products

Here is my
let unlockTestInAppPurchase1ProductId = "AppUnlock"

Here is my iTunes Connect
image

Please help this makes no sense

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.