1

What would be the best way to wrap Purchases.shared.purchaserInfo to just return true or false when doing multiple comparisons in an If statement.

What I want to be able to do is to quickly check if the user has access to PRO features by having a method or a property that return true or false since I need to make multiple checks in an if statement, something like... if userHasAccess && someOtherCheck { // do something}

Is this a valid solution?

Singleton Class:

    class IAPHelper {

        static let shared = IAPHelper()

        func hasAccessToProFeatures()->Bool{
            var hasAccess:Bool?
            Purchases.shared.purchaserInfo { (purchaserInfo, error) in
                if let purchaserInfo = purchaserInfo {
                    if purchaserInfo.activeEntitlements.contains("myEntitlement") {
                        hasAccess = true
                    }else{
                        hasAccess = false
                    }
                }
            }
            return hasAccess!
        }
    }

Usage:

    if IAPHelper.shared.hasAccessToProFeatures() && someOtherCheck{
        // unlock PRO features
    }
fs_tigre
  • 10,650
  • 13
  • 73
  • 146

1 Answers1

2

Shared instances are not bad, however for such a small class you could declare hasAccessToProFeatures as a static variable instead.

class IAPHelper {

static var hasAccessToProFeatures: Bool {

    var hasAccess:Bool?
    Purchases.shared.purchaserInfo { (purchaserInfo, error) in
        if let purchaserInfo = purchaserInfo {
            if purchaserInfo.activeEntitlements.contains("myEntitlement") {
                hasAccess = true
            }else{
                hasAccess = false
            }
        }
    }

    guard let isProMember = hasAccess else {
        return false
    }

    return isProMember

  }

}

Then you could call it like:

if IAPHelper.hasAccessToProFeatures && someOtherCheck {
    // unlock PRO features
}
Barnyard
  • 273
  • 3
  • 11
  • @ Barnyard - I like your approach, but I think the `else` clause in `if purchaserInfo.activeEntitlements.contains("myEntitlement")` is redundant and can be removed since the `guard let` is taking care of that, right? – fs_tigre Jun 26 '19 at 11:37
  • 1
    You are right, guard will take care of instances where the `hasAccess` is false. – Barnyard Jun 26 '19 at 11:51
  • 1
    You could also replace the guard and current return statement with `return hasAccess ?? false`. – Barnyard Jun 26 '19 at 11:56