使用 URL 将 Plist 文件加载到数组中

Use URL to Load Plist File into Array

我创建了一个在表视图中包含员工目录的应用程序。该应用程序在我的项目中使用 plist 文件创建字典数组时运行良好,但该文件经常随着员工的来去而更改,因此我确实需要将其置于 Xcode 项目之外。我正在尝试使用 URL 和 NSURL 来完成它,但是在让它工作时遇到了问题并且需要一组新的眼睛。假设文件位于 www.abc.com/directory.plist?
,最好的方法是什么? 对不起,我几乎是一个编程初学者,但我正在尽快学习!

这是我的功能代码:

class TableViewController: UITableViewController {

var filePath: String?
var employees: [[String: String]] = []

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.delegate = self
    self.tableView.dataSource = self

    filePath = Bundle.main.path(forResource: "directory", ofType: "plist")
    employees = NSArray(contentsOfFile: filePath!) as! [[String: String]]

    for item in employees {

        print(item["Name"] as Any)
        print(item.count)
        print(employees.count)
    }
}

编辑 -
我在我的代码中用 PropertyListSerialization 替换了 NSArray。仍在使用 URLSession 添加远程文件加载。

        if let filePath = Bundle.main.url(forResource: "directory", withExtension: "plist") {
        do {
            let data = try Data(contentsOf:filePath)
            employees = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [[String : String]]

        } catch {
            print("Error loading file.")
        }
    }

正如其他人所说,您需要使用 NSURLSessionURLSession in Swift 3)

这是从远程服务器进行异步下载的现代方式。

我写了一个名为 Async_demo 的小演示项目,您可以从 Github 下载它,其中包括 class DownloadManager。您可以将 class 放到您的项目中,以将您的 plist 数据下载为 Data 对象。然后,您将该数据保存到应用程序的文档或缓存目录中。

我成功了。感谢您使用 URLSession 为我指明了正确的方向。我阅读了 Apple 的文档,然后将 Xcode 自动完成和几个示例拼凑在一起,其中一些来自 vadian。我希望这对其他人有帮助。

    override func viewDidLoad() {
    super.viewDidLoad()

    let filePath = URL(string: "https://www.example.com/directory.plist")
    URLSession.shared.dataTask(with: filePath!) { (data, response, error) in
        if error != nil {
            print("Error loading URL.")
        }
    }
    do {
            let data = try Data(contentsOf:filePath!)
            employees = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [[String : String]]

            for item in employees {
                print(item["Name"] as Any)
                print(item.count)
                print(employees.count)
            }
    } catch {
           print("Error loading employee data.")
      }
  }

URLSession.shared.dataTask(with: filePath!) { (data, response, error) and PropertyListSerialization.propertyList(from: data, options: [] 绝对是要走的路。搞定它真好出来并在此处为社区的其他人发布您的答案。