achat In-app en Swift avec un seul produit
Est-il un moyen simple de mettre en œuvre un achat in-app dans swift pour un seul produit?
je veux un bouton qui déclenche l'achat dans l'application comme un [ad-suppression] ou [unlock-premium-content]
je ne comprends pas la logique.
je suis en train de suivre et traduire ce tutoriel [Techotopia] http://www.techotopia.com/index.php/An_iOS_7_In-App_Purchase_Tutorial
mais c'est ma première fois avec le StoreKit Cadre, ainsi qu'avec Swift.
je veux juste connaître la logique de la transaction d'achat In-app avec le Framework StoreKit de Swift.
Merci!
3 réponses
étape 0: dans votre compte iTunes Connect, créez un achat In-App.
pour les achats simples, utilisez cette méthode:
- Import
import StoreKit
- Conforme à StoreKit Délégué
class YOURViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
- utilisez un utilisateur par défaut pour suivre les transactions
let defaults = NSUserDefaults.standardUserDefaults()
- numéro D'identification du produit. Celui-ci sera le même que dans votre iTunes Connect dans app purchase
var product_id: NSString?
override func viewDidLoad() {
product_id = "YOUR_PRODUCT_ID"
super.viewDidLoad()
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
//Check if product is purchased
if (defaults.boolForKey("purchased")){
// Hide a view or show content depends on your requirement
overlayView.hidden = true
} else if (!defaults.boolForKey("stonerPurchased")) {
print("false")
}
}
- Débloquer Le Contenu. C'est l'action de bouton qui initialisera l'achat
@IBAction func unlockAction(sender: AnyObject) {
print("About to fetch the products")
// We check that we are allow to make the purchase.
if (SKPaymentQueue.canMakePayments()) {
var productID:NSSet = NSSet(object: self.product_id!);
var productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID);
productsRequest.delegate = self;
productsRequest.start();
println("Fetching Products");
} else {
print("can't make purchases");
}
}
- Méthodes D'Aide
func buyProduct(product: SKProduct) {
println("Sending the Payment Request to Apple");
var payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment);
}
- Délégué Méthodes pour PEI
func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
var count : Int = response.products.count
if (count>0) {
var validProducts = response.products
var validProduct: SKProduct = response.products[0] as SKProduct
if (validProduct.productIdentifier == self.product_id) {
print(validProduct.localizedTitle)
print(validProduct.localizedDescription)
print(validProduct.price)
buyProduct(validProduct);
} else {
print(validProduct.productIdentifier)
}
} else {
print("nothing")
}
}
func request(request: SKRequest!, didFailWithError error: NSError!) {
print("Error Fetching product information");
}
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
print("Received Payment Transaction Response from Apple");
for transaction:AnyObject in transactions {
if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
switch trans.transactionState {
case .Purchased:
print("Product Purchased");
SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
defaults.setBool(true , forKey: "purchased")
overlayView.hidden = true
break;
case .Failed:
print("Purchased Failed");
SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
break;
case .Restored:
print("Already Purchased");
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
default:
break;
}
}
}
}
Swift > 3.0
import StoreKit
class YOURVIEWController:UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
let product_id: NSString = "com.some.inappid" // <!-- Change it to your inapp id
Dans votre viewDidLoad
ajouter
override func viewDidLoad() {
super.viewDidLoad()
SKPaymentQueue.default().add(self)
dans votre action de bouton d'achat
@IBAction func buyNowAction(_ sender: UIButton) {
if (SKPaymentQueue.canMakePayments()) {
let productID:NSSet = NSSet(array: [self.product_id as NSString]);
let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
productsRequest.delegate = self;
productsRequest.start();
print("Fetching Products");
} else {
print("can't make purchases");
}
}
dans votre bouton de restauration action
// MARK: - Restore In App Purchase
@IBAction func restoreAction(_ sender: UIButton) {
if (SKPaymentQueue.canMakePayments()) {
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().restoreCompletedTransactions()
} else {
// show error
}
}
Ajouter Délégués:
// SKProductRequest Delegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print(response.products)
let count : Int = response.products.count
if (count>0) {
let validProduct: SKProduct = response.products[0] as SKProduct
if (validProduct.productIdentifier == self.product_id as String) {
print(validProduct.localizedTitle)
print(validProduct.localizedDescription)
print(validProduct.price)
self.buyProduct(product: validProduct)
} else {
print(validProduct.productIdentifier)
}
} else {
print("nothing")
}
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction:AnyObject in transactions {
if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
self.dismissPurchaseBtn.isEnabled = true
self.restorePurchaseBtn.isEnabled = true
self.buyNowBtn.isEnabled = true
switch trans.transactionState {
case .purchased:
print("Product Purchased")
//Do unlocking etc stuff here in case of new purchase
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
break;
case .failed:
print("Purchased Failed");
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
break;
case .restored:
print("Already Purchased")
//Do unlocking etc stuff here in case of restor
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
default:
break;
}
}
}
}
//If an error occurs, the code will go to this function
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
// Show some alert
}
Dans l'app Purchas délégué de la Méthode :
func buyInApp()
{
if (SKPaymentQueue.canMakePayments())
{
let productID:NSSet = NSSet(object: "com.valueedge.plane_post");
let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
productsRequest.delegate = self;
productsRequest.start();
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse)
{
let count : Int = response.products.count
if (count>0)
{
let validProduct: SKProduct = response.products[0] as SKProduct
if (validProduct.productIdentifier == "com.valueedge.plane_post")
{
buyProduct(validProduct);
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
func buyProduct(product: SKProduct)
{
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
}
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])
{
for transaction:AnyObject in transactions
{
if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction
{
switch trans.transactionState
{
case .Purchased:
self.PaymentSuccess("Apple", details: "Apple(In-App)")
print("In App Payment Success")
SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
MBProgressHUD.hideHUDForView(self.view, animated: true)
break
case .Failed:
MBProgressHUD.hideHUDForView(self.view, animated: true)
SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
let alert = UIAlertController(title: "Planes Only", message: "Payment failed", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action:UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
break
case .Restored :
SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
MBProgressHUD.hideHUDForView(self.view, animated: true)
break
default:
MBProgressHUD.hideHUDForView(self.view, animated: true)
break
}
}
}
}
func restore()
{
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue)
{
for transact:SKPaymentTransaction in queue.transactions
{
if transact.transactionState == SKPaymentTransactionState.Restored
{
//let t: SKPaymentTransaction = transact as SKPaymentTransaction
//let prodID = t.payment.productIdentifier as String
//restore prodID
SKPaymentQueue .defaultQueue().finishTransaction(transact)
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
}
func paymentQueue(queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: NSError)
{
for transaction:SKPaymentTransaction in queue.transactions
{
if transaction.transactionState == SKPaymentTransactionState.Restored
{
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
MBProgressHUD.hideHUDForView(self.view, animated: true)
break
}
}
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
func request(request: SKRequest, didFailWithError error: NSError)
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
dans le bouton app cliqué événement:
@IBAction func In_App_Payment_Clicked(sender: AnyObject)
{
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
self.buyInApp()
}
Pour le développement de l'achat in-app pour ipad, même dans la simple façon dont vous avez besoin pour résoudre suivant sous-tâches qui ne se rapportent pas au codage:
- Registrer as developer et la création d'un ID D'application sous https://developer.apple.com/account/
- sélectionnez Certificats, IDs & Profiles.
- sélectionnez identificateurs > applications, et cliquez sur + pour créer une nouvelle application ID.
- assurez-vous que L'In-App L'achat est activé pour votre ID D'application.
- remplissez le contrat et les informations bancaires. Pour que la connexion à https://itunesconnect.apple.com/
- étape Importante