YeahGarage
@YeahGarage
Developer

Сохранение одинаковых видео в swift?

Добрый день друзья
Есть метод, который использую для сохранение видео файлов в приложении. Но он не сохраняет одно и тоже видео, что крайне требуется. Проблема в данной строке
if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) {


Сам метод вот
guard let videoURL = URL(string: i) else { return }

                    guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

                    // check if the file already exist at the destination folder if you don't want to download it twice
                   if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) {

                       // set up your download task
                        URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in

                            // use guard to unwrap your optional url
                            guard let location = location else { return }

                            // create a deatination url with the server response suggested file name
                            let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? videoURL.lastPathComponent)

                            do {

                                try FileManager.default.moveItem(at: location, to: destinationURL)

                                PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in

                                    // check if user authorized access photos for your app
                                    if authorizationStatus == .authorized {
                                        PHPhotoLibrary.shared().performChanges({
                                            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
                                                if completed {
                                                    print("Video asset created")
                                                } else {
                                                    print(error)
                                                }
                                        }
                                    }
                                })

                            } catch { print(error) }

                            }.resume()

                    } else {
                    print("File already exists at destination url")
                    }


Если убрать данную проблемную строку, то сохранение не происходит. Выводится в дебаггере ошибка
), NSDestinationFilePath=/var/mobile/Containers/Data/Application/C00DF827-E2C7-479D-8569-26BC84724F67/Documents/20955097_824456947720366_7510952727510253568_n.mp4, NSFilePath=/private/var/mobile/Containers/Data/Application/C00DF827-E2C7-479D-8569-26BC84724F67/tmp/CFNetworkDownload_w7z5UB.tmp, NSUnderlyingError=0x17404eeb0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}


Кто знает, буду очень признателен
  • Вопрос задан
  • 192 просмотра
Решения вопроса 1
doublench21
@doublench21 Куратор тега Swift
// -
try FileManager.default.moveItem(at: location, to: destinationURL)

// +
if fileManger.fileExists(atPath: destinationURL.path) {
   try fileManger.removeItem(at: destinationURL)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы