GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Debugging Guard Let Try?

Forums > SwiftUI

I'm trying to understand how I can get visibility on one of the values in the middle of a guard, let, try? block cribbed almost exactly from the Apple Earthquakes project:

    guard let (data, response) = try? await session.data(for: request),
          let httpResponse = response as? HTTPURLResponse,
          httpResponse.statusCode == 200
    else {
        logger.debug("Failed to receive valid response and/or data!")
        throw PollError.missingData
    }

I needed to modify it slightly because I am sending a POST request to my API (unlike the Earthquakes demo), but I don't think that changes anything really.

If I'm understanding this correctly, in plain English, this code says: Wait for the results of the post request and store the httpResponse from the server in the response variable and the data returned by the server in the data variable. Then if we get a response, check to see that the server returned a 200 OK status code. If the POST didn't work or the data returned isn't valid (or is missing) or if the response code is not 200, then throw an error.

My problem is that -- for reasons I cannot comprehend -- I suspect the web server is sending back a 404 response because there's a CORS issue with the favicon.ico file. Obviously that has nothing to do with SwiftUI or my app, but I'm having a hell of a time debugging this to see if that is, in fact, the case.

How can I refactor this code to print() or otherwise log what the status code response is from the server?

2      

Hi,

You could try something like this:

guard let (data, response) = try? await session.data(from: url),
      let httpResponse = response as? HTTPURLResponse
//              httpResponse.statusCode == 200
else {
    logger.debug("Failed to received valid response and/or data.")
    throw QuakeError.missingData
}
print(httpResponse.statusCode)

2      

Hacking with Swift is sponsored by try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.