Search code examples
swiftin-app-purchasestorekitswiftystorekit

Retrieve product localised price - Unexpected non-void return value in void function


I am using SwiftyStoreKit to implement iAP within my project. I have a auto-renewable subscription that users can purchase and restore. This seems to work fine however I am having issues when retrieving the product information to display to the UI.

I am trying to get the localised price to display, the price returned is the yearly cost so I need to divide the number by 12 to also display it as a monthly cost. However when getting the price and trying to return to value I get the following error:

Unexpected non-void return value in void function

Setting the button value

let subscribeButton = subscriptionManager.getSubscriptionPricePerMonth(isYearly: false)
subscribeButton(monthlyCost, for: .normal)

Retrieving the price

//Get prices

func getSubscriptionPricePerMonth() -> String {
    let productId = getProductId()


    NetworkActivityIndicatorManager.networkOperationStarted()
    SwiftyStoreKit.retrieveProductsInfo([productId]) { result in
        NetworkActivityIndicatorManager.networkOperationFinished()

        if let product = result.retrievedProducts.first {

            let priceString = product.localizedPrice!
            return priceString
        } else if let invalidProductId = result.invalidProductIDs.first {
              //return ("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
            print("Could not retrieve product info\(invalidProductId)")
        } else {
            let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
            //return ("Could not retrieve product info, \(errorString)")
            print("\(errorString)")

        }
    }

}

Solution

  • Unexpected non-void return value in void function

    Error says, that you are trying to return some value from the void function.

    Now, let's understand your case.

    Your actual function is

    func getSubscriptionPricePerMonth() -> String {}
    

    which you are expecting to return you some value as a String. But looking at the code inside, there you are using asynchronous block, which has void return type

    SwiftyStoreKit.retrieveProductsInfo([productId]) { result -> Void in 
      // Here you are returning some values after parsing the data, which is not allowed.
    }
    

    For returning something out of the block, you can use DispatchGroup to make it synchronous

    Hope this helps.