简体   繁体   中英

URLSession.Datatask returns 0 bytes of data

Trying to figure this one out, I'm stumped. When making a REST call to get json data back from a response (GET or POST, each should return data) I get back 0 bytes.

This is pre-serialization. The POST successfully creates a message on the backend, and the backend shows a response being sent; with charles proxy on, I've confirmed that there is a response with valid JSON data.

Any ideas why this would be failing ONLY in iOS? Postman/Charles proxy (from the iOS calls!) shows valid data in the response, but the debugger picks up nothing.

Thanks in advance for anything thoughts.

    let components = URLComponents(string: "mysuperValidURL.com")

    guard let url = components?.url else {
        return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    setUrlRequestToken(request: &request)

    let message = ChatMessage(content: message, group: group, userId: userId)

    let jsonEncoder = JSONEncoder()

    guard let data = try? jsonEncoder.encode(message) else {
        return
    }

    URLSession.shared.uploadTask(with: request, from: data) { (data, response, error) in
        // Here there be 0 bytes
    }.resume()

}

Data will sometimes come back as 0 bytes in the debugger; add a print with debug description to ensure you're getting data. In this case it was a failure of the debugger mixed with a later serialization error that caused it to appear to be broken.

TLDR; don't trust the realtime debugger, use some prints to sanity check.

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