-1

I'm tackling my first In-App Purchase set-up in my first Swift project. I'm trying to get an in-app bundle string from my UserDefaults, rather than bake it in as a fixed string, but I'm getting an error "fatal error: unexpectedly found nil while unwrapping an Optional value"

I'm calling my variable from the UserDefaults as follows:

var bundleIdentity : AnyObject!

NSUserDefaults.standardUserDefaults().synchronize()
    var userDefaults = NSUserDefaults.standardUserDefaults()

    if let myBundle: AnyObject? = userDefaults.objectForKey("bundle") {
        bundleIdentity = myBundle as String
    }

Now, I try to use it in my "getProductInfo" func:

func getProductInfo(){
    if SKPaymentQueue.canMakePayments(){
        let productID:NSSet = NSSet(object:self.bundleIdentity!)
        let request:SKProductsRequest = SKProductsRequest(productIdentifiers: productID)
        request.delegate = self
        request.start()
    }
}

I know the "bundleIdentity" is coming in, as I can printLn it as a string but I'm confused why I can't use it in the NSSet (object:self.bundleIdentity!) and get the error.

Any help would be much appreciated as I'm still a newbie to Swift!

Thanks

Richard B
  • 3
  • 1
  • The message means exactly what it says: this object is nil. You say you can println it as a string, but I don't see you doing it. The question is not whether you can println it in some other code. The question is what happens when you println it _right there_ at the time you try to hand it over to the NSSet. If you try, you will see that it is indeed nil. – matt Nov 10 '14 at 17:55

1 Answers1

0

You have declared bundleIdentity as optional (using ?), and then you have told the machine that it definitely has a value (using !). It is throwing a temper tantrum because you lied to it.

Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51
  • Thanks Ian,OK, so now making myBundle not optional, "if let myBundle: AnyObject! = userDefaults.objectForKey("bundle")" I still get the same error. – Richard B Nov 10 '14 at 20:27
  • Presumably because it still doesn't exist. The object held within `userDefaults` can certainly be `nil` if you haven't yet set a value to it. You should be checking for `nil` inside `getProductInfo`. – Ian MacDonald Nov 10 '14 at 20:41