Casting UIImagePicker from video to Data in Swift

0

Hi, I have a small code where I get a video of the phone's reel to code, and now I need to transform that video to the Data class so that if I can send it for a Rest service, does anyone know any way?

        var imagePicker = UIImagePickerController()

    private func cargar() {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary

    imagePicker.mediaTypes = ["public.movie"]
    self.present(imagePicker, animated: true, completion: {

    })
    }
    
asked by Rogelio Sanchez 09.10.2018 в 07:40
source

2 answers

1

Pass it using the url of the video, first declare a variable of type Data:

          var dataVideo = Data()

          guard let url = URL(string: "videoUrl") else { return }
    do {
        let data = try Data(contentsOf: url)
           print(data)    // -> te imprime los datos del video, checa como obtener la url del picker
         dataVideo = data

    } catch let error as NSError {
        print(error.userInfo)
    }

That would be one way, another is using ReadingOptions:

       guard let url = URL(string: "videoUrl") else { return }

    do {
        let data = try Data(contentsOf: url, options: .mappedIfSafe)
            print(data)
            dataVideo = data
    } catch let error as NSError {
        print(error.userInfo)
    }
    
answered by 09.10.2018 в 23:41
1

I present the solution taking as an example the comment of @Yan Cervantes, add an extension where the url is obtained, and add a sign of! to the string in the url.

extension MiClaseController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

// Esta funcion se llama despues de haber seleccionado el video
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    videoURL = info[UIImagePickerControllerMediaURL] as? URL
    print("videoURL:\(String(describing: videoURL!))")


    var dataVideo = Data()

    guard let url = URL(string: "\(String(describing: videoURL!))") else { return }
    do {
        let data = try Data(contentsOf: url)
        print("Data : >>>  \(data)")    // -> te imprime los datos del video, checa como obtener la url del picker
        dataVideo = data
        self.dismiss(animated: true, completion: nil)
    } catch let error as NSError {
        print(error.userInfo)
    }

    /*guard let url = URL(string: "\(String(describing: videoURL))") else { return }
    do {
        let data = try Data(contentsOf: url, options: .mappedIfSafe)
        print(data)
        dataVideo = data
    } catch let error as NSError {
        print(error.userInfo)
    }*/


}

}

    
answered by 11.10.2018 в 04:05