You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Alamofire.request可用但AF.request无提示、.GET方法不显示如何解码数据

问题原因说明

  • 你当前集成的是Alamofire 4.x版本:Alamofire 5.0+才把全局调用入口从Alamofire.request改成了AF.request,同时HTTP方法的调用风格也做了调整,4.x版本的HTTP方法是作为request方法的参数传入,不支持链式调用.GET方法,所以你会遇到这两个现象。如果要使用AF.request的调用方式,你可以把Alamofire版本升级到5.0及以上即可。

接口返回数据解码方案

推荐配合系统Codable协议实现高效解码,步骤如下:

第一步:根据接口返回结构定义数据模型,遵守Codable协议

假设你的接口返回结构如下:

{
  "code": 200,
  "message": "请求成功",
  "data": {
    "userName": "张三",
    "age": 20
  }
}

对应定义的Swift模型:

// 外层通用响应结构
struct ApiResponse<T: Codable>: Codable {
    let code: Int
    let message: String
    let data: T?
}

// 内层业务数据结构
struct UserInfo: Codable {
    let userName: String
    let age: Int
}

第二步:调用Alamofire接口完成自动解码

方案1:使用Alamofire自带的responseDecodable方法(推荐)

直接修改你的现有代码即可:

import UIKit
import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 4.x版本HTTP方法通过method参数传入,默认是GET可以省略
        Alamofire.request("https://api.npoint.io/ad9bc4bdbf536cff1d3e", method: .get)
            .responseDecodable(of: ApiResponse<UserInfo>.self) { response in
                switch response.result {
                case .success(let res):
                    // 解码成功,直接使用结构化数据
                    if let userInfo = res.data {
                        print("用户名:\(userInfo.userName),年龄:\(userInfo.age)")
                    }
                case .failure(let error):
                    print("请求或解码失败:\(error)")
                }
            }
    }
}

方案2:手动从返回数据中解析

如果你需要手动处理返回的原始数据,也可以用JSONDecoder自行解析:

Alamofire.request("https://api.npoint.io/ad9bc4bdbf536cff1d3e").response { response in
    guard let data = response.data else {
        print("无返回数据")
        return
    }
    do {
        let result = try JSONDecoder().decode(ApiResponse<UserInfo>.self, from: data)
        print(result)
    } catch {
        print("解码失败:\(error)")
    }
}

内容的提问来源于stack exchange,提问作者Haroon Maqsood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:42:04