我正在编写一个小型 Mac OS X 桌面应用程序,它将文件的随机样本从源文件夹复制到目标文件夹,请参阅 https://github.com/belovachap/Select-Random-Files-Mac/blob/主/选择%20Random%20Files/ContentView.swift
目前给我带来最大麻烦的代码是 FileManager.default.copyItem 方法。即使我在文档目录中选择对我的用户似乎具有读/写权限的文件夹,我也会收到错误“无法复制,因为您无权访问”。
这是相关代码
//
// ContentView.swift
// Select Random Files
//
// Created by Chapman on 6/29/24.
//
import SwiftUI
struct ContentView: View {
@State var sourceFolder: URL? = nil
@State var destinationFolder: URL? = nil
var body: some View {
VStack {
Button("Choose Source Folder") {
self.selectSourceFolder()
}
Button("Choose Destination Folder") {
self.selectDestinationFolder()
}
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Button(action: {
var files = [URL]()
if let enumerator = FileManager.default.enumerator(at: sourceFolder!, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
for case let fileURL as URL in enumerator {
do {
let fileAttributes = try fileURL.resourceValues(forKeys:[.isRegularFileKey])
if fileAttributes.isRegularFile! {
files.append(fileURL)
}
} catch { print(error, fileURL) }
}
print(files)
}
files = Array(files.shuffled().prefix(3))
for f in files {
let dst = destinationFolder!.appendingPathComponent(f.lastPathComponent)
do { try FileManager.default.copyItem(at: f, to: dst)
} catch { print(error, f) }
}
}, label: {
Text("Copy")
})
}
.padding()
}
func buildFolderPicker() -> NSOpenPanel {
let folderChooserPoint = CGPoint(x: 0, y: 0)
let folderChooserSize = CGSize(width: 500, height: 600)
let folderChooserRectangle = CGRect(origin: folderChooserPoint, size: folderChooserSize)
let folderPicker = NSOpenPanel(contentRect: folderChooserRectangle, styleMask: .utilityWindow, backing: .buffered, defer: true)
folderPicker.canChooseDirectories = true
folderPicker.canChooseFiles = true
folderPicker.allowsMultipleSelection = true
folderPicker.canDownloadUbiquitousContents = true
folderPicker.canResolveUbiquitousConflicts = true
return folderPicker
}
func selectSourceFolder() {
let folderPicker = buildFolderPicker()
folderPicker.begin { response in
if response == .OK {
sourceFolder = folderPicker.url
}
}
}
func selectDestinationFolder() {
let folderPicker = buildFolderPicker()
folderPicker.begin { response in
if response == .OK {
destinationFolder = folderPicker.url
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
以及单击“复制”按钮的屏幕截图,其中包含有关权限错误的控制台输出:
我已经尝试用谷歌搜索这个问题,但似乎没有很多解决我的问题的示例。
我们想通了!!我只设置了只读权限,需要读写!这是解决所有问题的行:https://github.com/belovachap/Select-Random-Files-Mac/blob/main/Select%20Random%20Files/Select_Random_Files.entitlements#L7