我正在尝试使用AlamoFire下载一个文件,并将其保存到用户选择的下载目录(比如safari)。但是,每当我将下载目录设置为应用程序文档之外的文件夹时,就会得到以下错误(在实际的iOS设备上):
downloadedFileMoveFailed(错误:错误Domain=NSCocoaErrorDomain Code=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/Shared/AppGroup/E6303CBC-62A3-4206-9C84-E37041894DEC/File Provider存储/下载/100 MB.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,目的地: file:///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 iPhoneSave 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/>有人能帮我弄清楚如何授予文件和文件夹权限并解释它的作用吗?我真的很感谢你的帮助。
发布于 2022-01-18 22:24:30
经过一些研究后,我无意中发现了这个苹果文档页面(当我发布这个问题时,在谷歌搜索了几个小时之后,没有找到这个页面)。
导航到本文的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)")
}
}
}
}https://stackoverflow.com/questions/70750276
复制相似问题