returns POST 请求的 Alamofire 路由器

Alamofire Router that returns POST request

阅读 RAYWENDERLICH Alamofire tutorial 后,我决定构建自己的路由器,除了一些细节外,它工作正常。它 returns GET 请求,但我需要 POST 请求。我花了一些时间尝试在 Router 中设置 HTTPMethod = "POST" 但可能是因为缺乏经验,我做错了并且出现了一些错误。那么我到底需要更改路由器什么才能使其成为 return POST 请求?

她是我的密码

enum Router: URLRequestConvertible
{
    static let baseURLString = "http://www.com"
    case Friends(Int)
    var URLRequest: NSURLRequest
    {
        let (path: String, parameters: [String: AnyObject]) = {
            switch self
            {
            case .Friends (let ID):
                let params = ["userID": "\(ID)"]
                return ("/getFriends.php", params) 
            }
        }()
        let URL = NSURL(string: Router.baseURLString)
        let URLRequest = NSURLRequest(URL: URL!.URLByAppendingPathComponent(path))
        let encoding = Alamofire.ParameterEncoding.URL
        return encoding.encode(URLRequest, parameters: parameters).0
    }
}

完美地遵循代码:)谢谢@Kaan Dedeoglu

  enum Router: URLRequestConvertible
  {
    static let baseURLString = "http://www.com"
    case Friends(Int)
    var URLRequest: NSURLRequest
      {
        let (path: String, parameters: [String: AnyObject]) = {
          switch self
          {
          case .Friends (let ID):
            let params = ["userID": "\(ID)"]
            return ("/getFriends.php", params)
          }
          }()
        let URL = NSURL(string: Router.baseURLString)
        let URLRequest = NSMutableURLRequest(URL: URL!.URLByAppendingPathComponent(path))
        URLRequest.HTTPMethod = "POST"
        let encoding = Alamofire.ParameterEncoding.URL
        return encoding.encode(URLRequest, parameters: parameters).0
    }
  }

简单的解决方案 swift 3+Alamofire 4+

import Foundation
import Alamofire

public enum mRouter: URLRequestConvertible {
  static let baseURLString = "baseURL"
  static let token = "token"

  case profile
  case timeline

  public func asURLRequest() throws -> URLRequest {
    var method: HTTPMethod {
      switch self {
      case .profile:
        return .get
      case .timeline:
        return .post
      }
    }

    let params: ([String: Any]?) = {
      switch self {
      case .profile(let Id):
        return (["id": Id])
      case .timeline:
        return nil
      }
    }()

    let url: URL = {
      let relativePath: String?
      switch self {
      case .profile:
        relativePath = "profile"
      case .timeline:
        relativePath = "timeline"
      }
      var url = URL(string: mRouter.baseURLString)!
      if let relativePath = relativePath {
        url = url.appendingPathComponent(relativePath)
      }
      return url
    }()

    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = method.rawValue
    urlRequest.setValue(mRouter.token, forHTTPHeaderField: "Authorization")

    let encoding = JSONEncoding.default
    return try encoding.encode(urlRequest, with: params)
  }
}