I believe something has changed within Swift 2, because no tutorials on how to read and write to property lists seem to be working.
Can anyone whose developing for iOS 9 share their method of R/W to Plists using Swift 2 on Xcode 7?
答案 0 :(得分:2)
这适用于iOS 9和Xcode 7:
let filePath = NSBundle.mainBundle().pathForResource("FileName", ofType: "plist")!
let stylesheet = NSDictionary(contentsOfFile:filePath)
唯一的结果是NSDictionary
而不是Dictionary
。
答案 1 :(得分:1)
希望这很有用 - 没有代码就很难回答。
让我失望的变化是,当将plist文件复制到文档目录时,方法stringByAppendingPathComponent不再可用。你必须使用NSURL。
如果你有一个preparePlistForUseMethod,它现在应该是这样的。
let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
let url = NSURL(string: rootPath)
plistPathInDocument = (url?.URLByAppendingPathComponent("plistfilename.plst").absoluteString)!
if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
let plistPathInBundle = NSBundle.mainBundle().pathForResource("plistfilename.plst", ofType: "plist")!
do{
try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
print("plist copied")
}
catch{
print("error copying plist!")
}
}
else{
print("plst exists \(plistPathInDocument)")
}
}
答案 2 :(得分:1)
为了在PLIST上阅读,我将逻辑封装在Singleton中。 就我而言,我想阅读文件URLs.plist。
/// <summary>
/// Parses a continuous hex stream from a string.
/// </summary>
public static byte[] ParseHexBytes(this string s)
{
if (s == null)
throw new ArgumentNullException("s");
if (s.Length == 0)
return new byte[0];
if (s.Length % 2 != 0)
throw new ArgumentException("Source length error", "s");
int length = s.Length >> 1;
byte[] result = new byte[length];
for (int i = 0; i < length; i++)
{
result[i] = Byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber);
}
return result;
}
只要您需要访问其中一个网址,就可以:
class URLs {
class var sharedInstance: URLs {
struct Singleton {
static let instance = URLs()
}
return Singleton.instance
}
private var urls: NSDictionary!
required init() {
let filePath = NSBundle.mainBundle().pathForResource("URLs", ofType: "plist")!
self.urls = NSDictionary(contentsOfFile:filePath)
}
var backendBaseUrl: String {
get {
return urls["BackendBaseUrl"] as! String
}
}
var locationEndpoint: String {
get {
return urls["LocationEndpoint"] as! String
}
}
}
这适用于Xcode 7.1和Swift 2.1。