实战指南:用Swift处理代理IP的JSON数据存储
在移动应用开发中,经常需要处理来自API的代理IP数据。本文将以天启代理的API响应为例,演示如何用Swift将JSON数据转换为本地文件,并提供可直接运行的代码示例。
准备工作:配置代理IP环境
首先需要获取有效的代理IP服务,这里推荐天启代理的企业级服务。其API响应格式简洁规范,适合作为示例:
{
"proxy_list": [
{
"ip": "123.45.67.89",
"port": 8080,
"protocol": "socks5",
"city": "上海",
"expire_time": "2024-03-20T12:00:00Z"
}
],
"status": "success"
}
注意使用前需在项目中导入Alamofire网络库,在Podfile中添加:
pod 'Alamofire', '~> 5.6'
核心代码实现步骤
以下代码演示完整的数据获取与存储流程:
import Alamofire
struct ProxyIP: Codable {
let ip: String
let port: Int
let protocolType: String
let city: String
let expireTime: String
enum CodingKeys: String, CodingKey {
case ip, port, city
case protocolType = "protocol"
case expireTime = "expire_time"
}
}
class ProxyManager {
let apiUrl = "https://api.tianqidaili.com/v2/get_proxy"
func fetchAndSaveProxies() {
AF.request(apiUrl).responseDecodable(of: [ProxyIP].self) { response in
switch response.result {
case .success(let proxies):
self.saveToFile(proxies: proxies)
case .failure(let error):
print("请求失败: \(error.localizedDescription)")
}
}
}
private func saveToFile(proxies: [ProxyIP]) {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let jsonData = try encoder.encode(proxies)
if let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let filePath = documentPath.appendingPathComponent("proxy_list.json")
try jsonData.write(to: filePath)
print("文件保存成功:\(filePath.path)")
}
} catch {
print("文件保存失败: \(error.localizedDescription)")
}
}
}
代码关键点解析
1. 模型映射技巧:使用CodingKeys处理字段名称差异,特别是protocol
这个系统保留字
2. 网络请求优化:Alamofire的responseDecodable
方法自动完成JSON解析,相比原生URLSession更简洁
3. 文件存储路径:优先使用系统文档目录,保证iOS沙盒机制下的存储安全
参数 | 说明 | 天启代理优势 |
---|---|---|
protocolType | 代理协议类型 | 支持HTTP/HTTPS/SOCKS5 |
city | 节点所在城市 | 全国200+城市覆盖 |
expireTime | IP有效期 | 自建机房纯净网络 |
常见问题QA
Q:文件保存失败如何处理?
A:检查沙盒权限设置,确保有写入文档目录的权限。天启代理的API响应时间<1秒,可排除网络超时因素
Q:中文内容出现乱码?
A:在encoder设置encoder.outputFormatting = .prettyPrinted
后,添加encoder.encoding = .utf8
Q:如何实现IP自动更新?
A:建议配合天启代理的高可用接口(可用率≥99%),设置定时任务定期请求新IP并覆盖旧文件
最佳实践建议
在真实项目中使用时,建议:
- 添加IP有效性验证逻辑,利用天启代理的≤10ms低延迟特性快速检测
- 对敏感数据做加密存储,使用iOS系统提供的数据保护API
- 建立本地IP池管理机制,根据业务需求自动切换不同节点
通过本文方案,开发者可以快速构建稳定的代理IP管理模块。天启代理的优质IP资源和标准化API接口,配合合理的本地存储策略,能有效提升应用的数据采集效率和稳定性。