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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.