使用ipdata.co API的Swift IP信息查找库
介绍
ipdata.co提供每天最多1500次请求的免费API密钥。
ipdata API文档ipdata
IPDataDotCo
允许您创建请求API所需的URLRequest
,然后您可以将其包含到您的网络工作流程中。
要求
- iOS 8.0+ / macOS 10.10+
- Swift 5+
使用方法
// Prepare the API to use your api key
let settings = IPDataDotCo.Settings(apiKey: "YOUR_API_KEY")
// If the api enpoint has changed (default: https://api.ipdata.co), you can use
let settings = IPDataDotCo.Settings(host: "HTTPS://NEW_ENDPOINT", apiKey: "YOUR_API_KEY")
// create a new `IPDataDotCo` with your settings
let ipdata = IPDataDotCo(with: settings)
// for a call to look up your current ip
let request = ipdata.lookupRequest()
// for a call to look up a specific ip
let request = ipdata.lookupRequest(ip: "8.8.8.8")
// for a call to look up a specific ip's country name with a link to it's flag png.
let request = ipdata.lookupRequest(ip: "8.8.8.8", for: [.countryName, .flag])
此调用需要自定义解析响应JSON
// for a call to look up a specific ip's country name
let request = ipdata.lookupRequest(ip: "8.8.8.8", for: .countryName)
对付费用户
// for a call to look up a bulk of ips (max 100 ip per request)
let request = ipdata.bulkLookUpRequest(ips: ["8.8.8.8", "1.1.1.1"])
响应的解析可能是
// use of `IPDataDotCo.JSONRootObject` to decode the JSON
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let http = response as? HTTPURLResponse {
// check status error / http.statusCode
// **200** successful response
// **400** bad ip or bulk with more than 100 ips
// **401** missing api-key
// **403** quota exceeded or not a valid api-key
}
if let data = data {
// for normal requests, but the one with only 1 field
let object = try? JSONDecoder().decode(IPDataDotCo.JSONRootObject.self, from: data)
// for bulk request
let object = try? JSONDecoder().decode([IPDataDotCo.JSONRootObject].self, from: data)
// ...
}
}
task.resume()
许可
IPDataDotCo遵循MIT许可协议。有关详细信息,请参阅LICENSE
文件。