Swift Alamofire 多部分表单数据 URLRequest 没有成员失败

Swift Alamofire multipart form data URLRequest has no member failure

我正在尝试在我的应用程序中连接图片上传。我正在使用 Alamofire 和 Alamofire 中的 multipartFormData 功能来实现这一点。

我编写了函数来上传这张图片以及其他属性。

func savePreferences(parameters: [String:Any], image: UIImage, completion: @escaping (Response?, Error?) -> Void) {
    let url = "http://localhost:3000/users/3b4e124d-3b3c-4c71-8e05-013e461c2892"
    let imgData = image.jpegData(compressionQuality: 0.5)!

    AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "profile_imgname",fileName: "ProfilePic_\(UserDefaults.standard.string(forKey: "user_id") ?? "").jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, to: url, method: .patch) { (result) in
        switch result {
        case .success(let upload):
            upload.responseJSON { response in
                if let err = response.error {
                    failure(err)
                    return
                }
                completion(response.result.value)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
        }
    }
}

在最后的 switch 语句中,在 case .successcase .failure 中,我收到以下错误:

Type 'URLRequest' has no member 'failure'

Type 'URLRequest' has no member 'success'

我已经使用现有的 Stack Overflow 资源来理解这个 multipartFormData 是如何工作的,而且它们似乎在一定程度上遵循了这种格式。

请看下面:

为什么我会收到 URLRequest has no member failure 的错误,我该如何更正?

Alamofire 5.0 迁移文档是这样说的:

MultipartFormData’s API has changed and the top level upload methods to create and upload MultipartFormData have been updated to match other request APIs, so it’s not longer necessary to deal with the Result of the multipart encoding.

(https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md)

您使用的代码看起来来自早期版本。在 5.0 中,尾随闭包使用 URLRequest 作为其参数(解释您所看到的错误)。

使用指南 (https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) 将此作为上传多部分表单数据的示例:

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)
    }

HTTPBinResponse 是一个 Decodable 的示例,您可以用自己的替换)。

除了responseDecodable,貌似还可以用responseJSONresponseDataresponseString

请注意,所有这些都附加了一个 . 调用结束 ) 之后——而不是作为尾随闭包。