如何检索NSURLRequest的HTTPBody参数到字典:Swift中的[NSObject:AnyObject]

时间:2015-05-27 13:40:33

标签: ios swift dictionary afnetworking nsurlconnection

我正在尝试将NSURLRequest HTTPBodyNSData转换为Dictionary,以便访问其参数并运行检查。

 var parameters: [NSObject: AnyObject?] = [
            "method": "foo",
        ]
        var urlRequestString = "www.foobar.com/api/aMethod"
        var urlRequest = AFOAuth2Manager().requestSerializer.requestWithMethod("POST",
            URLString:urlRequestString ,
            parameters: postParameters,
            error: nil)

在另一种方法中,我尝试对上面构建的urlRequest进行检查,以确保NSURLRequest中的"method"包含正确的值"foo"

我需要的是将HTTPBody转换为Dictionary[NSObject: AnyObject])  这样我就可以检查"method"参数是否包含我需要的值。

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

试试这个:

func queryDictionaryForQueryString(query: String) -> Dictionary<String, String> {
    var dictionary = [String: String]()

    for keyValueString in query.componentsSeparatedByString("&") {
        var parts = keyValueString.componentsSeparatedByString("=")
        if parts.count < 2 { continue; }

        var key = parts[0].stringByRemovingPercentEncoding!
        var value = parts[1].stringByRemovingPercentEncoding!

        dictionary[key] = value
    }

    return dictionary
}

然后你可以

let httpBody = urlRequest.HTTPBody
let httpBodyString = NSString(data: httpBody!, encoding: NSUTF8StringEncoding) as! String
let queryDictionary = queryDictionaryForQueryString(httpBodyString)
println(queryDictionary["method"])

答案 1 :(得分:0)

这是我的更多Swifty 3.0 NSURL扩展,以实现这一目标,无需安全:

extension NSURL {

    var paramsDictionary: [String : String]? {

        guard let parameterString = parameterString else {
            return nil
        }

        var dictionary: [String : String] = [:]
        parameterString.components(separatedBy: "&").forEach {
            let componants = $0.components(separatedBy: "=")
            guard let name = componants[0].removingPercentEncoding, let value = componants[1].removingPercentEncoding else {
                return
            }
            dictionary[name] = value
        }
        return dictionary.isEmpty ? nil : dictionary
    }
}

var url = NSURL(string: "https://www.testWebSite.com/index.php;param=value&testParam=test&thingParam=thing")
let params = url?.paramsDictionary //results in "Optional(["thingParam": "thing", "testParam": "test", "param": "value"])"