iOS | Alamofire,如何将原始 JSON 数据发送到正文

标签 ios swift xcode post alamofire

我有一个关于使用 Alamofire 向端点发送原始 JSON 的问题。

使用下面的代码

let request = AF.request("URL OF ENDPOINT", method: .post, parameters: ["FirstName" : "kwstas"], encoder: URLEncodedFormParameterEncoder(destination: .httpBody), headers: headers).responseJSON{ (response) in
                //Check the result from Alamofire's response and check if it's a success or a failure
                switch response.result {
                case .success(let value):
                    //Everything is fine, return the value in onNext
                    observer.onNext(value)
                    observer.onCompleted()
                case .failure(let error):
                    //Something went wrong, switch on the status code and return the error
                    switch response.response?.statusCode {
                    case 403:
                        observer.onError(ApiError.forbidden)
                    case 404:
                        observer.onError(ApiError.notFound)
                    case 409:
                        observer.onError(ApiError.conflict)
                    case 500:
                        observer.onError(ApiError.internalServerError)
                    default:
                        observer.onError(error)
                    }
                }
            }

至少我得到一个失败信息,即端点需要更多值(它确实如此)

但是使用其他任何东西而不是编码器 URLEncodedFormParameterEncoder(destination: .httpBody) (例如 JSONEncoder.default),请求甚至不会返回响应(成功或失败)。

问题是,我有一个接收多个值( int 、 string 、对象数组)的字典,当我将字典(类型为 String : Any )传递给参数时,我收到一个错误,协议(protocol)为“Any” ' 因为类型不能符合 'Encodable'。

任何答案将不胜感激

最佳答案

也许你想要这样的东西:

        var memberJson : String = ""
    do{
        let jsonEncoder = JSONEncoder()
        let jsonData = try jsonEncoder.encode(yourJson)
        memberJson = String(data: jsonData, encoding: String.Encoding.utf8)!
    
        
    }catch{}

    var request = URLRequest(url: URL(string: "url here")
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = (memberJson).data(using: .unicode)
    AF.request(request).responseJSON{response in }

关于iOS | Alamofire,如何将原始 JSON 数据发送到正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71558273/

相关文章:

xcode - 为什么 switch 语句中的 'case' 是负缩进的?

ios - 点击 UITextField 时更改键盘动画持续时间

IOS7 - SLComposeViewController - 包括链接/图像?

swift - 根据tableView中的附件创建条件语句

iphone - 应用程序未通过代码设计验证

ios - 设置 UIStoryboardSegue 子类的属性 [模态 segue 上的可选动画]

objective-c - 如何将现有的 XCode (4.5) 项目添加到 BitBucket

ios - 未调用可达性通知。使用 tonymillion/可达性

iOS - 如何创建条纹图像?

ios - Xcode 9 中的 Swift 4 - 读取核心数据中的数据失败