aboutsummaryrefslogtreecommitdiff
path: root/DomainDig/IPGeolocationService.swift
blob: 809dd289f0a32f52253dd129bc268c29b95baf01 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Foundation

struct IPGeolocationService {
    static func lookup(ip: String) async -> ServiceResult<IPGeolocation> {
        let url = URL(string: "https://ipapi.co/\(ip)/json/")!
        let request = URLRequest(url: url, timeoutInterval: 10)

        do {
            let (data, response) = try await URLSession.shared.data(for: request)

            guard let httpResponse = response as? HTTPURLResponse,
                  httpResponse.statusCode == 200 else {
                return .error(URLError(.badServerResponse).localizedDescription)
            }

            let geolocation = try JSONDecoder().decode(IPGeolocation.self, from: data)
            return .success(geolocation)
        } catch {
            return .error(error.localizedDescription)
        }
    }
}