Search code examples
iosswiftbase64urlsessionvideo-gallery

How to convert a local Video to base64 in swift?


I am currently working on a method to upload videos short videos (10-30sec) to my data base, and was questioning if is possible to convert a video from the local gallery to base64, at the moment I get the video using the imagePickerController as you can see in this code:

func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        //Here is save the video URL
        let url = info[.mediaURL] as? URL

        //Here goes the code to convert this video URL to base64...
    
        self.dismiss(animated: true)
}

I was also questioning if is viable to save the video to base64 and send it in the body of my post request or should I use other way to upload my video in the server? I am open to any recommendation, thanks


Solution

    1. Get data from file url
    2. Get Base64 string from data
    guard let url = info[.mediaURL] as? URL else { return }
    let data = Data(contentsOf: url)
    let base64String = data.base64EncodedString()
    

    For upload file to server use Multipart/form-data, because Base64 has 4/3 of original file size