首页 > 解决方案 > 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.})))

但是,它成功了,图像和数据被发送到服务器/数据库。

标签: swiftalamofire

解决方案


选项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>

推荐阅读