Leave a rating/review
Working with cookies is pretty important, so it’s time to give you a good old fashioned cookie challenge.
In this challenge, I want you to make a request to a website and show all of the cookie names and values.
Here’s a hint to get you started: the code is very much the same that was demonstrated in the previous episode except now that you are looping through all the cookies instead of getting the first one.
Pause the video, try out the challenge, and I’ll see you in a bit.
How’d it go? Here’s a way you could have solved the challenge.
Open CookieView.swift and add this code in place of the *TODO:
guard let url = URL(string: "https://google.com”) else {
setDescription()
return
}
If the URL is created successfully, you then make the request to the website and handle any errors:
do {
let (_, response) = try await URLSession.shared.data(from: url)
} catch {
setDescription()
}
At the end of the do block, get the header fields from the response:
guard let httpResponse = response as? HTTPURLResponse,
let fields = httpResponse.allHeaderFields as? [String: String]
else {
setDescription()
return
}
And set the cookies from the response:
let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
setDescription(for: cookies)
Finally, and in order to visualize the cookies, update the setDescription function to print out the cookies:
func setDescription(for cookies: [HTTPCookie]? = nil) {
Task { @MainActor in
guard let cookies = cookies, !cookies.isEmpty else {
description = "Cookies: N/A"
return
}
var descriptionString = ""
for cookie in cookies {
descriptionString += "\(cookie.name): \(cookie.value)\n"
}
description = descriptionString
}
}
You update the guard to ensure you have cookies, then you create a string and begin appending the cookie’s details to it.
Finally, you set the description property with your string of cookie info. Build and run the project. Go to the Cookies tab. Tap Get Cookies. Voila!
Now you have all of the cookies being printed out, excellent work.
You’ve done great, great work here and throughout the course. Let’s wrap it all up in the next episode :)