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 数据,提升代码可维护性。

相关推荐
00后程序员张14 小时前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
咕噜签名分发冰淇淋16 小时前
内测分发是什么?
ios
2501_9160074720 小时前
Transporter App 使用全流程详解:iOS 应用 ipa 上传工具、 uni-app 应用发布指南
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc21 小时前
【OC】单例模式
开发语言·ios·单例模式·objective-c
Digitally1 天前
比较 iPhone:全面比较 iPhone 17 系列
android·ios·iphone
2501_915909061 天前
HTTPS 错误解析,常见 HTTPS 抓包失败、443 端口错误与 iOS 抓包调试全攻略
android·网络协议·ios·小程序·https·uni-app·iphone
他们都不看好你,偏偏你最不争气2 天前
【iOS】UIViewController
开发语言·macos·ios·objective-c·cocoa
前端小超超2 天前
如何配置capacitor 打包的ios app固定竖屏展示?
前端·ios·web app
CocoaKier2 天前
AI让35岁程序员再次伟大
ios·微信小程序·aigc
库奇噜啦呼2 天前
【iOS】单例模式
ios·单例模式