AFNetworking + AFJSONRequestOperation + Rails - ruby-on-rails

I'm using NSMutableURLRequest before using AFJSONOperationRequest and I have a problems getting the data in my Rails app.
If I use :
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
}];
Then :
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
else {
}
}
I get my data correctly formatted in the Rails logs:
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
But I don't need AFMultipartFormData to send a file... (no file to send)
So, instead, I use:
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict];
with my AFJSONRequestOperation too. But, my parameters are now not set correctly in my rails app:
Parameters: {contact[country_id] => "45", contact[lastname] => "Tutu"}
instead of
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
I don't understand why. It looks like the body of the request is not set correctly when I don't use the block: "constructingBodyWithBlock".

Don't use multipartFormRequestWithMethod.
Just use the postPath method like this
[[YourHTTPClient sharedClient] postPath:path
parameters:dict
success:^(AFHTTPRequestOperation *operation, NSString* path){
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Edit:
If you need an operation use AFJSONRequestOperation directly
+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
NSURL *url = [NSURL URLWithString:#"http://yoursite.com/path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];

Related

AFJSONRequestOperation : variable 'operation' is uninitialized when captured by block

I am getting the above warning in this code on line number 6 and the userInfo also becoming nil in the block.Please suggest something to remove this warning and userInfo issue.
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:operation.userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:operation.userInfo];
}];
operation.userInfo = userInfo;
[operation start];
Just use userInfo variable when you create operation, instead of calling operation.userInfo - which is not existing in a moment you are creating it.
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:userInfo];
}];
operation.userInfo = userInfo;
[operation start];
Another option is to set block later:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:nil failure:nil];
operation.userInfo = userInfo;
[operation setCompletionBlockWithSuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:userInfo];
}];
[operation start];

AFNetworking not getting proper response

I'm trying to use AFNetworking to call a Rest API but I'm not getting the proper response string. This is my code:
NSURL *url = [[NSURL alloc] initWithString:#"https://www.ez-point.com/api/v1/ezpoints"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#",#"testing");
NSLog(#"%#",operation.responseData);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
}];
[operation start];
but I'm getting this as print out:
2013-10-29 08:31:08.175 EZ-POINT[4004:c07] testing
2013-10-29 08:31:08.175 EZ-POINT[4004:c07] (null)
As you can see, it is returning null, I was expecting this:
{"status": "user_invalid", "data": "", "token": "", "errors": ["user not found"], "user_id": ""}
I'm more accustomed to this way of setting up the request:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.ez-point.com/api/v1/ezpoints"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#",#"testing");
NSLog(#"%#",operation.responseData);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
}];
[operation start];

AFNetworking, getting 401 with proper token

I'm making a request on https://www.ez-point.com/api/v1/ezpoints with a proper token using a Chrome Rest Client. I'm properly getting the result. However, when using AFNetworking, I'm getting a 401.
Here is my code snippet:
NSURL *url = [[NSURL alloc] initWithString:#"https://www.ez-point.com/api/v1/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url ];
[httpClient setAuthorizationHeaderWithToken:#"xxxxxxxxxx"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:#"/ezpoints" parameters:nil];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", #"success");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
Here is the error:
2013-10-29 08:51:38.908 EZ-POINT[4944:c07] I restkit:RKLog.m:34 RestKit logging initialized...
2013-10-29 08:51:39.189 EZ-POINT[4944:c07] I restkit.network:RKObjectRequestOperation.m:180 GET 'https://www.ez-point.com/ezpoints'
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] E restkit.network:RKObjectRequestOperation.m:209 GET 'https://www.ez-point.com/ezpoints' (401 Unauthorized) [2.7191 s]: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401" UserInfo=0x1052ef40 {AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest https://www.ez-point.com/ezpoints>, NSErrorFailingURLKey=https://www.ez-point.com/ezpoints, NSLocalizedDescription=Expected status code in (200-299), got 401, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xac54520>}
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] Error
Its working with the following code:
NSURL *url = [[NSURL alloc] initWithString:#"https://www.ez-point.com/api/v1/ezpoints"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:#"4f62fab9c91c46ad971cc2ae4a32bb6f" forHTTPHeaderField:#"Authorization"];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#",[JSON objectForKey:#"status"]);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
}];
[operation start];

How to add custom header to AFNetworking on a JSONRequestOperation

Hi, I have the following code accessing a URL:
NSString * stringURL = [NSString stringWithFormat:#"%#/%#/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
completionHandler(nil, error);
}];
But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.
Cant find it on AFNetworking documentation, should I change the operation type?
Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:#"X-USER-TOKEN" value:userToken];
You can check the documentation
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue: #"X-USER-TOKEN" forHTTPHeaderField:#"< clientToken >"];
[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Token token=\"%#\"", _userObj.oAuth] forHTTPHeaderField:#"Authorization"];
If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
[[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:#"X-Register"];

AFNetworking : Cancelled, No Request

Dumb question. I'm just pasting the example AFNetworking code in:
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:nil];
[operation start];
But, nothing happens. If I output operation to NSLog it looks like the request was cancelled:
<AFJSONRequestOperation: 0x81655f0, state: isExecuting, cancelled: NO request: <NSURLRequest https://gowalla.com/users/mattt.json>, response: (null)>
What am I doing wrong?
Your best bet would be to add a failure block and then inspect the variables provided in that
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", [error localizedDescription]);
}];
[operation start];

Resources