0
votes

I keep running into this error. I've tried numerous things, could someone tell me where I've gone wrong at? heres my code:

    let receiptFileURL = Bundle.main.appStoreReceiptURL
    let receiptData = try? Data(contentsOf: receiptFileURL!)
    let recieptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    guard let jsonDict: [String: AnyObject] = ["receipt-data" : recieptString! as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject] else {
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "mainVC", sender: nil)
        }
    }
2
["receipt-data" : recieptString! as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject] can't be nil, so it's not an optional, so guard let can't be done. Why do you use guard let or if let? To unwrap an optional, no? Here there is no optional. - Larme

2 Answers

0
votes

Since you are initializing the data, the ["receipt-data" : recieptString! as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject] cannot be nil, and thus it makes no sense to wrap it in guard. The only optional you have in this statement is recieptString, which you are force-unwrapping (can be causing crash if recieptString! is nil.

So change your guard statement to

guard let recieptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) else {
    // ...
    return
}

and then initialize the dictionary without guard or force unwrap:

let jsonDict: [String: AnyObject] = ["receipt-data" : recieptString as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject]
0
votes

You are going to create a non-optional dictionary so the error

Initializer for conditional binding must have Optional type, not '[String : AnyObject]'

reminds you that you cannot optional bind a non-optional type. Remove the guard expression.

By the way a JSON collection type does never contain AnyObject values, this avoid the ugly bridge cast along the way, and you can omit the options parameter in base64EncodedString

let receiptFileURL = Bundle.main.appStoreReceiptURL!
let receiptData = try! Data(contentsOf: receiptFileURL)
let receiptString = receiptData.base64EncodedString()
let jsonDict : [String: Any] = ["receipt-data" : receiptString, "password" : IAPProduct.apiID.rawValue]
// DispatchQueue.main.async {
//    self.performSegue(withIdentifier: "mainVC", sender: nil)
// }