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

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

问题描述

-免责声明-
我对 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)

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

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 而不是 NSArrayNSDictionary.

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

我们也可以使用 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天全站免登陆