iOS Alamofire库的使用

Alamofire 是 iOS/macOS 开发中最常用的网络请求库之一,基于 Swift 编写,封装了 URLSession,提供了链式调用、JSON 解析、文件上传/下载等高级功能。以下是 Alamofire 的具体用法和示例,涵盖常见场景。


  1. 安装 Alamofire
    通过 CocoaPods 安装
    在 Podfile 中添加:
ruby 复制代码
pod 'Alamofire', '~> 5.8'

然后运行 pod install。

通过 Swift Package Manager (SPM)

在 Xcode 的 File > Add Packages 中输入:

复制代码
https://github.com/Alamofire/Alamofire.git 

  1. 基本用法
    (1) 发起 GET 请求
swift 复制代码
import Alamofire 
 
AF.request("https://httpbin.org/get").response { response in 
    switch response.result {
    case .success(let data):
        print("请求成功: \(String(describing: data))")
    case .failure(let error):
        print("请求失败: \(error)")
    }
}

(2) 带参数的 GET 请求

swift 复制代码
let parameters = ["page": 1, "limit": 10]
 
AF.request("https://httpbin.org/get", parameters: parameters).responseJSON { response in 
    switch response.result {
    case .success(let json):
        print("JSON 数据: \(json)")
    case .failure(let error):
        print("请求失败: \(error)")
    }
}

(3) 发起 POST 请求

swift 复制代码
let parameters = ["username": "test", "password": "123456"]
 
AF.request("https://httpbin.org/post", method: .post, parameters: parameters).responseJSON { response in 
    switch response.result {
    case .success(let json):
        print("POST 成功: \(json)")
    case .failure(let error):
        print("POST 失败: \(error)")
    }
}

(4) 使用 Encodable 发送 JSON

如果你的参数是 Encodable 对象(如 struct),可以这样:

swift 复制代码
struct User: Encodable {
    let name: String 
    let age: Int 
}
 
let user = User(name: "John", age: 25)
 
AF.request("https://httpbin.org/post", method: .post, parameters: user, encoder: JSONParameterEncoder.default).responseJSON { response in 
    switch response.result {
    case .success(let json):
        print("POST 成功: \(json)")
    case .failure(let error):
        print("POST 失败: \(error)")
    }
}

  1. 高级用法
    (1) 文件上传
swift 复制代码
let fileURL = Bundle.main.url(forResource: "test", withExtension: "jpg")!
 
AF.upload(fileURL, to: "https://httpbin.org/post").uploadProgress { progress in 
    print("上传进度: \(progress.fractionCompleted)")
}.responseJSON { response in 
    switch response.result {
    case .success(let json):
        print("上传成功: \(json)")
    case .failure(let error):
        print("上传失败: \(error)")
    }
}

(2) 文件下载

swift 复制代码
let destination: DownloadRequest.Destination = { _, _ in 
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("image.jpg")
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
 
AF.download("https://httpbin.org/image/jpeg", to: destination).response { response in 
    if let filePath = response.fileURL?.path {
        print("文件已保存到: \(filePath)")
    }
}

(3) 请求头 & 认证

swift 复制代码
let headers: HTTPHeaders = [
    "Authorization": "Bearer YOUR_TOKEN",
    "Accept": "application/json"
]
 
AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in 
    switch response.result {
    case .success(let json):
        print("带 Header 的请求: \(json)")
    case .failure(let error):
        print("请求失败: \(error)")
    }
}

(4) 拦截请求(RequestInterceptor)

可以统一处理认证、重试等逻辑:

swift 复制代码
struct AuthInterceptor: RequestInterceptor {
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request = urlRequest 
        request.setValue("Bearer YOUR_TOKEN", forHTTPHeaderField: "Authorization")
        completion(.success(request))
    }
}
 
let session = Session(interceptor: AuthInterceptor())
session.request("https://httpbin.org/headers").responseJSON { response in 
    // 处理响应 
}

  1. 错误处理
    Alamofire 提供了详细的错误信息:
swift 复制代码
AF.request("https://httpbin.org/status/404").validate().response { response in 
    if let error = response.error {
        if let statusCode = response.response?.statusCode {
            print("HTTP 状态码错误: \(statusCode)")
        }
        print("详细错误: \(error.localizedDescription)")
    }
}

  1. 结合 Combine(iOS 13+)
    Alamofire 支持 Combine,可以轻松集成到响应式编程中:
swift 复制代码
import Combine 
 
AF.request("https://httpbin.org/get")
    .publishDecodable(type: ResponseModel.self)
    .sink { completion in 
        if case .failure(let error) = completion {
            print("请求失败: \(error)")
        }
    } receiveValue: { response in 
        print("收到数据: \(response.value)")
    }
    .store(in: &cancellables)

总结

功能 示例
GET 请求 AF.request("https://example.com/get")
POST 请求 AF.request("https://example.com/post", method: .post, parameters: params)
文件上传 AF.upload(fileURL, to: "https://example.com/upload")
文件下载 AF.download("https://example.com/file", to: destination)
请求头 headers: HTTPHeaders = ["Authorization": "Bearer token"]
错误处理 response.validate().responseJSON { ... }

Alamofire 让网络请求变得更简单,适用于大多数 HTTP 请求场景。建议结合 Codable 解析 JSON 数据,提升代码可维护性。

相关推荐
Lancker8 小时前
没有 Mac 也能上架 iOS:GitHub Actions 全自动构建 + 签名 + TestFlight 送审实录
macos·ios·github
茶底世界之下8 小时前
晚霞要多暖?用 Awaking 只改色温做一次取舍
ios
酒神dnspup10 小时前
多地区网站可用性监控怎么做?DNSPup 从基线到告警的完整实战
运维·ios·云计算·iphone·dns·网络监控
福兮说1 天前
浏览器里把 iPhone 的 HEIC 转成 JPG:Chrome 解不开、转完大了七成、拍摄时间全丢,六个坑实测
前端·javascript·图像处理·chrome·ios·iphone·heic
茶底世界之下1 天前
时间线效果层,为什么不能只复用一个处理器?
ios·swift
ZZH_AI项目交付1 天前
实时字幕负责快,本地录音负责不丢:一个 iOS 录音功能为什么需要两条链路
ios·ai编程
Cc.Y1 天前
Swift深度链接的极简之道
ios·cocoa·swift
AI砖家1 天前
iPhone Duo 上架新规:旧 App 怎么兼容,还能不能继续更新?
ios·cocoa·iphone·ios上架·ios上架新规
黑科技iOS上架1 天前
小蟹iOS混淆:Objective-C项目实战
ios·审核·ios混淆·执行程序差异化
茶底世界之下1 天前
照片边缘太抢眼?用 Awaking 做一次 1:1 裁切
ios