简体   繁体   English

尝试使用Swift 2.0从Document目录中读取plist文件

[英]Trying to read a plist file from the Document directory using swift 2.0

Ok, Managed to put this code together, created a plist file with Xcode which I copied {using iTunes} to the app folder, it doesn't work... 好的,设法将这段代码放在一起,用Xcode创建了一个plist文件,我将{using iTunes}复制到了app文件夹中,但是它不起作用...

import Foundation

class getBeaconConfiguration {
var myBeaconsDict: NSDictionary?

func getBeacons() {
    let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
    let sourcePath:NSString = documentsPath.stringByAppendingString("/beacons.plist")

    let dict = NSDictionary(contentsOfFile: sourcePath as String)
    print("dict",dict)

   }

} }

The path is good, and the plist is there, but the NSDictionary returned is a null pointer it seems. 路径很好,plist在那,但是返回的NSDictionary似乎是空指针。 How do you do this in swift 2.0. 您如何在Swift 2.0中做到这一点。

Get Create a URL to the file and then create a dictionary from it. 获取为文件创建URL,然后从中创建字典。

let filename = "beacons.plist"

guard
    let fileURL =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent(filename)
    else { fatalError("Unable to get file") }

let dict = NSDictionary(contentsOfURL: fileURL)

A little different in Swift 2.0, String no longer has stringByAppendingPathComponent, and you should be using this method when working with file paths. 在Swift 2.0中有所不同,String不再具有stringByAppendingPathComponent,在处理文件路径时应使用此方法。

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let sourcePath = documentsPath.stringByAppendingPathComponent("beacons.plist")
let dictionary = NSDictionary(contentsOfFile: sourcePath as String)
print("dict: \(dictionary)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM