如何为Alamofire 5.2添加可接受的图片MIME类型
在Alamofire 5.2中添加自定义图片MIME类型例外规则
我刚帮你梳理了Alamofire 5.2的相关实现,旧版本的addAcceptableImageContentTypes方法在这个版本里已经被重构移除了,不过有两种简洁的方式可以实现你要的MIME类型例外规则:
方式一:全局配置(所有请求生效)
如果你希望所有通过Alamofire发起的请求都能接受image/jpg这个非标准类型,可以自定义一个Session实例,修改它的配置来添加这个类型:
// 获取默认的可接受内容类型集合 let defaultAcceptableTypes = URLSessionConfiguration.default.acceptableContentTypes ?? Set() // 添加我们需要的例外类型 let updatedTypes = defaultAcceptableTypes.union(["image/jpg"]) // 创建自定义配置并设置更新后的类型 let customConfig = URLSessionConfiguration.default customConfig.acceptableContentTypes = updatedTypes // 使用这个配置创建Session,之后所有通过该Session的请求都会生效 let customSession = Session(configuration: customConfig) // 示例:用自定义Session发起请求 customSession.request("你的图片接口URL") .responseData { response in // 处理图片数据 }
方式二:单个请求单独配置(仅当前请求生效)
如果只是特定的图片请求需要接受image/jpg,可以在请求链中通过validate方法直接指定允许的内容类型:
AF.request("你的图片接口URL") // 这里同时包含标准的image/jpeg和需要的例外image/jpg .validate(contentTypes: ["image/jpeg", "image/jpg"]) .responseData { response in // 处理图片数据 }
如果不想手动列出所有默认类型,也可以先获取默认集合再添加例外:
let defaultTypes = Session.default.sessionConfiguration.acceptableContentTypes ?? Set() let allowedTypes = defaultTypes.union(["image/jpg"]) AF.request("你的图片接口URL") .validate(contentTypes: allowedTypes) .responseData { ... }
这两种方式都能替代旧版本的addAcceptableImageContentTypes方法,帮你解决后端返回非标准MIME类型的验证问题~
内容的提问来源于stack exchange,提问作者Sean Dev
相关产品推荐
相关产品推荐

