@@ -62,29 +62,42 @@ class AdService: ObservableObject {
6262 // The Worker reads request.cf.country server-side (trusted, can't be spoofed)
6363 // and returns the 2-letter country code as the response body.
6464 // Fallback: ipapi.co → system locale
65- private static let geoEndpoint = " https://service.h4ux.com/geo-service "
65+ private static let geoEndpoints = [
66+ " https://service.h4ux.com/geo-service " ,
67+ " https://billowing-term-c225.alon-f46.workers.dev " ,
68+ ]
6669
6770 private init ( ) {
6871 self . userCountry = UserDefaults . standard. string ( forKey: Self . countryKey)
6972 ?? Locale . current. region? . identifier ?? " US "
7073 self . currentAd = Self . defaultAd
71- detectCountryThenFetchAds ( )
74+ detectCountryThenFetchAds ( endpointIndex : 0 )
7275 }
7376
74- private func detectCountryThenFetchAds( ) {
75- guard let url = URL ( string: Self . geoEndpoint) else { fetchAds ( ) ; return }
77+ private func detectCountryThenFetchAds( endpointIndex: Int ) {
78+ guard endpointIndex < Self . geoEndpoints. count,
79+ let url = URL ( string: Self . geoEndpoints [ endpointIndex] ) else {
80+ fetchAds ( ) ; return
81+ }
7682
7783 var request = URLRequest ( url: url)
7884 request. setValue ( Secrets . geoWorkerKey, forHTTPHeaderField: " X-Tickr-Key " )
85+ request. timeoutInterval = 5
86+
87+ URLSession . shared. dataTask ( with: request) { [ weak self] data, response, error in
88+ let http = response as? HTTPURLResponse
7989
80- URLSession . shared . dataTask ( with : request ) { [ weak self ] data , _ , _ in
81- if let data = data,
90+ // Check if we got a valid 2-letter country code
91+ if let data = data, http ? . statusCode == 200 ,
8292 let code = String ( data: data, encoding: . utf8) ? . trimmingCharacters ( in: . whitespacesAndNewlines) ,
8393 code. count == 2 , code != " XX " {
8494 UserDefaults . standard. set ( code, forKey: Self . countryKey)
8595 DispatchQueue . main. async { self ? . userCountry = code }
96+ self ? . fetchAds ( )
97+ } else {
98+ // Fallback to next endpoint
99+ self ? . detectCountryThenFetchAds ( endpointIndex: endpointIndex + 1 )
86100 }
87- self ? . fetchAds ( )
88101 } . resume ( )
89102 }
90103
0 commit comments