swift - Alamofire 上传功能打印 responseJSON
问题描述
这是我的alamofire函数......
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "imagePath" , fileName: "profile-image.png", mimeType: "image/png")
for (key, value) in params {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
print(multipartFormData.contentLength)
},
to: URLLink, method: .post, headers: headers)
.downloadProgress { progress in
print(progress)
}
.response { response in
print(response.result)
}
.responseJSON(completionHandler: {data in
print(data)
})
如何以 JSON 格式打印响应,以便根据提供的信息处理来自服务器的响应?
response.result 和 response.value 不做正常请求函数所做的事情。
.responseJSON()
不响应来自服务器的响应。打印出来的数据是:
failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.})))
但是,它成功了,图像和数据被发送到服务器/数据库。
解决方案
选项1
Alamofire 提供开箱即用的 JSON 序列化程序,它是responseJSON()
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
选项 2
response()
是更通用的方法。您可以将响应序列化为您自己的输出类型(JSON、字符串等)。
这是response()
方法的函数头。您可以通过指定responseSerializer
.
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data contained in the destination url.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DownloadResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
-> Self
您可以使用此静态方法DownloadRequest.jsonResponseSerializer()
获取方法中所需的 JSON 序列化器response()
。
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DownloadResponseSerializer<Any>
推荐阅读
- kubernetes - 如何将 70% 的流量路由到 ExternalName 服务并附加 url?
- javascript - Webpack 类不共享 this 从构造函数到类的方法
- java - 正则表达式中的Java减号和hypen差异
- flutter - 颤振布局问题
- spring-boot - 合并两个分布式异步任务结果并触发一个动作
- c# - EF Core 使用 Fluent API 按类型配置实体属性
- php - dompdf在完整的bodytag中放置相同的字体
- cocoapods - 我在安装 cocoapods 时遇到了这个错误
- r - 逻辑回归 - eval(family$initialize):y 值必须为 0 <= y <= 1
- python - 反向级联规则不会影响 mongoengine 对象的覆盖删除方法