Search code examples
iosswiftin-app

In App purchase swift


I'm trying to add In-app purchase in my app for the first time. There is no guide with swift language on the net. So I started to convert Obj-c to swift but I don't know what mean this line and how I can convert it into swift.

proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;

from this guide: http://troybrant.net/blog/2010/01/in-app-purchases-a-full-walkthrough/

extract:

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response    
{
    NSArray *products = response.products;
    proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;
    if (proUpgradeProduct)
    {
        NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
        NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
        NSLog(@"Product price: %@" , proUpgradeProduct.price);
        NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
    }

    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
        NSLog(@"Invalid product id: %@" , invalidProductId);
    }    

    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData
    [productsRequest release];

    [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerProductsFetchedNotification object:self userInfo:nil];
} 

Please if anyone know In-App purchase guide in swift it will be so nice !


Solution

  • The trick is to know what the errors are saying, but its fixed by typing things correctly using optionals

    var products = response.products
    var proUpgradeProductOpt:SKProduct? = products.count == 1 ? products.first as SKProduct? : nil
    if let proUpgradeProduct = proUpgradeProductOpt {
        println("Product title: \(proUpgradeProduct.localizedTitle)")
        println("Product description: \(proUpgradeProduct.localizedDescription)")
        println("Product price: \(proUpgradeProduct.price)")
        println("Product id: \(proUpgradeProduct.productIdentifier)")
    }