func scene(_ scene: UIScene, openURLContexts...) - 无法通过 FileManager.copyItem() 复制 URL

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

不知道为什么在尝试复制通过 openURLContexts 传递到我的应用程序的文件时会出现此错误。源文件位于我的 iCloud 驱动器上,我点击它打开了我的应用程序。

有趣的是,我可以读取传入的 URL (JSON),因此该文件实际上对我来说是可读的,但如果我尝试将其复制到 iCloud 无处不在容器的临时目录,它会生成此异常。

tempDir路径= /private/var/mobile/Containers/Data/Application/E4886514-A6C5-41FE-A844-D57C40D10F24/tmp/someFile

将文件复制到临时目录时出错:Error Domain=NSCocoaErrorDomain Code=257“无法打开文件“somefile”,因为您无权查看它。” UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/somefile, NSUnderlyingError=0x2819ac090 {错误域=NSPOSIXErrorDomain 代码=1“不允许操作”}}
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else { return }
        let filename = url.lastPathComponent            
        // Cache it a temporary location so we can keep the URL valid and readable
        let tempDirURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
        do {
            try FileManager.default.copyItem(at: url, to: tempDirURL)
        } catch {
            print("Error copying file to temporary directory: \(error)")
        }
    }
ios swift url copy file-permissions
1个回答
0
投票

您需要检查文件是否必须就地打开。这是通过查看 URL 上下文选项的

openInPlace
属性来完成的。

如果已设置,则您必须使用

startAccessingSecurityScopedResource()/stopAccessingSecurityScopedResource()
并在其间进行访问。

这是更新后的场景委托方法:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let urlContext = URLContexts.first else { return }

    let url = urlContext.url
    let filename = url.lastPathComponent
    let openInPlace = urlContext.options.openInPlace

    // Cache it a temporary location so we can keep the URL valid and readable
    let tempDirURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename)

    defer {
        if openInPlace {
            url.stopAccessingSecurityScopedResource()
        }
    }

    do {
        if !openInPlace || url.startAccessingSecurityScopedResource() {
            try FileManager.default.copyItem(at: url, to: tempDirURL)
        }
    } catch {
        print("Error copying file to temporary directory: \(error)")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.