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

Day 60: error 403 when trying to fetch friendface.json

Forums > 100 Days of SwiftUI

When I try to fetch friendface.json for the challenge, I get an HTTP 403 error.

Here is the code where I get the error.

class JUsers: ObservableObject {
    @Published var items = [JUser]()

    init() {
        let json = "https://www.hackingwithswift.com/samples/friendface.json"
        guard let url = URL(string: json) else {
            print("Invalid URL.")
            return
        }
        var request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in

            if let error = error {
                fatalError("Network error: " + error.localizedDescription ?? "Unknown error")
            }
            guard let response = response as? HTTPURLResponse else {
                fatalError("Not a HTTP response")
            }
            guard response.statusCode >= 200, response.statusCode < 300 else {
                fatalError("Invalid HTTP status code: \(response.statusCode)")
            }
            guard let data = data else {
                print("No data : \(error?.localizedDescription ?? "Unknown error").")
                return
            }

            let decoder = JSONDecoder()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
            decoder.dateDecodingStrategy = .formatted(formatter)
            if let decodedResponse = try? JSONDecoder().decode([JUser].self, from: data) {
                DispatchQueue.main.async {
                    self.items = decodedResponse
                }
            } else {
                print("Invalid server response: \(error?.localizedDescription ?? "Unknown error").")
                return
            }
        }.resume()
    }
}

And the error:

Fatal error: Invalid HTTP status code: 403: file /Users/billgates/Desktop/SwiftUI/60- consolidation user and friends/userAndFriends/userAndFriends/ContentView.swift, line 102
2020-07-17 09:38:25.170854+0200 userAndFriends[53332:910076] Fatal error: Invalid HTTP status code: 403: file /Users/billgates/Desktop/SwiftUI/60- consolidation user and friends/userAndFriends/userAndFriends/ContentView.swift, line 102

Does anyone have any idea what caused the error?

I can get the file without error in Safari or curl in Terminal.

2      

Did you ever figure this out? I'm currently stuck on this step. I haven't gone down the road of debugging the error and such, but it just doesn't work.

2      

is the file the exact same name making sure its lower case and added to your project?

2      

I am not sure of the cause but think it might be to do with the date Try using

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

I have included my project on this for reference

struct ContentView: View {
    @State private var users = [User]()

    var body: some View {
        NavigationView {
            List {
                ForEach(users, id: \.id) { user in
                   UserRow(user: user)
                }
            }
            .navigationTitle("User Profiles")
        }
        .onAppear(perform: loadData)

    }

    func loadData() {
        guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
            fatalError("Invalid URL")
        }

        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601

            if let data = data {
                if let decodedUsers = try? decoder.decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        users = decodedUsers
                    }

                    return
                }
            }

            print("Fetch failed \(error?.localizedDescription ?? "Unknown Error")")
        }.resume()
    }
}

UserRow file

import SwiftUI

struct UserRow: View {
    let user: User

    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text(user.name)
                    .font(.title3)
                    .bold()
                Spacer()
                Text("Joined: \(user.registered, style: .date)")
                    .foregroundColor(.secondary)
            }

            Text(user.company)
        }
    }
}

struct UserRow_Previews: PreviewProvider {
    static var previews: some View {
        UserRow(user: User.example)
            .previewLayout(.sizeThatFits)
    }
}

User file

import Foundation

struct User: Identifiable, Decodable {
    let id: String
    let isActive: Bool
    let name: String
    let age: Int
    let company: String
    let email: String
    let address: String
    let about: String
    let registered: Date
    let tags: [String]
    let friends: [Friend]

    struct Friend: Identifiable, Decodable {
        let id: String
        let name: String
    }

    #if DEBUG
    // show in preview set up only
    static let example = User(
        id: "0",
        isActive: true,
        name: "Test Name",
        age: 99,
        company: "Test.inc",
        email: "test@test.com",
        address: "1 Test drive", about: "Occaecat consequat elit aliquip magna laboris dolore laboris sunt officia adipisicing reprehenderit sunt. Do in proident consectetur labore. Laboris pariatur quis incididunt nostrud labore ad cillum veniam ipsum ullamco. Dolore laborum commodo veniam nisi. Eu ullamco cillum ex nostrud fugiat eu consequat enim cupidatat. Non incididunt fugiat cupidatat reprehenderit nostrud eiusmod eu sit minim do amet qui cupidatat. Elit aliquip nisi ea veniam proident dolore exercitation irure est deserunt.\r\n", registered: Date(), tags: ["cillum"], friends: [])
    #endif
}

2      

NigelGee - this was very helpful... Thanks!

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.