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

SOLVED: Fetching localized json

Forums > SwiftUI

I have a json file in the bundle but would like to move to a https site that I can call, however at the moment the complier choose the lang of the json that has been translated from user setting. But a network call will allway call the same json. I have come up with this and it works but if anyone has a better way

@Environment(\.locale) var locale

Network call

func fetch() async {
    let lang = "\(locale)"
    switch lang.prefix(2) {
    case "hu":
        urlString = "https://example.com/AuditItems-hu.json"
    case "pl":
        urlString = "https://example.com/AuditItems-pl.json"
    case "fr":
        urlString = "https://example.com/AuditItems-fr.json"
    default:
        urlString = "https://example.com/AuditItems.json"
    }

    do  {
        async let items = try await URLSession.shared.decode([Audit].self, from: urlString)
        auditItems = try await items
    } catch {
        print("Failed to fetch data!")
    }
}

1      

I would do something like this instead:

//first...
extension Locale {
    var urlString: String {
        //if writing for iOS 16+, use self.language.languageCode.identifier instead
        guard let lang = self.languageCode else {
            return "https://example.com/AuditItems.json"
        }

        switch lang {
        case "hu": return "https://example.com/AuditItems-hu.json"
        case "pl": return "https://example.com/AuditItems-pl.json"
        case "fr": return "https://example.com/AuditItems-fr.json"
        default: return "https://example.com/AuditItems.json"
        }
    }
}

//and then...
func fetch() async {
    do  {
        async let items = try await URLSession.shared.decode([Audit].self, from: locale.urlString)
        auditItems = try await items
    } catch {
        print("Failed to fetch data!")
    }
}

(But probably with a better property name than urlString.)

1      

Cheers @roosterboy Make the call a lot cleaner

PS used auditURL

1      

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.