Hello community!
I made an app, where the user can add videos from their photo library and they are copied into the app, where they are displayed. A PHpicker gets the video from the library and copies it to the documents-directory of the app, then returns the url, showing where it is saved, as a string. That url -string is then saved in core data and retrieved in order to watch the video, in a video player. This all works really well, until the app is rebuilt, because then the url saved to core data doesn’t lead to the video anymore.
It is basically this problem:
So my question: How can I save some kind of key in core data, that always returns me the right url to that video, instead of saving the url directly? I wasn’t able to implement the Stack overflow solutions, sorry about that /: , that’s why I am asking here. The code for the picker and saving the url to core data is below:
Picker:
import SwiftUI
import UIKit
import PhotosUI
struct VideoPicker: UIViewControllerRepresentable{
@Binding var videoURL:String?
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
config.filter = .videos
let picker = PHPickerViewController(configuration: config)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator:NSObject, PHPickerViewControllerDelegate{
let parent:VideoPicker
init(_ parent: VideoPicker){
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true) {
// do something on dismiss
}
guard let provider = results.first?.itemProvider else {return}
provider.loadFileRepresentation(forTypeIdentifier: "public.movie") { url, error in
guard error == nil else{
print("error in video picker")
return
}
// receiving the video-local-URL / filepath
guard let url = url else {
print("error 2 in video picker")
return
}
// create a new filename
let fileName = "\(Int(Date().timeIntervalSince1970)).\(url.pathExtension)"
// create new URL
let newUrl = URL(fileURLWithPath: NSTemporaryDirectory() + fileName)
// copy item to APP Storage
try? FileManager.default.copyItem(at: url, to: newUrl)
self.parent.videoURL = newUrl.absoluteString
print("video added")
}
}
}
}
Core Data Save:
//exercise.videoUrls is an array of strings,
func saveVideo( url: String){
if exercise.videoUrls != nil{
exercise.videoUrls!.append(url)
try! viewContext.save()
} else {
exercise.videoUrls = [url]
try! viewContext.save()
}