Read plist in swift 3 playground

孤街浪徒 提交于 2019-12-01 10:02:03

问题


I have followed loads of questions here but nothing seems to work.

I am using Swift3 in a Playground. Running on El Capitan and Xcode 8.1. I have a plist with the root as a Dictionary containing one Int value and two 2D Arrays of Ints.

plist

Every question I follow does not seem to work the closest I have got is for the playground to not return errors but it seems to be constantly running (the spinning icon never stops).

my current code, I believe to be the closest I have achieved.

import Foundation 
if let path = Bundle.main.path(forResource: "levelList", ofType: "plist") {
    let plistXML = FileManager.default.contents(atPath: path)!

    let mydata = try! PropertyListSerialization.propertyList(from: plistXML, options: [], format: nil) as! [String:Any]
}

other options I have tried from previous stack overflow answers in a similar context.

let mydata = Dictionary(fromPropertyList: path, format: "XML") as! [String: Any]
******
let mydata = Dictionary(contentsOf: path) as? [String: Any]

The data was added to the resources folder correctly as the linked question gave instructions for. I have restarted Xcode(and mac) as suggested in the comments. After a while the execution stopped with error "error: Execution was interrupted reason exc_bad_access (code=1 address=0x0)" After another restart the code works. How do would i extract the data into an array in swift since at the moment the playground is showing ["Level 2":["Col": <_NS_array0 0x7fc620d091a0>(


回答1:


You are using the wrong API, you need to load Data rather than something in the file system.

if let url = Bundle.main.url(forResource: "levelList", withExtension: "plist"),
   let plistData = try? Data(contentsOf: url ) {
      let mydata = try! PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as! [String:Any]
}



回答2:


To finally get the program working I used.

devices = NSArray(contentsOfFile: path) as! [AnyObject]

The issue with playground continuously running was solved by going to activity monitor and force quitting the process named com.apple.coresimulator which was identified as not responding. After doing this the playground ran instantly.



来源:https://stackoverflow.com/questions/41074149/read-plist-in-swift-3-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!