Alamofire不允许直接发送对象

时间:2019-04-30 10:02:28

标签: ios swift alamofire

我的API仅接受对象作为主体,而alamofire仅将Dictionary发送为对象,我的服务器不接受请求帮助

我必须使用alamofire调用一个API,它是一个后置api

当我将模型转换为字典并将字典转换为json时 并将其发布Alamofire不允许我发布字符串

它允许我发送我的api不接受的字典

["key":"value"]- Not acceptable
{"key":"value"}- Acceptable

任何人都可以分享任何解决方案吗?

我正在使用Swift 5,Xcode 10,Alamofire 4.8.2

do{
    let d  = try data.asDictionary()
    jsonString = DictionaryToJSON(data: dictionary)
} catch {
    print(error)
}
Alamofire.request(url, method: .post, parameters: jsonString, encoding: .utf8, headers: [: ]).responseJSON { (res) in
    print(res.result)
    print("Request Data \(res.request) \n Dictionary \(jsonString)")
    do {
        let d = try JSONDecoder().decode([OTPMessage].self, from: res.data!)
        print(d[0].message)
    } catch {
        print(error)
    }
}

// Dictionary to JSON

func DictionaryToJSON(data: [String:Any])->String {
    if let theJSONData = try? JSONSerialization.data(
        withJSONObject: data,
        options: .prettyPrinted
    ),
    let theJSONText = String(data: theJSONData, encoding: String.Encoding.ascii) {
        print("JSON string = \n\(theJSONText)")
        return theJSONText
    }
    else {
        return ""
    }
}

// Object to Dictionary

extension Encodable {
    func asDictionary() throws -> [String: Any] {
        let data = try JSONEncoder().encode(self)
        guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
            throw NSError()
        }
        return dictionary
    }
}

//Struct
struct OTPMessage:Codable {
    var message = String()
}

2 个答案:

答案 0 :(得分:0)

使用Alamofire,您无法执行此操作。您需要做的是创建一个URLRequest对象并设置其httpBody属性,然后将其传递给Alamofire。

URLRequest允许您将Data作为POST正文。

            var request = URLRequest(url: urlFinal)
            request.httpMethod = HTTPMethod.post.rawValue
            request.allHTTPHeaderFields = dictHeader
            request.timeoutInterval = 10
            request.httpBody = newPassword.data(using: String.Encoding.utf8)

            Alamofire.request(request).responseString { (response) in
                if response.response!.statusCode >= 200 && response.response!.statusCode <= 300 {
                    completion("success")
                }else {
                    completion("failed")
                }
            }

此处newPassword是字符串。从那里我创建了Data对象。您必须将Custom类对象转换为Data对象。

答案 1 :(得分:0)

您不必将字典转换为JSON字符串,因为Alamofire可以进行编码,请参见此example

我建议您将代码更改为类似的内容

do{
   let dictionary = try data.asDictionary()
   Alamofire.request(url, method: .post, parameters: dictionary, encoding: .JSON, headers: [:]).responseJSON { (res) in
        print(res.result)
        print("Request Data \(res.request) \n Dictionary \(jsonString)")
        do{
            let d = try JSONDecoder().decode([OTPMessage].self, from: res.data!)
            print(d[0].message)
        }catch{
            print(error)
        }
    }
} catch{
    print(error)
}