-Haftungsausschluss-
Ich bin extrem neu in der Entwicklung von iOS und Swift, aber in der Programmierung bin ich nicht besonders neu.
Ich habe eine grundlegende iOS
-Anwendung mit Swift3
-Elementen darin.
Ich habe eine plist
-Datei mit einigen Einträgen erstellt, die ich in meiner Anwendung lesen und anzeigen möchte. (Es ist kein Schreibzugriff erforderlich)
Wie kann man einen Wert für einen bestimmten Schlüssel für eine gebündelte plist
-Datei in Swift3 lesen?
Dies scheint mir eine sehr einfache Frage zu sein, aber eine Reihe von Suchen lässt mich meinen gesamten konzeptionellen Ansatz in Frage stellen.
Hilfreiche Tipps wären dankbar.
Auf dieselbe Weise wie in Swift 2.3 oder niedriger wurde die Syntax geändert.
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] {
}
}
Hinweis: In Swift ist es besser, den generischen Typ Array und Dictionary von Swift anstelle von NSArray
und NSDictionary
zu verwenden.
Edit: Anstelle von NSArray(contentsOfFile: path)
und NSDictionary(contentsOfFile:)
können wir auch PropertyListSerialization.propertyList(from:)
verwenden, um Daten aus der plist
-Datei zu lesen.
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)
}
}
Wie Swift 4 Codable einführt
Schritt 1: Laden Sie die Plist-Datei aus dem Paket.
Schritt 2: Verwenden Sie PropertyListDecoder zum Dekodieren von Eigenschaftenlistenwerten in semantische Decodable
-Typen.
Schritt 3: Codierbare Struktur erstellen
Vollständiger Code -
func setData() {
// location of plist file
if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
do {
var settings: MySettings?
let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
let decoder = PropertyListDecoder()
settings = try decoder.decode(MySettings.self, from: data)
print("toolString is \(settings?.toolString ?? "")")
print("DeviceDictionary is \(settings?.deviceDictionary?.phone ?? "")")
print("RootPartArray is \(settings?.RootPartArray ?? [""])")
} catch {
print(error)
}
}
}
}
struct MySettings: Codable {
var toolString: String?
var deviceDictionary: DeviceDictionary?
var RootPartArray: [String]?
private enum CodingKeys: String, CodingKey {
case toolString = "ToolString"
case deviceDictionary = "DeviceDictionary"
case RootPartArray
}
struct DeviceDictionary: Codable {
var phone: String?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
phone = try values.decodeIfPresent(String.self, forKey: .phone)
}
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
toolString = try values.decodeIfPresent(String.self, forKey: .toolString)
deviceDictionary = try values.decodeIfPresent(DeviceDictionary.self, forKey: .deviceDictionary)
RootPartArray = try values.decodeIfPresent([String].self, forKey: .RootPartArray)
}
}
Plist-Beispieldatei -> https://Gist.github.com/janeshsutharios/4b0fb0e3edeff961d3e1f2829eb518db
Hier ein Beispiel, wie Sie BundleID von Info plist erhalten:
var appBundleID = "Unknown Bundle ID"
if let bundleDict = Bundle.main.infoDictionary,
let bundleID = bundleDict[kCFBundleIdentifierKey as String] as? String {
appBundleID = bundleID
}
Auf dieselbe Weise können Sie problemlos auf jeden Schlüssel zugreifen. Dieser Ansatz eignet sich für Projekte mit vielen Zielen.
Hier ist eine Swift 3 -Implementierung basierend auf Antwort von Nirav D :
/// Read Plist File.
///
/// - Parameter fileURL: file URL.
/// - Returns: return plist content.
func ReadPlist(_ fileURL: URL) -> [String: Any]? {
guard fileURL.pathExtension == FileExtension.plist, let data = try? Data(contentsOf: fileURL) else {
return nil
}
guard let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
return nil
}
print(result)
return result
}
In AppDelegate-Datei
var bundlePath:String!
var documentPath:String!
var plistDocumentPath:URL!
let fileManager = FileManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
bundlePath = Bundle.main.path(forResource: "Team", ofType: "plist")
documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
plistDocumentPath = URL.init(string: documentPath)?.appendingPathComponent("Team.plist")
print(plistDocumentPath.path)
if !fileManager.fileExists(atPath: plistDocumentPath.path){
do {
try fileManager.copyItem(atPath: bundlePath, toPath: plistDocumentPath.path)
} catch {
print("error Occured \(error.localizedDescription)")
}
}
return true
}
In ViewController
@IBOutlet weak var TeamTable: UITableView!
var appDelegate:AppDelegate!
var arrayForContacts:[[String:Any]]! // array object
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if appDelegate.fileManager.fileExists(atPath: appDelegate.plistDocumentPath.path){
arrayForContacts = []
if let contentOfPlist = NSArray.init(contentsOfFile: appDelegate.plistDocumentPath.path ){
arrayForContacts = contentOfPlist as! [[String:Any]]
TeamTable.reloadData()
}
}
}
Sie können den Wert auch direkt aus Ihrer plist-Datei lesen
let value = Bundle.init(for: AppDelegate.self).infoDictionary?["your plist key name"] as? Any
Für Swift 3.0 wird der folgende Code direkt auf den Schlüssel ausgerichtet. Wohin als dict object alles geben wird, was in Ihrer Plist-Datei vorhanden ist.
if let path = Bundle.main.path(forResource: "YourPlistFile", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
let value = dict["KeyInYourPlistFile"] as! String
}