把一个字符串变成plist - swift

时间:2015-01-06 14:11:38

标签: ios swift nsdictionary plist

看起来我可能是唯一一个尝试这个的人,或者它很容易,但我已经知道如何了!

网站请求返回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)

结果是带有xml标题的plist字符串和plist结构之后的数据。如果我使用

,则plist返回效果很好
NSDictionary(contentsOfURL: NSURL(string: path)!)!
但是,我发帖,而不是'得到'所以据我所知,我无法使用NSURL路径。

提前感谢!

2 个答案:

答案 0 :(得分:4)

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)
    }
}

答案 1 :(得分:0)

快捷键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)
    }
}