简体   繁体   English

打印 Alamofire 请求正文

[英]Print Alamofire request body

I'm using Alamofire library for connecting with an API in iOs.我正在使用 Alamofire 库来连接 iOs 中的 API。 I have a problem in one of the connection, and I don't know if it is because of the data encoded in the body or any other thing.我有一个连接有问题,我不知道是因为body中编码的数据还是其他任何东西。 In order to detect my error, I'm trying to print in the console the request body for checking if I'm sending the correct data structure.为了检测我的错误,我试图在控制台中打印请求正文以检查我是否发送了正确的数据结构。

My code is the following:我的代码如下:

func updateUser (#user: User, completionHandler: (responseObject: User?, error: AnyObject?) -> ()) {
    let parameters = [
        "_id": "\(user._id!)",
        "email": "\(user.email!)",
        "media": "\(Mapper().toJSONArray(user.media!))",
        "blogs": "\(Mapper().toJSONArray(user.blogs!))"
    ]

    var manager = Alamofire.Manager.sharedInstance
    manager.request(.PUT, apiUrl + "/route/to/api", parameters: parameters, encoding: .JSON)
        .responseObject{ (req: NSURLRequest, res: NSHTTPURLResponse?, user: User?, data: AnyObject?, error: NSError?) in
            if(error != nil) {
                NSLog("Error API updateUser: \(error)")
            }
            else {
                completionHandler(responseObject: user as User?, error: data)
            }
    }
}

User is a Mappable object, since I'm using ObjectMapper combined with Alamofire. User 是一个 Mappable 对象,因为我将 ObjectMapper 与 Alamofire 结合使用。 User is defined by the following code:用户由以下代码定义:

class User: Mappable {
   var _id: String?
   var name: String?
   var media: [Media]?

   init(_id: String, name: String, media: [Media]){
      self._id = _id;
      self.name = name;
      self.media = media
   }

   required init=(_ map: Map){
      mapping(map)
   }

   func mapping(map: Map){
      _id <- map["_id"]
      name <- map["name"]
      media <- map["media"]
   }
}

Media is defined like User, but with different variables.媒体的定义与用户类似,但具有不同的变量。

Also, I would like to know, in addition of printing request body, if I could include the parameters to Alimofire request in a more efficient way (something like parsing the User object and substituting it for the parameters variable)另外,我想知道,除了打印请求正文之外,是否可以以更有效的方式将参数包含到 Alimofire 请求中(例如解析 User 对象并将其替换为参数变量)

Any idea about my problems?知道我的问题吗?

EDIT:编辑:

Following the suggestion of @Travis, finally I found the solution for printing the request body.在@Travis 的建议下,终于找到了打印请求正文的解决方案。 Below you could find the code:您可以在下面找到代码:

println("request body: \(NSString(data:req.HTTPBody!, encoding:NSUTF8StringEncoding) as String?)")

About passing as parameters an object I couldn't work it, I followed the official documentation, but I could do it.关于将一个对象作为参数传递我无法工作,我遵循了官方文档,但我可以做到。

Swift 3+

print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))

The answer to your first question is,你第一个问题的答案是,

println("request body: \(request.HTTPBody)")

As far as your 2nd question goes, there's a whole section on API Parameter Abstraction as well as CRUD & Authorization on the Alamofire main page .就您的第二个问题而言, Alamofire 主页上有一整节关于 API 参数抽象以及 CRUD 和授权。

Added the below extension for the Request class for printing the logs.为用于打印日志的请求类添加了以下扩展。

extension Request {
    public func debugLog() -> Self {
        #if DEBUG
            debugPrint("=======================================")
            debugPrint(self)
            debugPrint("=======================================")
        #endif
        return self
    }
}

To use the extension, just use debugLog() after defining your request, like so:要使用扩展,只需在定义请求后使用 debugLog() ,如下所示:

Alamofire.request(url).debugLog()
            .responseJSON( completionHandler: { response in
   })

reference url : link参考网址: 链接

Just to turn it a bit easier.只是为了让它更容易一点。

    if let requestBody = request.request?.HTTPBody {
        do {
            let jsonArray = try NSJSONSerialization.JSONObjectWithData(requestBody, options: [])
            print("Array: \(jsonArray)")
        }
        catch {
            print("Error: \(error)")
        }
    }

斯威夫特 5

print(response.debugDescription)

For Swift 4 & Swift 5, just like that :对于 Swift 4 和 Swift 5,就像这样:

String(data: data!, encoding: String.Encoding.utf8)

If not in DefaultDataResponse extension or object, replace data with yourObject.response.data如果不在 DefaultDataResponse 扩展或对象中,用 yourObject.response.data 替换数据

From Alamofire documentation here https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output来自此处的 Alamofire 文档https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output

You can get curl request description您可以获得 curl 请求描述

AF.request("https://httpbin.org/get")
    .cURLDescription { description in
        print(description)
    }
    .responseDecodable(of: DecodableType.self) { response in
        debugPrint(response.metrics)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM