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

2024-05-28 08:12

本文主要是介绍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请求")// 准备一个urllet url = "https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_hot_1.json"// 使用Alamofile发起请求,默认是GETAF.request(url).responseData(completionHandler: { res in// response.result为枚举类型,所以需要使用switchswitch 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 inswitch 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:Stringlet password:String
}let login = Login(email: "aaa", password: "bbb")
AF.request("https://httpbin.org/post",method: .post,parameters: login,encoder: JSONParameterEncoder.default).response { response indebugPrint(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 indebugPrint(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 indebugPrint(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 indebugPrint("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 indebugPrint("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 indebugPrint("Response: \(response)")
}

下载文件

1.下载Data

AF.download("https://httpbin.org/image/png").responseData { response inif 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 indebugPrint(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 inprint("Download Progress: \(progress.fractionCompleted)")}.responseData { response inif let data = response.value {let image = UIImage(data: data)}}

4.恢复下载

var resumeData: Data!let download = AF.download("https://httpbin.org/image/png").responseData { response inif let data = response.value {let image = UIImage(data: data)}
}// download.cancel(producingResumeData: true) // Makes resumeData available in response only.
download.cancel { data inresumeData = data
}AF.download(resumingWith: resumeData).responseData { response inif 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 indebugPrint(response)
}

2.上传文件

let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")AF.upload(fileURL, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response indebugPrint(response)
}

3.上传 Multipart Data

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

4.上传进度

let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")AF.upload(fileURL, to: "https://httpbin.org/post").uploadProgress { progress inprint("Upload Progress: \(progress.fractionCompleted)")}.responseDecodable(of: HTTPBinResponse.self) { response indebugPrint(response)}

这篇关于Alamofire常见GET/POST等请求方式的使用,响应直接为json的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010012

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

内核启动时减少log的方式

内核引导选项 内核引导选项大体上可以分为两类:一类与设备无关、另一类与设备有关。与设备有关的引导选项多如牛毛,需要你自己阅读内核中的相应驱动程序源码以获取其能够接受的引导选项。比如,如果你想知道可以向 AHA1542 SCSI 驱动程序传递哪些引导选项,那么就查看 drivers/scsi/aha1542.c 文件,一般在前面 100 行注释里就可以找到所接受的引导选项说明。大多数选项是通过"_

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti