I'm trying to send file to the server via multipart. It can be image or an ordinary file. I have some difficulties with URLConvertible usage. As I see Alamofire has such method, which maybe will be useful for me:
AF.upload(multipartFormData: <(MultipartFormData) -> Void>, to: <URLConvertible>)
but here as you can I can't attach interceptor which will handle 401 error. For this purpose I have created such variable:
let manager = Session(configuration: URLSessionConfiguration.default, interceptor: CallInterceptor.init(method:HTTPMethod.post))
and also created the request:
var request = URLRequest(url: Pathes.init(endpoint: "photo").resourseUrl)
request.httpMethod = HTTPMethod.post.rawValue
and final usage is attached to photo selector:
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)
})
}
}
but as a result my app crashes with such error:
Could not cast value of type 'Foundation.URLRequest' (0x7fff85d1dbd8) to 'Alamofire.URLConvertible' (0x7ffb558a5320)
I think I have two ways: use another AF method or created another request type. But I can't imagine which method will help me one one side and on another side I don't know how to create URLConvertible. I thought that I can do it in such way:
let urlRequest: Alamofire.URLRequestConvertible = request
but the app crashed again. What I did wrong?
question from:
https://stackoverflow.com/questions/65878638/how-to-upload-file-multipart-alamofire-swift5 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…