I'm trying to pick a video with photo picker this way:
@State var selectedItem: PhotosPickerItem? = nil
@State var showPhotoPicker = false
With those 2 states i'm showing the picker:
.photosPicker(isPresented: $showPhotoPicker, selection: $selectedItem, matching: .videos)
.onChange(of: selectedItem) {
if let item = selectedItem {
showProgress = true
item.loadTransferable(type: SelectedMovie.self) { result in
switch result {
case .success(let movie):
if let movie = movie {
onVideoSelected(movie.url)
} else {
Log.w("movie is nil")
}
case .failure(let failure):
Log.w("\(failure.localizedDescription)")
}
showProgress = false
}
}
}
And my SelectedMovie is as follows:
struct SelectedMovie: Transferable {
let url: URL
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(contentType: .movie) { movie in
SentTransferredFile(movie.url)
} importing: { received in
let fileName = received.file.lastPathComponent
Log.d("File name: \(fileName)")
let copy = URL.documentsDirectory.appendingPathComponent(fileName)
do {
if FileManager.default.fileExists(atPath: copy.path()) {
try FileManager.default.removeItem(at: copy)
}
try FileManager.default.copyItem(at: received.file, to: copy)
} catch {
Log.e("Cannot copy movie: \(error.localizedDescription)")
}
Log.d("Copied: \(copy.path())")
return Self.init(url: copy)
}
}
}
The path of my saved url is:
file:///Users/mymac/Library/Developer/CoreSimulator/Devices/BB7B011B-B525-49E1-837E-4828D3151B3F/data/Containers/Data/Application/336F4FD2-F4EA-46E8-AB6B-80023E195E5E/Documents/mymovie.mp4
I'm using the Xcode simulator Iphone 15
I'm trying to save the selected video in the document directory, all goes well but when i'm rerunning the app (via xcode) the file is not accessible anymore. any idea what i'm doing wrong? Thanks
As lorem ipsum suggested (see comments in question), I need to "play" only with my file name (lastPathComponent) so my save logic is fine.
So instead of keeping the initial url (which holds non fixed path to the document folder) I will take only its lastPathComponent and create the correct url:
let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = dir.appendingPathComponent(initialUrl.lastPathComponent)
Alternatively, I should save only the string of lastPathComponent instead the whole url but it will require db changes.
Thanks for assisting!