UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.