I need to serialize a Request with some default headers and an authentication token. With AFNetworking, I would create a subclass of AFJSONRequestSerializer. What can I do in Alamofire? I've read about response serializers but not request serializers.
Thanks.
In alamofire you just need to specify the headers you need before creating the request.
Something like this should work:
var authenticatedHeaders = ["Authorization": token, "otherHeader": otherHeader]
let request = Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding, headers: headers)
If your parameters need to be encoded as JSON, you just need to specify the encoding to .JSON(the default value is .URL).
If your request is supposed to return a JSON you can then trigger it using:
request.responseJSON { (response) -> Void in
// parsing the response here
}
If you need help to parse the response, you can take a look at my alamofire fork, where I implemented a wrapper for the networking framework so that it can be used in Objective-C Alamofire Objective-c wrapper GitHub and this complete walkthrough the changes.
Let me know if you need more information or help with this.
Related
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
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
I'm working online with different people from different projects who take care of backend API webservice. Usually I don't have problems with sending and receiving JSON, but this time, I can't seem to be able to send JSON properly to the server.
Usually I use Alamofire to receive and send JSON message, and the usual call go like this:
let param = populateParamWithDictionary();
let url = "https://www.example.com";
Alamofire.request(.POST, url, parameters: param, headers: nil)
.responseJSON { response in {
// take care of response here
}
But this time, I got project which the backend programmer requires me to use OAuth v2. So, let's say I've develop a function which already take care of getting the access_token string. The function now become like this:
let param = populateParamWithDictionary();
let url = "https://www.example.com";
let headers : Dictionary<String, String> = [
"Content-Type":"application/json",
"Authorization":"Bearer \(access_token)"
];
Alamofire.request(.POST, url, parameters: param, headers: headers)
.responseJSON { response in {
// take care of response here
}
But instead of the result, I get 400 bad request error. I also even try this:
let param = populateParamWithDictionary();
let url = "https://www.example.com";
let headers : Dictionary<String, String> = [
"Content-Type":"application/json",
"Authorization":"Bearer \(access_token)"
];
Alamofire.request(.POST, url, parameters: param, encoding: ParameterEncoding.JSON, headers: headers)
.responseJSON { response in {
// take care of response here
}
But the result is even worse. This is what I get when I print the response.
FAILURE: Error Domain=NSURLErrorDomain Code=-1017 "cannot parse
response" UserInfo={NSUnderlyingError=0x7fbb505788f0 {Error
Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)"
UserInfo={_kCFStreamErrorCodeKey=-1, _kCFStreamErrorDomainKey=4}},
NSErrorFailingURLStringKey=http://lfapp.learnflux.net/v1/me,
NSErrorFailingURLKey=http://lfapp.learnflux.net/v1/me,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response}
But the request works if I use REST client, by setting the headers to have the authentication and Content-Type, and have the parameters to be written as plain Content, e.g. in plain API in the body content.
How can I fix this?
EDIT: The part with the access token is already clear. The access token works. I can call an API successfully if the API doesn't requires any parameters (maybe because on the server, the code doesn't bother to even check or validate the body at all because it doesn't need anything from there, hence no error raised). The problem is when I make a request which needs any parameters.
The error you have is probably because of encoding: ParameterEncoding.JSON in the request. Try to change it to encoding: .URLEncodedInURL. If this doesn't help you, do add your parameters to the question and if you´re make a request to get the token do the following:
if let access_token = json["access_token"]!{
// Make the request here when you know that you have your token
}
I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.
My base url: http://myofficeit.in/bizfeed/webservices/client.php
Parameter I wanna Pass:
Parameter =
{
UserName = xyz;
deviceModel = iPhone;
deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
emailid = "xyz#gmail.com";
location = Asia;
userMobileNo = 1234567890;
};
functionName = register;
The code I used for hitting the service is: http://pastebin.com/aaT4uhS7
Thanks
you can use like
let param: [String:AnyObject] = [
"UserName": iPhone,
"deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
"emailid": "xyz#gmail.com",
"location": Asia,
"userMobileNo": 1234567890
]
Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
print(req)
print(res)
print(json)
print(error)
}
for sample request in Alamofire
As broad as your question is, the broad will be my answer:
The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.
You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.
Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.
According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.
How this eventually looks like is given in the answer of #AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.
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.
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).
I have an array of JSON objects that I would like to pass into the request body of a POST request to our server. However the method signature for the request method only takes a dictionary as its parameters:
func request(method: Alamofire.Method, _ URLString: URLStringConvertible, parameters: [String : AnyObject]? = default, encoding: Alamofire.ParameterEncoding = default, headers: [String : String]? = default) -> Alamofire.Request
Is there a way to currently do this in Alamofire without creating the NSURLRequest yourself? Or is it in the plan for future development?
You will need to use the .Custom parameter encoding to do this or manually create the NSURLRequest yourself. Another possible option would be to modify the server to accept the array with a parameter name in the JSON.
As of right now, there are no plans to support this feature, but thank you for making us aware of this limitation. I have added the issue to our internal Trello board and we will discuss whether we would like to support this in the future.