Search code examples
swiftswift3

Accessing code in Swift 3 Error


New in Xcode 8 beta 4, NSError is bridged to the Swift Error protocol type. This affects StoreKit when dealing with failed SKPaymentTransactions. You ought to check to be sure the error didn't occur because the transaction was cancelled to know whether or not to show an error message to the user. You do this by examining the error's code. But with Error instead of NSError, there is no code defined. I haven't been able to figure out how to properly get the error code from Error.

This worked in the previous version of Swift 3:

func failedTransaction(_ transaction: SKPaymentTransaction) {
    if let transactionError = transaction.error {
        if transactionError.code != SKErrorCode.paymentCancelled.rawValue {
            //show error to user
        }
     }
     ...
}

Now that error is an Error not NSError, code is not a member.


Solution

  • Casting to SKError seems to be working for me in xCode 8 and Swift 3...

        guard let error = transaction.error as? SKError else {return}
        switch error.code {  // https://developer.apple.com/reference/storekit/skerror.code
        case .unknown: break
        case .paymentCancelled: break
        case .clientInvalid: break
        case .paymentInvalid: break
        case .paymentNotAllowed: break
        case .cloudServiceNetworkConnectionFailed: break
        case .cloudServicePermissionDenied: break
        case .storeProductNotAvailable: break
        }
    

    No need for rawValue.