我想读取 url 的内容,但此代码在 macOS 中产生了有关权限的问题,我在 iOS 中测试了此代码,它有效,但在 macOS 中产生了权限问题,我知道删除沙箱可以解决问题,但我无法使用这种方式,因为我需要在应用程序商店中午餐这个应用程序,那么如何解决这个问题?
import SwiftUI
struct ContentView: View {
@State var isShowing: Bool = Bool()
var body: some View {
VStack {
Button("Import Folder") {
isShowing.toggle()
}
}
.padding()
.fileImporter(isPresented: $isShowing, allowedContentTypes: [.folder], allowsMultipleSelection: false, onCompletion: { results in
switch results {
case .success(let items):
print("count: " + String(items.count))
print("- - - - - - - - - - -")
for item in items {
print(item.path)
lookToURL(item: item)
}
print("- - - - - - - - - - -")
case .failure(let error):
print(error)
}
})
}
}
func lookToURL(item: URL) {
isItemDirectory(at: item, result: { itemResult in
if let itemIsDirectory: Bool = itemResult {
if (itemIsDirectory) {
print("Item is a folder!", "Name:", item.lastPathComponent)
contentsOfDirectory(url: item, contents: { contents in
for content in contents {
lookToURL(item: content)
}
})
}
else {
print("Item is a file!", "Name:", item.lastPathComponent)
}
}
else {
print("Item is not a folder or file!")
}
})
}
func contentsOfDirectory(url: URL, contents: ([URL]) -> Void) {
if (FileManager.default.fileExists(atPath: url.path)) {
if let unwrappedValueOfIsDirectory: Bool = isItemDirectory(at: url) {
if (unwrappedValueOfIsDirectory) {
do {
let contentsOfDirectory = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
contents(contentsOfDirectory)
}
catch let error {
print(error.localizedDescription)
}
}
else {
print("URL is a file!")
}
}
}
else {
print("URL is not a folder or file!")
}
}
func isItemDirectory(at url: URL, result: (Bool?) -> Void) {
do {
result(try url.resourceValues(forKeys: [URLResourceKey.isDirectoryKey]).isDirectory)
}
catch let error {
print(error.localizedDescription)
result(nil)
}
}
func isItemDirectory(at url: URL) -> Bool? {
do {
return (try url.resourceValues(forKeys: [URLResourceKey.isDirectoryKey]).isDirectory)
}
catch let error {
print(error.localizedDescription)
return nil
}
}
错误:
数量:1
/卷/mac Drive/我的版本
项目是一个文件夹!名称:我的发布
无法打开文件“我的版本”,因为您无权查看它。
url.startAccessingSecurityScopedResource
。
顺便说一下,如果您想保留权限,即使用户已重命名文件夹或重新启动您的应用程序,您也需要
url.bookmarkData
。