ios - Swift 文件下载问题

标签 ios swift

我正在尝试从远程位置下载一个 plist 文件,并在我正在创建的 iOS 应用程序中使用它。该文件将用于应用程序日历中的日历详细信息。目标显然是我可以更新远程文件,而不是每次需要更改日历详细信息时都必须将更新推送到应用程序本身。

我从这个例子中使用的代码开始:Download File From A Remote URL

这是我修改后的版本:

// Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("2017.plist")
    //let destinationFileUrl = URL(string: Bundle.main.path(forResource: String(currentYear), ofType: "plist")!)


    //Create URL to the source file you want to download
    let fileURL = URL(string: "https://drive.google.com/open?id=0BwHDQFwaL9DuLThNYWwtQ1VXblk")

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL!)

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")

            }

            do {

                try FileManager.default.removeItem(at: destinationFileUrl)
                try FileManager.default.moveItem(at: tempLocalUrl, to: destinationFileUrl)
                print("File was replaced")
                print(NSArray(contentsOf: tempLocalUrl))
                //print(tempLocalUrl)
            } catch (let writeError) {
                print("Error creating a file \(String(describing: destinationFileUrl)) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
        }
    }
    task.resume()

我最初试图覆盖与应用程序捆绑在一起的文件,结果出错。所以我改为尝试将其保存在应用程序的文档文件夹中,并删除了该错误。我必须确保并删除该文件的任何先前版本,因为它在第一次运行后给我一个文件已存在的错误。

虽然它说一切正常(成功下载和替换文件的输出都会发生),但当我从下载的 URL 打印数组的内容时,它只给我 nil

这是我第一次尝试在应用程序中使用任何类型的外部资源。之前我总是把所有事情都藏在心里,所以我确信我遗漏了一些非常明显的东西。

更新 1: 我意识到我没有用于从 Google 驱动器下载文件的正确 URL。该行代码已更改为:

let fileURL = URL(string: "https://drive.google.com/uc?export=download&id=0BwHDQFwaL9DuLThNYWwtQ1VXblk")

所以现在我实际上正在下载 plist,就像我最初认为的那样。即使删除了第一条评论中提到的删除问题,我仍然无法让下载的文件真正替换现有的文件。

更新 2: 我已将实际文件操作减少到以下内容:

do {


                    try FileManager.default.replaceItemAt(destinationFileUrl, withItemAt: tempLocalUrl)
                    print("File was replaced")
                    print(NSArray(contentsOf: destinationFileUrl))

                } catch (let writeError) {
                    print("Error creating a file \(String(describing: destinationFileUrl)) : \(writeError)")
                }

            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
            }

执行替换后,文件的输出显示从互联网下载的正确新内容。

稍后在代码中,当我尝试访问该文件时,它的内容似乎再次为零。

最佳答案

查看您的下载完成代码。你:

  1. 删除目标 URL 处的文件(以防万一 剩下的)

  2. MOVE 临时文件到目标 URL(删除它从临时文件 网址)

  3. 尝试从临时 URL 加载文件。

这张图有什么问题吗?

关于ios - Swift 文件下载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043318/

相关文章:

ios - 如何在 Popover 的 TableView 选择中禁用动画?

ios - 如何在其他项目中复用 Swift 代码?

ios - 如何在urlRequest中向httpBody添加urlencoded参数

ios - UIViewController 中的 UITableView 不显示内容

ios - 本地化 Storyboard : How to add new content?

ios - 更好的可点击表格 View 单元格的可访问性标签

arrays - Swift:为什么在使用追加时没有元素添加到我的数组中?

ios - 我的字体大小不适用于我的自定义字体

ios - 关键字 "device"在Metal Shading Language中是什么意思

ios - 正确使用UINavigationController?