how to save video file into document directory

后端 未结 9 784
庸人自扰
庸人自扰 2020-12-12 21:45

I am capturing video using following code:

UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType =  UIImagePickerControllerSo         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 22:17

    Just Call this function, and it will do every thing for you :)

        private func saveVideo(url:URL) {
        DispatchQueue.global(qos: .userInitiated).async {
            guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
            if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(url.lastPathComponent).path) {
                URLSession.shared.downloadTask(with: url) { (location, response, error) -> Void in
                    guard let location = location else { return }
                    let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? url.lastPathComponent)
    
                    do {
                        try FileManager.default.moveItem(at: location, to: destinationURL)
                        PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in
                            if authorizationStatus == .authorized {
                                PHPhotoLibrary.shared().performChanges({
                                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
                                        DispatchQueue.main.async {
                                            if completed {
                                                self.view.makeToast(NSLocalizedString("Video Saved!", comment: "Video Saved!"), duration: 3.0, position: .center)
                                            } else {
                                                print(error!)
                                            }
                                        }
                                }
                            }
                        })
                    } catch { print(error) }
    
                    }.resume()
            } else {
                print("File already exists at destination url")
            }
        }
    }
    

提交回复
热议问题