Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching http request with query in Alamofire in Swift

I'm trying to fetch data from mLab service from my mongodb database. I can make the request successfully from browser and get data with code below.

https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp?q={"member_id":2}&apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI

I need to change "member_id" to \"member_id\" to not to get sytax error. The rest of is same. However, It doesn't fetch anything with Alamofire in Swift in iOS. (I also tried it without alamofire, with usual http request but still doesn't work)

If I try it without {"member_id":2} It is working. I'm doing fetching with below code (not working one);

Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp?q={\"member_id\":2}&apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI")

I also try to add parameters

   let parameters: Parameters = ["member_id": "3"]
Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp?q={\"member_id\":3}&apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))

This is the api document; http://docs.mlab.com/data-api/

Thank You

like image 905
Emre Önder Avatar asked Jan 20 '26 01:01

Emre Önder


1 Answers

Your request should look like that:

let parameters: Parameters = [
     "q": ["member_id": 2], 
     "apiKey": "2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI"
]
Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp", method: .get, parameters: parameters, encoding: URLEncoding.default)

It is more readable, and also you can easily change the parameters.

Hope it helps

like image 93
kamwysoc Avatar answered Jan 22 '26 15:01

kamwysoc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!