Alamofire常见GET/POST等请求方式的使用,响应直接为json

news2024/9/22 13:33:51

Alamofire

官方仓库地址:https://github.com/Alamofire/Alamofire

xcode中安装和使用:swift网络库Alamofire的安装及简单使用,苹果开发必备-CSDN博客

Alamofire是一个基于Swift语言开发的优秀网络请求库。它封装了底层的网络请求工作,提供了更简单、更易用的接口,大大简化了网络请求代码的编写。Alamofire提供了一套优雅且易于理解的API,使得开发者可以轻松发起各种类型的HTTP请求。它支持GET、POST、PUT、DELETE等常用的请求方法,并且提供了丰富的参数设置选项。Alamofire提供了强大的响应处理功能,支持数据解析、文件上传和下载等常见需求。它基于Swift的特性和语法,代码简洁、可读性强,易于维护和扩展。

GET请求

get请求是最常见的一种请求方式了,默认AF.request发送的就是get请求,代码示例:

    // get请求
    func getData() {
        print("发送get请求")
        // 准备一个url
        let url = "https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_hot_1.json"
        // 使用Alamofile发起请求,默认是GET
        AF.request(url).responseData(completionHandler: { res in
            // response.result为枚举类型,所以需要使用switch
            switch res.result {
                case let .success(Data):
                    // 将Data类型的数据转为Json字符串
                    let jsonString = try? JSONSerialization.jsonObject(with: Data)
                    // 打印json字符串
                    print("success\(String(describing: jsonString))")
                case let .failure(error):
                    print("error\(error)")
            }
            // print("响应数据:\(res.result)")
        })
    }

POST请求

发送post请求要带上method参数,设置为.post,携带的参数放parameters里面,如果想让返回的数据直接是json格式的,可以使用.responseJSON,代码示例:

    // post请求
    func postData() {
        print("发送post请求")
        let urlStr = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
        // payload 数据
        let payload = ["name": "hibo", "password": "123456"]
        AF.request(urlStr, method: .post, parameters: payload).responseJSON { response in
            switch response.result {
                case let .success(json):
                    print("post response: \(json)")
                case let .failure(error):
                    print("error:\(error)")
            }
        }
    }

其他的put/delete等请求和post一样,只是参数不一样而已:

 

post等请求参数解析: <Parameter:Encodable>

只要参数遵循Encodable协议,那么最终ParameterEncoder都会把Parameter encode成需要的数据类型

举个例子

struct Login: Encodable {
    let email:String
    let password:String
}

let login = Login(email: "aaa", password: "bbb")
AF.request("https://httpbin.org/post",
               method: .post,
               parameters: login,
               encoder: JSONParameterEncoder.default)
    .response { response in
        debugPrint(response)
}

Headers请求头设置 

设置请求头有三种方式

1.无参构造 

/// 1. 无参构造
public init() {}

/// 通过以下方式添加值
func add(name: String, value: String)
func add(_ header: HTTPHeader)

2.通过 HTTPHeader 数组构造

/// 2. 通过 HTTPHeader 数组构造
public init(_ headers: [HTTPHeader])

let headers: HTTPHeaders = [
    HTTPHeader(name: "Authorization", value: "Basic VXNlcm5hbWU6UGFzc3dvcmQ="),
    HTTPHeader(name: "Accept", value: "application/json")
]

AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

3.通过key/value 构造 

/// 3. 通过key/value 构造
public init(_ dictionary: [String: String])

let headers: HTTPHeaders = [
    "Authorization": "Basic VXNlcm5hbWU6UGFzc3dvcmQ=",
    "Accept": "application/json"
]

AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

响应处理

1.Alamofire 提供了4种 Response序列化工具,DataResponseSerializer 解析为Data

// Response Handler - Unserialized Response
func response(queue: DispatchQueue = .main, 
              completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self

// Response Data Handler - Serialized into Data
func responseData(queue: DispatchQueue = .main,
                  dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
                  emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
                  emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
                  completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self

//示例
AF.request("https://httpbin.org/get").responseData { response in
    debugPrint("Response: \(response)")
}

2.StringResponseSerializer 解析为String

// Response String Handler - Serialized into String
func responseString(queue: DispatchQueue = .main,
                    dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
                    encoding: String.Encoding? = nil,
                    emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
                    emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
                    completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self



//示例
AF.request("https://httpbin.org/get").responseString { response in
    debugPrint("Response: \(response)")
}

3.JSONResponseSerializer 解析为JSON

// Response JSON Handler - Serialized into Any Using JSONSerialization
func responseJSON(queue: DispatchQueue = .main,
                  dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
                  emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
                  emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
                  options: JSONSerialization.ReadingOptions = .allowFragments,
                  completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self
//示例
AF.request("https://httpbin.org/get").responseJSON { response in
    debugPrint("Response: \(response)")
}

下载文件

1.下载Data

AF.download("https://httpbin.org/image/png").responseData { response in
    if let data = response.value {
        let image = UIImage(data: data)
    }
}

2.下载到指定目录

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
AF.download("https://httpbin.org/image/png", to: destination).response { response in
    debugPrint(response)

    if response.error == nil, let imagePath = response.fileURL?.path {
        let image = UIImage(contentsOfFile: imagePath)
    }
}

3.下载进度

AF.download("https://httpbin.org/image/png")
    .downloadProgress { progress in
        print("Download Progress: \(progress.fractionCompleted)")
    }
    .responseData { response in
        if let data = response.value {
            let image = UIImage(data: data)
        }
    }

4.恢复下载

var resumeData: Data!

let download = AF.download("https://httpbin.org/image/png").responseData { response in
    if let data = response.value {
        let image = UIImage(data: data)
    }
}

// download.cancel(producingResumeData: true) // Makes resumeData available in response only.
download.cancel { data in
    resumeData = data
}

AF.download(resumingWith: resumeData).responseData { response in
    if let data = response.value {
        let image = UIImage(data: data)
    }
}

上传文件

1.上传 Data

let data = Data("data".utf8)

AF.upload(data, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
    debugPrint(response)
}

2.上传文件

let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")

AF.upload(fileURL, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
    debugPrint(response)
}

3.上传 Multipart Data

AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(Data("one".utf8), withName: "one")
    multipartFormData.append(Data("two".utf8), withName: "two")
}, to: "https://httpbin.org/post")
    .responseDecodable(of: HTTPBinResponse.self) { response in
        debugPrint(response)
    }

4.上传进度

let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")

AF.upload(fileURL, to: "https://httpbin.org/post")
    .uploadProgress { progress in
        print("Upload Progress: \(progress.fractionCompleted)")
    }
    .responseDecodable(of: HTTPBinResponse.self) { response in
        debugPrint(response)
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1702177.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

每日5题Day11 - LeetCode 51 - 55

每一步向前都是向自己的梦想更近一步&#xff0c;坚持不懈&#xff0c;勇往直前&#xff01; 第一题&#xff1a;51. N 皇后 - 力扣&#xff08;LeetCode&#xff09; class Solution {public List<List<String>> solveNQueens(int n) {List<List<String>…

WGCLOUD使用下发指令重启安卓设备

wgcloud的下发命令很好使&#xff0c;可以下发很多命令&#xff0c;最好的是可以选择很多主机同时下发命令 这里我想重启下我的安卓设备&#xff0c;只需要下发一个命令&#xff1a; bash reboot 就好啦 如下图

PTA 判断两个矩阵相等

Peter得到两个n行m列矩阵&#xff0c;她想知道两个矩阵是否相等&#xff0c;请你用“Yes”&#xff0c;“No”回答她&#xff08;两个矩阵相等指的是两个矩阵对应元素都相等&#xff09;。 输入格式: 第一行输入整数n和m&#xff0c;表示两个矩阵的行与列&#xff0c;用空格隔…

韬光养晦的超绝项目

发展方向 竞技闯关类 可以加入对战系统积累积分&#xff0c;竞技类的接受程度更高&#xff0c;小孩&#xff08;我和我身边大多数人小时候&#xff09;都喜欢玩王者吃鸡这种经济类游戏&#xff0c;开放世界探索&#xff08;本项目、一梦江湖、逆水寒&#xff09;的受众群体年…

最新dofm飞行棋高阶版,分享情侣版飞行棋高级版和终极版

阿星今天要给大家带来一款甜蜜蜜的小游戏——情侣飞行棋。这不是普通的飞行棋&#xff0c;而是专为情侣设计的&#xff0c;让你们的感情在游戏中升温&#xff0c;擦出更多爱的火花。 准备好了吗&#xff1f;跟着阿星一起&#xff0c;咱们来看看这款软件的魅力所在&#xff01;…

Kuberbetes图形化界面之Kuboard

1.1 Kuboard Kuboard 是一个 Kubernetes 可视化管理平台&#xff0c;它提供了一种简单易用的方式来管理和监控 Kubernetes 集群。通过 Kuboard&#xff0c;用户可以轻松地部署、扩展和管理容器化应用程序&#xff0c;同时它还提供了一些高级功能&#xff0c;比如集群监控、日志…

YOLOv10环境搭建、模型预测和ONNX推理

目录 1、开源代码、模型下载 2、环境配置 3、模型预测 4、onnxruntime测试 1、开源代码、模型下载 代码下载链接&#xff1a;https://github.com/THU-MIG/yolov10 模型下载&#xff1a; YOLOv10-N&#xff1a;https://github.com/THU-MIG/yolov10/releases/download/v1.1/…

Linux系统安装AMH服务器管理面板并实现远程访问管理维护

目录 前言 1. Linux 安装AMH 面板 2. 本地访问AMH 面板 3. Linux安装Cpolar 4. 配置AMH面板公网地址 5. 远程访问AMH面板 6. 固定AMH面板公网地址 1. 部署Docker Registry 2. 本地测试推送镜像 3. Linux 安装cpolar 4. 配置Docker Registry公网访问地址 5. 公网远程…

【NumPy】关于numpy.divide()函数,看这一篇文章就够了

&#x1f9d1; 博主简介&#xff1a;阿里巴巴嵌入式技术专家&#xff0c;深耕嵌入式人工智能领域&#xff0c;具备多年的嵌入式硬件产品研发管理经验。 &#x1f4d2; 博客介绍&#xff1a;分享嵌入式开发领域的相关知识、经验、思考和感悟&#xff0c;欢迎关注。提供嵌入式方向…

Kubernetes可视化界面之DashBoard

1.1 DashBoard Kubernetes Dashboard 是 Kubernetes 集群的一个开箱即用的 Web UI&#xff0c;提供了一种图形化的方式来管理和监视 Kubernetes 集群中的资源。它允许用户直接在浏览器中执行许多常见的 Kubernetes 管理任务&#xff0c;如部署应用、监控应用状态、执行故障排查…

AI整体架构设计6:vLLM

训练大型语言模型以及微调的教程比比皆是&#xff0c;但关于在生产环境中部署它们并监控其活动的资料相对稀缺。上个章节提到了未来云原生的AI是趋势&#xff0c;然而涉及到云原生会比较偏技术。而在此之前为了解决大模型部署量产的问题&#xff0c;社区也一直在探索&#xff0…

数据链路层 + NAT技术

数据链路层&#xff1a;负责设备之间的数据帧的传送和识别。 一、以太网 以太网的帧格式 如何分离报头和有效数据&#xff1f; 报头是固定长度的 如何将数据交给上层协议&#xff1f; 通过类型&#xff0c;如果是0800&#xff0c;则交给IP协议&#xff0c;如果是0806&#xf…

华火硬核专利库丨登创新科技之巅,探创新未至之境

十年的艰苦卓越&#xff0c;“灶”就了华火科技之巅&#xff1b;电生明火的应用&#xff0c;不仅是一次颠覆性的创新&#xff0c;更是对未来厨房的无尽遐想与探索。在当今日新月异的科技时代&#xff0c;创新已成为推动社会进步的重要动力。 华火烹饪科技&#xff0c;以其深厚的…

【空号检测】手机号码状态识别背后的神秘力量:信令检测技术揭秘!

在当今数字化时代&#xff0c;了解一个手机号码的真实状态——是空号、停机还是活跃使用&#xff0c;对于企业运营、客户服务乃至个人通讯管理都至关重要。这一切高效而精准的查询能力&#xff0c;很大程度上归功于一项核心技术——信令检测技术。 免费测试地址&#xff1a;号…

【Django】中间件实现钩子函数预处理和后处理,局部装饰视图函数

在app文件夹里新建middleware.py继承MiddlewareMixin&#xff0c; 编写中间件类&#xff0c;重写process_request、process_response钩子函数 from django.http import HttpRequest, HttpResponse from django.utils.decorators import decorator_from_middleware from django…

使用MyBatis进行批量新增更新操作 ON CONFLICT

1.数据库增加uniques 2.mybatis <?xml version"1.0" encoding"UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace"co…

蓝桥杯2023(十四届)省赛——接龙数列(DP)

接龙数列&#xff08;DP&#xff09; 1.接龙数列 - 蓝桥云课 (lanqiao.cn) 琢磨半天&#xff0c;本来是开一个三维的&#xff0c;dp[i][j][k] 表示 前i个&#xff0c;以j为首项&#xff0c;k为尾项的最大子集个数&#xff0c;但是实际上用二维即可。想求的是删除个数&#xf…

【SpringCloud】负载均衡

目录 负载均衡什么是负载均衡生活场景为什么需要负载均衡负载均衡手段负载均衡总的来说有两种实现手段负载均衡具体可以通过多种手段来实现 SpringCloud中的负载均衡组件Ribbon VS Nginx负载均衡区别集中式LB进程内LB RibbonRibbon的工作原理Ribbon在工作时分成两步 使用1.提供…

二叉树经典OJ题分析

目录 一、单值二叉树 1.1 题目 1.2 思路 1.3 C语言题解 二、相同的树 2.1 题目 2.2 思路 2.3 C语言题解 三、对称二叉树 3.1 题目 3.2 思路 3.3 C语言题解 四、另一颗树的子树 4.1 题目 4.2 思路 4.3 C语言题解 五、翻转二叉树 5.1 题目 5.2 思路 5.3 C语言…

Elasticsearch之文本分析

文本分析基本概念 官网&#xff1a;Text analysis | Elasticsearch Guide [7.17] | Elastic 官网称为文本分析&#xff0c;这是对文本进行一直分析处理的方式&#xff0c;基本处理逻辑是为按照预先制定的分词规则&#xff0c;把原本的文档进行分割成多个小颗粒度的词项&#x…