如何使用Swift 3 iOS应用程序阅读plist [英] How to read from a plist with Swift 3 iOS app

查看:151
本文介绍了如何使用Swift 3 iOS应用程序阅读plist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

-Disclaimer-

我对iOS和Swift开发非常陌生,但我对编程并不是特别陌生。

我有一个基本的 iOS 应用程序,其中包含 Swift3 元素。
我我创建了一个 plist 文件,其中包含一些我想要阅读并在我的应用程序中显示的条目。 (无需写入权限)

I have a basic iOS application with Swift3 elements in it.
I've created a plist file with some entries I want to read and display in my application. (No write access is necessary)

如何读取捆绑的 plist的给定键的值文件,在Swift3中?

How can you read a value for a given key for a bundled plist file, in Swift3?

这对我来说似乎是一个非常简单的问题,但是一堆搜索让我感到惊讶质疑我的整个概念方法。

This seems like a really simple question to me, but a bunch of searching is making me question my whole conceptual approach.

有用的提示将不胜感激。

Helpful tips would be appreciated.

推荐答案

你在Swift 2.3或更低版本中完成的方法只是改变了语法。

Same way you have done in Swift 2.3 or lower just syntax is changed.

if let path = Bundle.main.path(forResource: "fileName", ofType: "plist") {

    //If your plist contain root as Array
    if let array = NSArray(contentsOfFile: path) as? [[String: Any]] {

    }

    ////If your plist contain root as Dictionary
    if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] {

    }
}

注意:在Swift中最好使用Swift的泛型类型Array和Dictionary而不是 NSArray NSDictionary

Note: In Swift it is better to use Swift's generic type Array and Dictionary instead of NSArray and NSDictionary.

编辑:而不是 NSArray(contentsOfFile:path) NSDictionary(contentsOfFile :) 我们也可以使用 PropertyListSerialization.propertyList(from:) plist 文件中读取数据。

Instead of NSArray(contentsOfFile: path) and NSDictionary(contentsOfFile:) we can also use PropertyListSerialization.propertyList(from:) to read data from plist file.

if let fileUrl = Bundle.main.url(forResource: "fileName", withExtension: "plist"),
   let data = try? Data(contentsOf: fileUrl) {
       if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String: Any]] { // [String: Any] which ever it is 
            print(result)
       }
}

这篇关于如何使用Swift 3 iOS应用程序阅读plist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆