【问题标题】:How to upload file multipart alamofire swift5?如何上传文件多部分alamofire swift5?
【发布时间】:2023-03-11 13:36:02
【问题描述】:

我正在尝试通过多部分将文件发送到服务器。它可以是图像或普通文件。我在使用 URLConvertible 时遇到了一些困难。正如我所见,Alamofire 有这样的方法,这可能对我有用:

AF.upload(multipartFormData: <(MultipartFormData) -> Void>, to: <URLConvertible>)

但是在这里,我无法附加将处理 401 错误的拦截器。为此,我创建了这样的变量:

let manager =  Session(configuration: URLSessionConfiguration.default, interceptor: CallInterceptor.init(method:HTTPMethod.post))

并且还创建了请求:

var request = URLRequest(url: Pathes.init(endpoint: "photo").resourseUrl)
request.httpMethod = HTTPMethod.post.rawValue

最终用法附在照片选择器上:

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let fileUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL else { return }
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
 
         .....


          manager.upload(multipartFormData: { (formData) in
                formData.append(fileUrl, withName: "photo", fileName: fileName, mimeType: mediaType)
            }, to: request as! URLConvertible).validate(statusCode: 200..<300)
            .responseJSON(completionHandler: { (response) in
                print(response.debugDescription)
            })


}

}

但结果我的应用程序因此类错误而崩溃:

Could not cast value of type 'Foundation.URLRequest' (0x7fff85d1dbd8) to 'Alamofire.URLConvertible' (0x7ffb558a5320)

我想我有两种方法:使用另一种 AF 方法或创建另一种请求类型。但我无法想象哪种方法一方面可以帮助我,另一方面我不知道如何创建 URLConvertible。我认为我可以这样做:

 let urlRequest: Alamofire.URLRequestConvertible = request

但应用再次崩溃。我做错了什么?

【问题讨论】:

    标签: swift alamofire nsurlrequest


    【解决方案1】:

    如果您想使用URLRequest 而不是URL,您需要使用适当的upload 重载:upload(multipartFormData:with:)

    manager.upload(multipartFormData: { (formData) in
                    formData.append(fileUrl, withName: "photo", fileName: fileName, mimeType: mediaType)
        }, with: request)
    

    【讨论】:

    • 但在这里我还必须使用 URLRequestConvertible,因为我看到了,而且我还必须创建一些我不知道该怎么做的多部分数据。你能补充一些信息吗?
    • 不,URLRequest 已经符合 URLRequestConvertible,所以您无需再做任何事情。您可以使用现有代码并将to 交换为with,删除演员表,然后完成。
    • 你检查你的代码了吗?我尝试发送文件并收到此类错误unable to determine interface type without an established connectionunable to determine fallback status without a connection
    • 我看到它与新的 ios 13 连接策略有关,类似于 developer.apple.com/forums/thread/123346 你知道如何修复它以供 alamofire 使用吗?
    • 这似乎不是 Alamofire 问题,而是标准系统 TLS 问题。我建议你调查一下。
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2019-08-08
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多