将字符串转换为 plist - swift

turn a string into plist - swift

看来我可能是唯一一个尝试此操作的人,或者它是如此简单,但我已经知道怎么做了!

网站请求 returns 一个 plist 响应,响应以字符串形式接收。然后如何将 plist "string" 放入字典中?

let url = NSURL(string: "http://...")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

let boundaryConstant = "----------V2ymHFg03esomerasdfsalfkjlksjdfy"
let contentType = "mulutipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = ""
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

let results = NSString(data: reply!, encoding: NSUTF8StringEncoding)

results 是一个带有 xml header 的 plist 字符串,数据遵循 plist 结构。如果我使用

,plist return 效果很好
NSDictionary(contentsOfURL: NSURL(string: path)!)!

但是,我是发帖,而不是 'getting',所以据我所知,我不能使用 NSURL 路径。

提前致谢!

NSPropertyListSerialization 是你的朋友,只要你真正取回 plist 数据:

if let plistData = results.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
    var format = NSPropertyListFormat.XMLFormat_v1_0
    let options = NSPropertyListMutabilityOptions.Immutable
    if let dict = NSPropertyListSerialization.propertyListWithData(plistData, 
                                      options: NSPropertyListReadOptions(options.rawValue),
                                       format: &format, 
                                        error: nil) as? NSDictionary {
        println(dict)
    }
}

Swift 5

if let plistData = results(using: String.Encoding.utf8, allowLossyConversion: true) {
    var format = PropertyListSerialization.PropertyListFormat.xml
    let options = PropertyListSerialization.MutabilityOptions.mutableContainers
    if let dict = try PropertyListSerialization.propertyList(from: plistData,
                                                          options: PropertyListSerialization.ReadOptions(rawValue: options.rawValue),
                                                   format: &format) as NSDictionary {
        print(dict)
    }
}