2017-07-31 80 views
0

我一直在努力閱讀plist文件到我的iOS應用程序,但是我迄今使用的每種方法都失敗了。我目前使用的方法描述在http://basememara.com/reading-values-plist-bundle-swift/,但在我嘗試的每種方法似乎都有同樣的問題。變量不會填充plist數據,Swift

如果這是閱讀的plist文件中的代碼:

/** 
Gets the contents of the specified plist file. 

- parameter plistName: property list where defaults are declared 
- parameter bundle: bundle where defaults reside 

- returns: dictionary of values 
*/ 
public static func contentsOfFile(plistName: String, bundle: Bundle? = nil) -> [String : AnyObject] { 
    let fileParts = plistName.components(separatedBy: ".") 

    guard fileParts.count == 2, 
     let resourcePath = (bundle ?? Bundle.main).path(forResource: fileParts[0], ofType: fileParts[1]), 
     let contents = NSDictionary(contentsOfFile: resourcePath) as? [String : AnyObject] 
     let contentsarray = NSArray(contentsOfFile: resourcePath) 
     else { return [:] } 

    return contents 
} 

和呼叫

let values = Bundle.contentsOfFile(plistName: "Event.plist") 
print(values["Item0"]) // My string value 1. 

隨着plist中看起來像 enter image description here

變量內容和ContentsArray(用於測試)沒有任何東西。我已經驗證了resourcePath是正確的,並且沒有給出錯誤,所以我不知道什麼是錯的。其他每種方法都有正確的路徑,但永遠不會填充內容變量。

回答

0
if let path = Bundle.main.path(forResource: "Test", ofType: "plist") { 
     let myDict = NSDictionary(contentsOfFile: path) 
     print(myDict) 
} 

另一種方式 -

if let url = Bundle.main.url(forResource:"Test", withExtension: "plist"), 
     let myDict = NSDictionary(contentsOf: url) as? [String:Any] { 
     print(myDict) 
} 

此外,它可能有一些做目標與目標的成員也是如此。在項目導航器中選擇plist文件並檢查File inpector的目標成員部分。

+0

檢查文件的目標成員資格,並在finder中存在它說它會看起來,但這兩種方法打印零。 – traisjames

+0

文件的位置是什麼?它是在主包還是從某個地方下載它,同時保存到其他目錄,如緩存? – Avi

+0

它在主包中(.../6922A277-91D7-4F70-A03F-0DD6541C89EF/LG%20Sim%20Builder.app/Event.plist) – traisjames