사진 라이브러리 Swift에 비디오 저장 (Save video in Photo Library Swift)


문제 설명

사진 라이브러리 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
        }
    }
}

참조 솔루션

방법 1:

  • 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)
    

    }
    </code></pre></li>

  • now save this video in photo gellary

    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
    }
    

    }
    </code></pre></li>
    </ul>

    after it if you don't need then delete the image from document directory , I hope it will work for you ...:)

    (by MBPShivam Parmar)

    참조 문서

    1. Save video in Photo Library Swift (CC BY‑SA 2.5/3.0/4.0)

#uiimagepickercontroller #XCode #swift #save






관련 질문

UIImagePickerController 닫기 (Dismiss UIImagePickerController)

UIImagePickerController에서 이미지 크기 조정이 작동하지 않음 (Resizing an image from UIImagePickerController not working)

사진 촬영 후 사진 사용 또는 재촬영을 선택할 수 없습니다. (After Taking Picture cannot select Use Photo or Retake)

런타임 오류를 제공하는 UIImagePicker (UIImagePicker giving runtime error)

Swift:UIImagePickerController에서 버튼의 텍스트를 변경하는 방법은 무엇입니까? (Swift: how to change the text of buttons in UIImagePickerController?)

iOS 9에서 UIImagePickerController가 이미지를 선택하지 않음 (UIImagePickerController not picking image in iOS 9)

UIImagePNGRepresentation() 내 UIImage 회전 (UIImagePNGRepresentation() rotate my UIImage)

UIImagePickerController에서 편집 사각형을 구성할 수 있습니까? (Can we config edit rectangle in UIImagePickerController)

imagePickerController를 닫는 방법? (how to close imagePickerController?)

카메라 사용 설명/사진 라이브러리 사용 설명을 추가해도 경고가 표시되지 않음 (Not showing alert even when I add Camera Usage Description / Photo Library Usage Description)

UIImagePIcker를 통해 "JPG", "PNG" 및 "JPEG" 이미지만 선택할 수 있는 방법이 있습니까? (Is there any way by which I can select only "JPG", "PNG" and "JPEG" images through UIImagePIcker)

사진 라이브러리 Swift에 비디오 저장 (Save video in Photo Library Swift)







코멘트