DomainDig/IPGeolocationService.swift

25 lines · 860 bytes

 1import Foundation
 2
 3struct IPGeolocationService {
 4    static func lookup(ip: String) async -> ServiceResult<IPGeolocation> {
 5        guard let url = URL(string: "https://ipapi.co/\(ip)/json/") else {
 6            return .error("Not a valid IP address")
 7        }
 8
 9        let request = URLRequest(url: url, timeoutInterval: 10)
10
11        do {
12            let (data, response) = try await URLSession.shared.data(for: request)
13
14            guard let httpResponse = response as? HTTPURLResponse,
15                  httpResponse.statusCode == 200 else {
16                return .error(URLError(.badServerResponse).localizedDescription)
17            }
18
19            let geolocation = try JSONDecoder().decode(IPGeolocation.self, from: data)
20            return .success(geolocation)
21        } catch {
22            return .error(error.localizedDescription)
23        }
24    }
25}