1

I was just playing with Alamofire framework and making few api calls. However I observed there are two request methods in alamofire :

public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request{...}

and

public func request(URLRequest: URLRequestConvertible) -> Request {...}

I found this really interesting, because the first method prototype is detailed and is easily understood. But the second one is quite confusing, I know that it takes a parameter which conforms to URLRequestConvertible protocol that is defined by Alamofire.

In the second request prototype the HTTP Method (GET or POST) that needs to be used is never specified, so how does the alamofire knows which HTTP method to be used. Is there a way to let alamofire know which http method to use while making request.

Also what are the other significant differences between these two methods (if any) and which one is preffered and why?

Thank you.

iamyogish
  • 2,372
  • 2
  • 23
  • 40

1 Answers1

1

The rendition of request without a method or parameters is presuming that you manually prepared the NSMutableURLRequest that includes the appropriate HTTPMethod, the HTTP headers (e.g. Content-Type, etc.), and HTTPBody.

You wouldn't generally use this rendition of the request method (we use Alamofire precisely to get us out of the weeds of manually constructing requests), but is useful when you have to construct a request that Alamofire cannot otherwise prepare (e.g. Sending json array via Alamofire).

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • thanks for a very clear answer. However, if we don't specify the HTTP method while using the second version of request method i.e. which accepts URLRequestConvertible as parameter. What happens then? For ex, if you look at the router class written in this link : http://www.raywenderlich.com/85080/beginning-alamofire-tutorial , the never specify the HTTP method while creating a request via. Router enum. – iamyogish Jul 21 '15 at 06:33
  • 1
    The default `HTTPMethod` for a `NSURLRequest` (or `NSMutableURLRequest`) is `GET`, so if unspecified, that's what used. Also, this `enum` uses `Alamofire.ParameterEncoding.URL` (consistent with `GET`). – Rob Jul 21 '15 at 12:10