在Swift 3中从URLSession迁移到Alamofire 4.3,编码问题

时间:2017-02-20 09:01:30

标签: swift post alamofire

Alamofire 4.3Swift 3中的以下内容的等效代码是什么?

let baseUrl = "https://hiddenWebsite.com/api/index_load"
let url = URL(string: baseUrl)
let authObj = ["owner_id": "361900", "auth_key": "f408634ac1e14c08eebce46c34ab9db2", "device": "2", "version": "2.1.16"]
let infoObj = ["case": "feeds", "feeds_call_type": "init", "feed_type": "", "load_next_from": "1"]

let infoJSONData = try! JSONSerialization.data(withJSONObject: infoObj)
let infoStr = "info" + "=" + String(data: infoJSONData, encoding: String.Encoding.utf8)!

let authJSONData = try! JSONSerialization.data(withJSONObject: authObj)
let authStr = "auth" +  "=" + String(data: authJSONData, encoding: String.Encoding.utf8)!

let combinedStr = infoStr  +  "&" + authStr
let reqdat = combinedStr.data(using: String.Encoding.utf8)

var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = reqdat
let defaultSession = URLSession.shared
defaultSession.dataTask(
    with: request,
    completionHandler: { data, response, error in
        guard error == nil else {
            print("Error while fetching data: \(error)")
            return
        }
        guard let data = data,
            let json = try? JSONSerialization.jsonObject(
                with: data,
                options: JSONSerialization.ReadingOptions.mutableContainers)
            else {
                print("Nil data received")
                return
        }
        print(json)
}).resume()

我目前正在从Apple的URLSession迁移到Alamofire,但此时仍处于困境。我认为这与encodingParameter有关。 这是我失败的尝试。我也尝试过URLEncoding.httpbody,但没有工作。

    let baseUrl = "https://hiddenWebsite.com/api/index_load"
    let masterParameter = [
        "auth": ["owner_id": "361900",
                 "auth_key": "f408634ac1e14c08eebce46c34ab9db2",
                 "device": "2",
                 "version": "2.1.16"],
        "info": ["case": "feeds",
                 "feeds_call_type": "init",
                 "feed_type": "",
                 "load_next_from": "1"]
    ]
    Alamofire.request(baseUrl, method: .post, parameters: masterParameter, encoding: JSONEncoding.default).responseJSON { (response) in

        print(response)
    }

工作邮差等同于此 Postman Screenshot

2 个答案:

答案 0 :(得分:0)

您使用的编码无效JSON。因此,您不能使用masterParameter作为编码类型,因为它会将您的URLRequest字典编码为有效的JSON字典。

相反,您需要像在第一个示例中一样手动构建Alamofire.request(urlRequest)并使用URLRequest API,或者您可以创建自己的https://www.instituteforsupplymanagement.org/about/MediaRoom/newsreleasedetail.cfm?ItemNumber=30655数据然后编码floor(color / 16)*16

答案 1 :(得分:0)

感谢cnoon回答。以下代码解决了该问题:

public enum JSONError: Error {
    case serializing(String)
    case encoding
}

extension String: ParameterEncoding {
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = self.data(using: String.Encoding.utf8)
        return request
    }
}

let encodedStr = try getEncodedString(parameters: masterParameter)
Alamofire.request(baseUrl, method: .post, parameters: [:], encoding: encodedStr).responseJSON { response in
        print(response)
}

其中getEncodedString(parameters :)定义为:

func getEncodedString(parameters: Parameters) throws -> String {

        var encodedStr = ""
        for (key, value) in parameters {

            let jsonData: Data
            do {
                jsonData = try JSONSerialization.data(withJSONObject: value)
            }
            catch(let error) {
                throw JSONError.serializing(error.localizedDescription)
            }
            guard let encodedJsonString = String(data: jsonData, encoding: .utf8) else {
                throw JSONError.encoding
            }
            let keyValueStr = key + "=" + encodedJsonString
            encodedStr += keyValueStr + "&"
        }
        if encodedStr.characters.last == "&" {
            encodedStr.remove(at: encodedStr.index(before: encodedStr.endIndex))
        }

        return encodedStr
    }