简体   繁体   中英

URLSession dataTask returns with no error and no data, causing SwiftyStoreKit.ReceiptError error 1

Why would the following code cause URLSession to return nil for both data and error ?

let task = URLSession.shared.dataTask(with: storeRequest as URLRequest) { data, _, error -> Void in

    // there is an error
    if let networkError = error {
        print("There was a network error")
        return
    }

    // there is no data
    guard let safeData = data else {
        print("No network error, but no data either")
        return
    }
...

On running this code, one user hits the No network error, but no data either line.

According to Apple's docs on URLSession.dataTask :

If the request completes successfully, the data parameter of the completion handler block contains the resource data, and the error parameter is nil. If the request fails, the data parameter is nil and the error parameter contain information about the failure.

I read that as: either data or error should always be non-nil. But that doesn't seem to be happening here. In what situation would both be nil?

(It if helps - the URL in question is the iTunes receipt validation API at https://buy.itunes.apple.com/verifyReceipt and the affected users are the reviewers at Apple, who are generally unwilling to assist in debug. This code is actually part of SwiftyStoreKit and it causes the error SwiftyStoreKit.ReceiptError error 1 for the reviewer - but never for anyone else.)

This could possibly depend on the HTTPURLResponse that you are ignoring in the completion handler of the dataTask ( documentation for URLSession.dataTask indicates that the response, while of type URLResponse , is actually of type HTTPURLResponse - so it would have a statusCode property that would be helpful to understand the result of your request..

The request may very well have been successful, but with no data returned (ie a 204 No Content response or a 300 Redirect response). These would not have a data response, but would also not have an error response, as the request did not fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM