HTTP Parameters in Alamofire

In this lesson

Let’s have a quick talk about how to add parameters to an Alamofire request and the available encodings for them so you know what use for the API that you are working with.

Kyle Roberts
Swift Guru at Large

Kyle's Series

Transcript

Tap on time to skip ahead

0:11

Hello world, Kyle here and we’re going to talk about the argument of the Alamofire request initialization method request: parameters. And in the method definition of this request method, the type of parameters is actually a Swift dictionary, which expects a string key with an any object type corresponding value to that key. And most of the parameters I’m using here in SteamReader, which is in, of course the NetworkInterface.swift file are pretty simple. 

0:44

Here is the most complicated one that I’m using which is actually fetching the news items for an app when you’re in SteamReader. And within this parameters dictionary I am requesting the news items for an app ID and passing in the corresponding app ID for the app that’s open, passing in a desired maximum count of ten, and passing in my API key with the string key of key. That’s like a keychain! But that’s how easy it is to define parameters. 

1:19

The parameter argument here actually has a default value so it’s not required to be included when you are calling this request method but if you do have any parameters to include then you do have to, you know, define them. Another parameter you might have noticed when we were in the method definition of the request function here is the encoding argument, which is of type ParameterEncoding, which is a custom Alamofire type. But we can and that argument like so and type in ParameterEncoding. and view some of the available options. The default value is .URL, which means that your parameters will actually be encoded into the end of the URL here automatically when this request is made. 

2:07

But the other options we saw our URLEncodedInURL which is another option I have not used so I’m not entirely sure what it is. You can also use JSON, which is probably good when you’re uploading an object of data and maybe an array of data and the API is expecting you to send it some JSON, you can use that. PList is another option. Not sure how common that is but it’s great that there’s support. And there’s even an ability to upload custom objects, actually passing in a request in the dictionary of parameters, and this is when you define your custom type, and making sure that it returns the modified request which you customly modify yourself when you define that special encoding. And since we’re just using the default of .URLEncoding, we don’t even need to include this value but if your parameters are indeed needing to be in, probably the second most common form, is JSON, then you will need to add that encoding there. 

Additional Info

Register to get access to additional resources and info.