返回POST请求的Alamofire路由器

时间:2015-06-03 22:13:40

标签: ios swift post alamofire

阅读 RAYWENDERLICH Alamofire tutorial 后,我决定建立自己的路由器,除了一些细节之外它工作得很好。它会返回GET个请求,但在我的情况下我需要POST个请求。我花了一些时间尝试在路由器中设置HTTPMethod = "POST",但可能是因为缺乏经验我做错了并且遇到了一些错误。那么我究竟需要在路由器中进行哪些更改以使其返回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
    }
}

2 个答案:

答案 0 :(得分:2)

使用 swift 3 + Alamofire 4 +

简单解决方案

Handler mHandler= new Handler()
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do your stuff here, called every second
        mHandler.postDelayed(this, 1000);
    }
};

// start it with:
mHandler.post(runnable);

答案 1 :(得分:1)

完全遵循代码:)谢谢@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
    }
  }