重新运行应用程序后无法访问 swiftui photopicker 视频

问题描述 投票:0回答:1

我正在尝试用照片选择器这样选择视频:

@State var selectedItem: PhotosPickerItem? = nil
@State var showPhotoPicker = false

对于这两种状态,我将显示选择器:

    .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
            }
        }
    }

我的SelectedMovie如下:

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)
    }
  }
}

我保存的url路径是:

file:///Users/mymac/Library/Developer/CoreSimulator/Devices/BB7B011B-B525-49E1-837E-4828D3151B3F/data/Containers/Data/Application/336F4FD2-F4EA-46E8-AB6B-80023E195E5E/Documents/mymovie.mp4

我正在使用 Xcode 模拟器 Iphone 15

我正在尝试将选定的视频保存在文档目录中,一切顺利,但是当我重新运行应用程序(通过 xcode)时,文件将无法再访问。 知道我做错了什么吗? 谢谢

ios swift swiftui nsfilemanager photo-picker
1个回答
0
投票

正如 lorem ipsum 建议的那样(请参阅相关评论), 我只需要“播放”我的文件名(lastPathComponent) 所以我的保存逻辑没问题。

因此,不要保留初始网址(其中包含文档文件夹的非固定路径) 我将只使用它的lastPathComponent 并创建正确的url:

let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = dir.appendingPathComponent(initialUrl.lastPathComponent)

或者, 我应该只保存lastPathComponent 的字符串而不是整个url,但这将需要数据库更改。

感谢您的协助!

© www.soinside.com 2019 - 2024. All rights reserved.