skip to Main Content

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

Answers


  1. 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]
    
    Login or Signup to reply.
  2. 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)
    // }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search