ios - 导入应用程序后保存文件

标签 ios swift import

我有一个 iOS 应用程序,我想保存当 Safari 上的用户下载文件并选择“使用 MYAPP 导入”时提供给它的文件

我已经得到了它识别出我的应用程序支持该文件的部分,但是当我选择使用该应用程序打开该文件时,它没有被添加。

关于这方面的文档确实不多,或者至少最近没有。这是我保存文件的失败尝试:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?, openURL Url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {

    let encrypteddata = NSData(contentsOf: Url as URL)
    if(encrypteddata != nil){

        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("test.ipa")
        print(paths)
        fileManager.createFile(atPath: paths as String, contents: encrypteddata as Data?, attributes: nil)

    }
return true

}

更新:

这些文件似乎存储在应用程序沙箱容器的 Documents/Inbox 目录中。如何列出所有文件并读取其内容?

最佳答案

一旦您获得了

的 URL
optional func application(_ application: UIApplication, open url: URL, 
    sourceApplication: String?, 
           annotation: Any) -> Bool

方法,您可以从此 URL 访问文件,也可以从 FileManager 中查找所有文档,如下所示

let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
    print(directoryContents)
} catch let error as NSError {
    print(error.localizedDescription)
}

这将列出文档目录中的所有文件。

关于ios - 导入应用程序后保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476391/

相关文章:

android-studio - 无法在 Android Studio 中导入标准 java 库类

ios - UIView 滚动到顶部

ios - 如何在 Swift 上单击按钮时打开 pdf 链接?

swift - 核心数据+本地化

python - pyinstaller onefile 但仍然导入外部库(如果可用)

python - 如何导入我在 Python 中创建的类并创建该类的实例?我收到一条错误消息,指出对象不可调用

iOS 从服务器同步对象的 json 列表

ios - Xcode 6 - 语法高亮/完成不起作用

ios - Obj-C 解析秒到 dd :hh:mm:ss

swift - 尝试使用 PAT 应用扩展时出现不符合协议(protocol)错误