From 1088e13f0880325b9af36bb36e1323b9ca83c766 Mon Sep 17 00:00:00 2001 From: Jungpyo Hong <54448459+jphong1111@users.noreply.github.com> Date: Wed, 5 May 2021 11:46:27 -0500 Subject: [PATCH] Create VideoDownloadManager.swift --- .../VideoDownloadManager.swift | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Helper/VideoDownloadHandler/VideoDownloadManager.swift diff --git a/Helper/VideoDownloadHandler/VideoDownloadManager.swift b/Helper/VideoDownloadHandler/VideoDownloadManager.swift new file mode 100644 index 0000000..3b27c51 --- /dev/null +++ b/Helper/VideoDownloadHandler/VideoDownloadManager.swift @@ -0,0 +1,40 @@ +// +// VideoManager.swift +// DispatchDemoApp +// +// Created by JungpyoHong on 4/29/21. +// +import Foundation +import PhotosUI + +struct VideoManager { + + func downloadVideoLinkAndCreateAsset(_ videoLink: String) { + + guard let videoURL = URL(string: videoLink) else { return } + guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } + if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) { + URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in + guard let location = location else { return } + let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? videoURL.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 + if completed { + print("Video asset created") + } else { + print("error") + } + } + } + }) + } catch { print(error) } + }.resume() + } else { + print("File already exists at destination url") + } + } +}