I need to upload a video to server using alamofire. The user selects the video and I get URL in didFinishPickingMediaWithInfo successfully as follows:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
if let pickedVideo = info[UIImagePickerControllerMediaURL] as? URL {
print(pickedVideo)
}
}
And then I upload the video using the following code:
Alamofire.upload( multipartFormData: { multipartFormData in
multipartFormData.append(videoUrl, withName: "video", fileName: "video.mp4", mimeType: "video/mp4")
}, to: url, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let JSON = response.result.value as? NSDictionary {
completion(true)
} else {
completion(false)
print(response)
}
}
case .failure(let encodingError):
print(encodingError)
completion(false)
}
})
It enters in the failure block, and the following error displays:
multipartEncodingFailed(Alamofire.AFError.MultipartEncodingFailureReason.bodyPartFileNotReachableWithError(atURL: file:/private/var/mobile/Containers/Data/Application/C662AB0E-6A4F-40FB-9949-7F0A5AA2BA49/tmp/52C86F07-5DCC-413A-9F8C-71BBF33F793C.MOV -- file:///, error: Error Domain=NSCocoaErrorDomain Code=260 "The file “52C86F07-5DCC-413A-9F8C-71BBF33F793C.MOV” couldn’t be opened because there is no such file.
You are trying to upload video by URL, that is not possible, in multipartFormData
need data to upload not URL, so firstly convert it to Data
then upload it.
Function for show imagePickerController only for Video's:
func showImagePicker(){
let picker = UIImagePickerController()
picker.delegate = self
picker.mediaTypes = [kUTTypeMovie as String]
self.present(picker, animated: true, completion: nil)
}
UIImagePickerControllerDelegate
function, that work after select video:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let videoUrl = info[UIImagePickerControllerMediaURL] as? URL else {
return
}
do {
let data = try Data(contentsOf: videoUrl, options: .mappedIfSafe)
print(data)
// here you can see data bytes of selected video, this data object is upload to server by multipartFormData upload
} catch {
}
}