我正在尝试使用 AlamoFire 下载文件并将其保存到用户选择的下载目录(如 safari)。但是,每当我将下载目录设置为应用程序文档之外的文件夹时,我都会收到以下错误(在真实的 iOS 设备上):
downloadedFileMoveFailed(错误:错误域=NSCocoaErrorDomain代码=513““CFNetworkDownload_dlIcno.tmp” 无法移动,因为您无权访问“下载”。” UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/A24D885A-1306-4CE4-9B15-952AF92B7E6C/tmp/CFNetworkDownload_dlIcno.tmp,NSUserStringVariant=(移动),NSDestinationFilePath=/private/var/mobile/Containers /共享/AppGroup/E6303CBC-62A3-4206-9C84-E37041894DEC/文件提供程序存储/下载/100MB.bin,NSFilePath=/private/var/mobile/Containers/Data/Application/A24D885A-1306-4CE4-9B15-952AF92B7E6C/ tmp/CFNetworkDownload_dlIcno.tmp,NSUnderlyingError=0x281d045d0 {Error Domain=NSPOSIXErrorDomain Code=1“不允许操作”}},来源:file:///private/var/mobile/Containers/Data/Application/A24D885A-1306-4CE4- 9B15-952AF92B7E6C/tmp/CFNetworkDownload_dlIcno.tmp,目标:文件:///private/var/mobile/Containers/Shared/AppGroup/E6303CBC-62A3-4206-9C84-E37041894DEC/File%20Provider%20Storage/Downloads/100MB.bin )
该错误的摘要是我无权访问刚刚授予访问权限的文件夹。
这是我附加的代码:
import SwiftUI
import UniformTypeIdentifiers
import Alamofire
struct ContentView: View {
@AppStorage("downloadsDirectory") var downloadsDirectory = ""
@State private var showFileImporter = false
var body: some View {
VStack {
Button("Set downloads directory") {
showFileImporter.toggle()
}
Button("Save to downloads directory") {
Task {
do {
let destination: DownloadRequest.Destination = { _, response in
let documentsURL = URL(string: downloadsDirectory)!
let suggestedName = response.suggestedFilename ?? "unknown"
let fileURL = documentsURL.appendingPathComponent(suggestedName)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let _ = try await AF.download(URL(string: "https://i.imgur.com/zaVQDFJ.png")!, to: destination).serializingDownloadedFileURL().value
} catch {
print("Downloading error!: \(error)")
}
}
}
}
.fileImporter(isPresented: $showFileImporter, allowedContentTypes: [UTType.folder]) { result in
switch result {
case .success(let url):
downloadsDirectory = url.absoluteString
case .failure(let error):
print("Download picker error: \(error)")
}
}
}
}
重现(在真实的 iOS 设备上运行!):
Set downloads directory
按钮即可 On my iPhone
Save to downloads directory
按钮经过进一步调查,我发现 safari 使用
Files and Folders
隐私权限(位于 iPhone 上的 Settings > Privacy > Files and folders
)来访问应用程序沙箱之外的文件夹( 代表我正在谈论的图像)。我尽可能多地搜索网络,但找不到任何有关此确切权限的文档。
我见过非苹果应用程序(例如VLC)使用此权限,但我不知道它是如何授予的。
我尝试启用以下 plist 属性,但它们都不起作用(因为我后来意识到这些属性仅适用于 macOS)
<key>NSDocumentsFolderUsageDescription</key>
<string>App wants to access your documents folder</string>
<key>NSDownloadsFolderUsageDescription</key>
<string>App wants to access your downloads folder</string>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
有人可以帮我弄清楚如何授予文件和文件夹权限并解释它的作用吗?我非常感谢您的帮助。
经过一番研究,我偶然发现了这个苹果文档页面(当我发布这个问题时,经过几个小时的谷歌搜索后没有找到)
https://developer.apple.com/documentation/uikit/view_controllers/providing_access_to_directories
导航至文章的
Save the URL as a Bookmark
部分。
利用 SwiftUI fileImporter 可以对用户选择的目录进行一次性读/写访问。为了保留这种读/写访问权限,我必须制作一个书签并将其存储在某个地方以便稍后访问。
由于我只需要用户下载目录的一个书签,因此我将其保存在 UserDefaults 中(书签的大小非常小)。
保存书签时,应用程序会添加到用户设置中的
Files and folders
中,因此用户可以立即撤销应用程序的文件权限(因此我的代码片段中的所有防护语句)。
这是我使用的代码片段,经过测试,下载确实在应用程序启动和多次下载时持续存在。
import SwiftUI
import UniformTypeIdentifiers
import Alamofire
struct ContentView: View {
@AppStorage("bookmarkData") var downloadsBookmark: Data?
@State private var showFileImporter = false
var body: some View {
VStack {
Button("Set downloads directory") {
showFileImporter.toggle()
}
Button("Save to downloads directory") {
Task {
do {
let destination: DownloadRequest.Destination = { _, response in
// Save to a temp directory in app documents
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Downloads")
let suggestedName = response.suggestedFilename ?? "unknown"
let fileURL = documentsURL.appendingPathComponent(suggestedName)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let tempUrl = try await AF.download(URL(string: "https://i.imgur.com/zaVQDFJ.png")!, to: destination).serializingDownloadedFileURL().value
// Get the bookmark data from the AppStorage call
guard let bookmarkData = downloadsBookmark else {
return
}
var isStale = false
let downloadsUrl = try URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &isStale)
guard !isStale else {
// Log that the bookmark is stale
return
}
// Securely access the URL from the bookmark data
guard downloadsUrl.startAccessingSecurityScopedResource() else {
print("Can't access security scoped resource")
return
}
// We have to stop accessing the resource no matter what
defer { downloadsUrl.stopAccessingSecurityScopedResource() }
do {
try FileManager.default.moveItem(at: tempUrl, to: downloadsUrl.appendingPathComponent(tempUrl.lastPathComponent))
} catch {
print("Move error: \(error)")
}
} catch {
print("Downloading error!: \(error)")
}
}
}
}
.fileImporter(isPresented: $showFileImporter, allowedContentTypes: [UTType.folder]) { result in
switch result {
case .success(let url):
// Securely access the URL to save a bookmark
guard url.startAccessingSecurityScopedResource() else {
// Handle the failure here.
return
}
// We have to stop accessing the resource no matter what
defer { url.stopAccessingSecurityScopedResource() }
do {
// Make sure the bookmark is minimal!
downloadsBookmark = try url.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: nil, relativeTo: nil)
} catch {
print("Bookmark error \(error)")
}
case .failure(let error):
print("Importer error: \(error)")
}
}
}
}
code24的答案是正确的,但我想添加额外的上下文,以防您的书签出现问题,只能工作一次或根本不起作用(或者可能在一段时间后过期)。
您还需要创建书签AFTER并调用
startAccessingSecurityScopedResource
,否则书签在单次使用后或一段时间后将停止工作。
guard url.startAccessingSecurityScopedResource() else {
// Handle the failure here.
return
}
// ...
// Call bookmarkData() here
您可能还想尝试将其添加到您的 info.plist 文件中:
Application supports iTunes file sharing -> Yes