Alamofire 4 URL请求参数编码为JSON

时间:2016-10-05 06:53:53

标签: ios json swift alamofire

最近升级到Alamofire 4并遇到了一些问题。想知道如何在Alamofire路由器中将url请求参数编码为JSON。这是我在Alamofire 3中关注的例子。

enum UserRouter: URLRequestConvertible {
  static let baseURLString = "http://jsonplaceholder.typicode.com/"

  case Get(Int)
  case Create([String: AnyObject])
  case Delete(Int)

  var URLRequest: NSMutableURLRequest {
    var method: Alamofire.Method {
      switch self {
      case .Get:
        return .GET
      case .Create:
        return .POST

      }
    }

    let params: ([String: AnyObject]?) = {
      switch self {
      case .Get:
        return (nil)
      case .Create(let newPost):
        return (newPost)
      }
    }()

    let url:NSURL = {
      let relativePath:String?
      switch self {
      case .Get(let postNumber):
        relativePath = "posts/\(postNumber)"
      case .Create:
        relativePath = "posts"
      }

      var URL = NSURL(string: PostRouter.baseURLString)!
      if let relativePath = relativePath {
        URL = URL.URLByAppendingPathComponent(relativePath)
      }
      return URL
    }()

    let URLRequest = NSMutableURLRequest(URL: url)

    let encoding = Alamofire.ParameterEncoding.JSON
    let (encodedRequest, _) = encoding.encode(URLRequest, parameters: params)

    encodedRequest.HTTPMethod = method.rawValue

    return encodedRequest
  }
}

现在似乎在Alamofire 4中已经改变了。

let encoding = Alamofire.ParameterEncoding.JSON
let (encodedRequest, _) = encoding.encode(URLRequest, parameters: params)

以下是我正在尝试使用Alamofire 4路由器,但没有按预期工作。

func asURLRequest() throws -> URLRequest {
        let url = try UserRouter.baseURLString.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue


        switch self {
            case .updateDeviceToken(_,let device):
                urlRequest =  try ParameterEncoding.encode(urlRequest as URLRequestConvertible, with: device)
                //urlRequest = try  JSONEncoding.default.encode(urlRequest, with: device)
            case .addUser(_, let user):
                urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
            case .updateUser(_,_,let user):
                urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
            case .lockUser(_,_,let user):
                urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
            default:
                break
        }
        return urlRequest

1 个答案:

答案 0 :(得分:17)

我使用这种编码语法:

...
method: .get,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil,
...

在你的情况下,它可能是这样的:

let encoding = Alamofire.JSONEncoding.default

我也在努力解决这个问题,直到我在这里找到一个简单的例子:

https://github.com/Alamofire/Alamofire#json-encoding