Swift Video to Document Directory

How to save video data to document directory in swift?

In your Info.plist, add the following permissions:

Supports opening documents in place: YES

Application supports iTunes file sharing: YES

let videoFilename = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" + getFileName() //return your filename from the getFileName function
videoNSData.write(toFile: videoFilename, atomically: true)

Then, inside Files, you can get a folder named with your app name, where you can access your saved video file (with the specified filename).

How to play video file from documentdirectory using avplayer

swift 3/4 100%%%%%%% workable

Recorder open video camera

@IBAction func RecordAction(_ sender: Any) {

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
print("CameraAvailable")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.allowsEditing = false
imagePicker.showsCameraControls = true

self.present(imagePicker,animated: true, completion: nil)
}

else{
print("CameraNotAvailable")
}
}

save to document directory

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// recover video URL
let url = info[UIImagePickerControllerMediaURL] as? URL
// check if video is compatible with album
let compatible: Bool = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum((url?.path)!)
// save
if compatible {
UISaveVideoAtPathToSavedPhotosAlbum((url?.path)!, self, nil, nil)
print("saved!!!! \(String(describing: url?.path))")

}
videopath = url //save url to send next function play video
dismiss(animated: true, completion: nil)
}
// error
func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) {
}

play video from Document directory

 @IBAction func playvideo(_ sender: Any)
{
let player = AVPlayer(url: videopath!) // video path coming from above function

let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}

I am trying to access the video from the Document directory and i am getting error No such file or directory

Your way to create the URL is cumbersome and outdated. The error occurs because a slash in the URL is missing (the scheme is file://). Never create file system URLs with URL(string anyway. And don't use NSURL in Swift.

Please use the FileManager API. And you cannot read video data as String

do {
let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let toURL = documentsURL.appendingPathComponent("1VIDEO.MOV")
let videoData = try Data(contentsOf: toURL)
print(videoData)
catch {
print(error)
}

How to save image or video from UIPickerViewController to document directory?

  • Use following steps to save Image to documents directory

Step 1: Get a path to document directory

let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)

Step 2: Append FileName in path

let newPath = path.stringByAppendingPathComponent("image.jpg")

Step 3: Decide filetype of Image either JPEG or PNG and convert image to data(byte)

//let pngImageData = UIImagePNGRepresentation(image) // if you want to save as PNG
let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG

Step 4: write file to created path

let result = jpgImageData!.writeToFile(newPath, atomically: true)

Add above code into your didFinishPickingImage function.

  • Use following func to save video to documents directory

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) 
    {
    // *** store the video URL returned by UIImagePickerController *** //
    let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL

    // *** load video data from URL *** //
    let videoData = NSData(contentsOfURL: videoURL)

    // *** Get documents directory path *** //
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]

    // *** Append video file name *** //
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/videoFileName.mp4")

    // *** Write video file data to path *** //
    videoData?.writeToFile(dataPath, atomically: false)
    }


Related Topics



Leave a reply



Submit