在照片库中保存视频 Swift

Save video in Photo Library Swift

我想知道如何在我的照片库中保存视频。开始时,我尝试使用 UIImagePickerController 简单地选择一个视频,然后使用 UISaveVideoAtPathToSavedPhotosAlbum 将其再次保存在库中。没有多大意义,但我试图了解保存视频的工作原理。

以下代码不起作用,因为它不保存视频:

@IBAction func ChooseVideo(_ sender: Any) {
    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    imagePickerController.mediaTypes = ["public.movie"]
    self.present(imagePickerController, animated: true, completion: nil)
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL
    print(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoURL!.path))

    dismiss(animated: true, completion: {
        UISaveVideoAtPathToSavedPhotosAlbum(videoURL!.path, self,  #selector(self.video(_:didFinishSavingWithError:contextInfo:)), nil)
    })
}

希望你能帮助我,因为我找不到太多关于保存视频的信息。

此致, MB

解法:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
    // *** store the video URL returned by UIImagePickerController *** //
    let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! URL

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

    // *** Get documents directory path *** //
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]

    // *** Append video file name *** //

    print(paths)
    let dataPath = paths.appending("/videoFileName.mp4")

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

    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: dataPath))
    }) { saved, error in
        if saved {
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

            let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).firstObject
            // fetchResult is your latest video PHAsset
            // To fetch latest image  replace .video with .image
        }
    }
}
  • 使用以下函数将视频保存到文档目录

    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)
    }
    
  • 现在将此视频保存在照片库中

    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: Your document directory file)
    }) { saved, error in
        if saved {
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    
            let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).firstObject
            // fetchResult is your latest video PHAsset
            // To fetch latest image  replace .video with .image
        }
    }
    

之后,如果不需要,请从文档目录中删除图像 , 希望对你有用...:)