iosswiftvideo-library

iOS Swift - Not able to use video from Library


I'm trying to obtain a video from the library in my swift app. I'm using the following code snippet :

 print("ChatDetailsController - imgaction - Vid from Lib pressed")
        self.selection = "videoLib";
        self.imgSelection = "vidFromLib"
        self.imagePicker.sourceType = .PhotoLibrary
        self.imagePicker.delegate = self
        self.imagePicker.mediaTypes = ["public.movie"]
        self.presentViewController(self.imagePicker!, animated: true, completion: nil)

Then in delegate method:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
    if(selection == "videoLib")
    {
    if let videoURL = info[UIImagePickerControllerReferenceURL] as? NSURL
        {


            print("imagePickerController - reached for video - from Lib - \(videoURL)")
            let videoData = NSData(contentsOfURL: videoURL)

         }   
   }

}

When running the app, it shows the library and I can select a video, then it says compressing video.. but then the app crashes.

The Crash happens when I try to access the videoData Variable becuase it wasn't able to get the actual data since the path is an asset path and not a video path.

The Log shows something similar to this:

fatal error: unexpectedly found nil while unwrapping an Optional value

The print function shows:

imagePickerController - reached for video - from Lib - assets-library://asset/asset.MOV?id=7D3BFA00-A7CB-470C-8899-F82FCC2CBC54&ext=MOV

Also, right after choosing/selecting the video, a message similar to this is displayed in the console/log:

[Generic] video path /var/mobile/Media/PhotoData/CPLAssets/group419/A2901DD1-FDEF-423B-B4A3-E808B9AC45E1.MOV for PLPreviewImageAndDurationForVideoAtPath does not exist

Of course the file name changes on every run.

I'm able to get a video and images from the camera, and getting images from the library, I'm only having trouble with using the the video from the library. I would expect to see the video URL similar to :

/var/mobile/Containers/Data/Application/BEDDC883-B20E-496D-8C9A-A40EC0A29214/Documents/63ea24932c101b76c72fcbae3993fc9b.mov for example; where the video file is in the application and not showing as an unusable asset URL. Any help would be appreciated.


Solution

  • The problem is that you're trying to fetch the wrong video. You're trying to use info[UIImagePickerControllerReferenceURL]. What you want is info[UIImagePickerControllerMediaURL].