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

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.mfbz.cn/a/652324.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

亚信安全:2024攻防演练利器之必修高危漏洞合集-百度网盘下载

亚信安全:2024攻防演练利器之必修高危漏洞合集-百度网盘下载. 90% ! 2023攻防演练期间 暴露的web漏洞占比90% 覆盖VPN、远程工具、办公软件 OA系统、聊天工具、安全产品等全路径 100% ! 隐藏在暗处的高危漏洞 一旦被利用&#xff0c;被攻陷率近100% 很多企业为此导致整…

解析新加坡裸机云多IP服务器网线路综合测评解析

在数字化高速发展的今天&#xff0c;新加坡裸机云多IP服务器以其卓越的性能和稳定性&#xff0c;成为了众多企业和个人用户的首选。源库主机评测将对新加坡裸机云多IP服务器的网线路进行综合测评&#xff0c;以帮助读者更深入地了解这一产品的优势。 一、性能表现 新加坡裸机云…

Facebook开户 | Facebook的CTR是什么?

在当今数字化的营销领域&#xff0c;了解和利用各种指标是成功的关键。其中一个关键指标是CTR&#xff0c;即点击率&#xff08;Click-Through Rate&#xff09;。 在Facebook广告中&#xff0c;CTR是一个至关重要的度量标准&#xff0c;它不仅可以衡量广告的效果&#xff0c;还…

OneForall工具的下载安装和使用(Windows和Linux)

目录 OneForall的介绍 OneForall的下载 OneForall的安装 安装要求 安装步骤&#xff08;git 版&#xff09; 安装&#xff08;kali&#xff09; OneForall的使用命令 在Windows 在Linux&#xff08;kali&#xff09; OneForall的结果说明 免责声明 本文所提供的文字和…

安全风险 - 切换后台时背景模糊处理

因为安全风险中提到当app处于后台卡片状态时&#xff0c;显示的卡片页面应该为模糊效果&#xff0c;否则容易泄露用户隐私&#xff0c;尤其当前页涉及个人信息、资产信息等&#xff0c;都会造成信息泄露&#xff01;基于这种场景&#xff0c;我研究了下这种业务下的模糊效果 找…

图像处理中的维度元素复制技巧

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、引言 二、维度元素复制的基本概念 三、如何实现维度元素复制 1. 方法介绍 2. 代码示…

方正国际金融事业部副总经理白冰受邀为第十三届中国PMO大会演讲嘉宾

全国PMO专业人士年度盛会 方正国际软件&#xff08;北京&#xff09;有限公司金融事业部副总经理白冰先生受邀为PMO评论主办的2024第十三届中国PMO大会演讲嘉宾&#xff0c;演讲议题为“浅析多项目管理的成功因素”。大会将于6月29-30日在北京举办&#xff0c;敬请关注&#xf…

flinkcdc 3.0 源码学习之客户端flink-cdc-cli模块

注意 : 本文章是基于flinkcdc 3.0 版本写的 我们在前面的文章已经提到过,flinkcdc3.0版本分为4层,API接口层,Connect链接层,Composer同步任务构建层,Runtime运行时层,这篇文章会对API接口层进行一个探索.探索一下flink-cdc-cli模块,看看是如何将一个yaml配置文件转换成一个任务…

RK平台ADB不识别问题排查

简介 ADB是Android系统的调试工具&#xff0c;一般用USB线连接开发板和PC&#xff0c;可以抓取开发板的调试日志&#xff0c;执行shell指令&#xff0c;传输文件等功能。为了调试方便&#xff0c;RK平台的Linux系统也默认支持ADB&#xff0c;其源码是从Android移植过来的。 本…

Android 中资源文件夹RES/RAW和ASSETS的使用区别

文章目录 1、res/raw 文件夹1.1、特点1.2、使用方法1.3、示例&#xff1a; 2. assets 文件夹2.1、特点2.2、使用方法2.3、示例&#xff1a; 3、使用场景3.1、res/raw 使用场景3.2、assets 使用场景 4、比较与选择5、文件夹选择的建议6、 示例代码总结6.1、res/raw 示例6.2、ass…

Diffusion Model 和 Stable Diffusion 详解

文章目录 Diffusion Model 基础生成模型DDPM概述向前扩散过程前向扩散的逐步过程前向扩散的整体过程 反向去噪过程网络结构训练和推理过程训练过程推理过程优化目标 详细数学推导数学基础向前扩散过程反向去噪过程 Stable Diffusion组成结构运行流程网络结构变分自编码器 (VAE)…

图形学初识--纹理采样和Wrap方式

文章目录 前言正文1、为什么需要纹理采样&#xff1f;2、什么是纹理采样&#xff1f;3、如何进行纹理采样&#xff1f;&#xff08;1&#xff09;假设绘制区域为矩形&#xff08;2&#xff09;假设绘制区域为三角形 4、什么是纹理的Wrap方式&#xff1f;5、有哪些纹理的Wrap方式…

Facebook之魅:数字社交的体验

在当今数字化时代&#xff0c;Facebook作为全球最大的社交平台之一&#xff0c;承载着数十亿用户的社交需求和期待。它不仅仅是一个简单的网站或应用程序&#xff0c;更是一个将世界各地的人们连接在一起的社交网络&#xff0c;为用户提供了丰富多彩、无与伦比的数字社交体验。…

云原生|为什么服务网格能够轻松重塑微服务?一文讲清楚!

目录 一、概述 二、 设计 三、服务网格 四、总结 一、概述 容器化技术与容器编排推动了微服务架构应用的演进&#xff0c;于是应用的扩展与微服务的数量日益增加&#xff0c;新的问题随之而来&#xff0c;监控服务的性能变得越来越困难&#xff0c;微服务与微服务之间相互通…

深度学习实战-yolox训练ExDark数据集所遇到的错误合集

跳转深度学习实战-yolox训练ExDark数据集(附全过程代码,超详细教程,无坑!) 一、 训练时出现ap为零 情况1.数据集没导进去 修改exps/example/yolox_voc/yolox_voc_s.py 当然由于image_sets只有一个元素因此修改yolox/data/datasets/voc.py 情况2.iou设置过高 修改yolo…

【全开源】在线题库微信小程序系统源码(ThinkPHP+FastAdmin+UniApp)

打造个性化学习平台 一、引言&#xff1a;在线学习的未来趋势 在数字化时代&#xff0c;线上学习已逐渐成为主流。随着移动互联网的普及&#xff0c;小程序以其轻便、快捷、无需安装的特点&#xff0c;成为用户日常学习的新选择。为了满足广大用户对于在线学习的需求&#xf…

深度学习模型在OCR中的可解释性问题与提升探讨

摘要&#xff1a; 随着深度学习技术在光学字符识别&#xff08;OCR&#xff09;领域的广泛应用&#xff0c;人们对深度学习模型的可解释性问题日益关注。本文将探讨OCR中深度学习模型的可解释性概念及其作用&#xff0c;以及如何提高可解释性&#xff0c;使其在实际应用中更可…

SqlServer 2016 2017 2019安装失败-无法找到数据库引擎启动句柄

SqlServer 2016 2017 2019安装失败-无法找到数据库引擎启动句柄 出现以上问题的原因是因为系统账户无法操作数据库引擎服务。需要调整权限。 按照以下步骤解决&#xff0c;成功完成安装&#xff0c;已亲测&#xff1a; 1、如果您已经安装了相同版本的SQL Server&#xff0c;…

Net快速开发-创建和使用项目模板(多个项目(解决方案)打包)

1.从nuget安装模版包 下载安装官方模版 从 NuGet 包源安装 Microsoft.TemplateEngine.Authoring.Templates 模板。 从终端运行 dotnet new install Microsoft.TemplateEngine.Authoring.Templates 命令。2.创建模版 Microsoft.TemplateEngine.Authoring.Templates 包含可用于…

TiDB-从0到1-分布式事务

TiDB从0到1系列 TiDB-从0到1-体系结构TiDB-从0到1-分布式存储TiDB-从0到1-分布式事务TiDB-从0到1-MVCC 一、事务定义 这属于老生常谈了&#xff0c;无论不管是传统事务还是分布式事务都离不开ACID A&#xff1a;原子性C&#xff1a;一致性I&#xff1a;隔离性D&#xff1a;…