Alamofire不允许直接发送对象

问题描述 投票:0回答:2

我的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()
}
ios swift alamofire
2个回答
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对象。


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)
}
© www.soinside.com 2019 - 2024. All rights reserved.