Afnetworking post array - objective-c

Im trying to post with an array as the post instead of a dictionary. However i get an error:
Incompatible pointer types sending NSMutableArray to parameter of type NSDictionary
Here is the code
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
How can I post JUST the arrays contents?
Update:
This code works, but I would prefer to get the answer below working as its cleaner and af handles the serialization. Im guessing the request body is different, but how do i see what the body is?
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.com/resources.json"]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];

I am assuming you want foo and bar to be your parameters without any values? if so you will want to do something like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:#[[NSNull null], [NSNull null]] forKeys:parameters];
[manager POST:#"http://example.com/resources.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT
Try adding
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

Related

Get Api is not working properly

i am working on get api when hit the api in app i am not getting updated response when i remove the app from simulator and device its working fine.guys what i am doing wrong please help me.i have already tried Afnetworking simple Api nsurl session.
NSString *strURL = [NSString stringWithFormat:#"https://mysponsers.com/m/comments/publicpost/674"];
NSURL *url = [NSURL URLWithString:strURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
[httpClient getPath:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"RESPONSE--->1%#",json);
} failure:^(AFHTTPRequestOperation* operation, NSError *error) {
//fail!
NSLog(#"Error String is %#", error.localizedDescription);
}];
Here is the code i am using afnetworkikng for hitting the api.
Thank You
You can try with latest version of AFNetworking library or you can simply use this code also.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://mysponsers.com/m/comments/publicpost/674"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
}
}];
[dataTask resume];
You can install or update AFNetworking via cocoapods by adding this (pod 'AFNetworking', '~> 3.1.0') in your pod file.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
// Change your api content-type here:
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
[manager GET:#"{ Write your url here }"
parameters:nil
progress:nil
success:^(NSURLSessionDataTask *operation, id responseObject) {
NSString *response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Success response: %#", response);
}
failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"Failure response: %#", response);
}];

Get plain response from AFNetworking 2.4.1

I'm sending a POST request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"method": #"login", #"email":#"email", #"password":#"password"};
[manager POST:#"http://www.apiwebsite.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
My responseObject is:
JSON: <0d0a7b22 72657370 6f6e7365 223a224f 4b222c22 30223a22 6d61696c
696e675f 6b657922 2c223122 3a226239 65653766 34643238 64333730
30666663 37393734 65376665 66626663 3136227d>
But calling the api with POSTMAN i get:
{"response":"OK", "id":"1234223123"}
How can I get the plain or JSON response to work with it?
thanks!
To get JSON object use proper serializer AFJSONResponseSerializer instead of AFHTTPResponseSerializer you uses now.
For debug purpose convert NSData to NSString
NSLog(#"JSON: %#", [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding]);

Creating dependencies between operations when using AFHTTPRequestOperation

I'm working with AFNetworking (2.4.1) in a mac application. I'm hoping to add my own block operation that is for after completion of all of the other operations (which are AFHTTPRequestOperation). I have tried adding dependencies between the completionOperation and the others, but the completionOperation block still executes before the others have completed with success or failure.
A cut down version of the code that illustrates the basics is below. Is anyone able to suggest how to make this work? Thanks.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"All operations complete");
}];
NSMutableURLRequest *request1 = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:[[NSURL URLWithString:#"https://api.parse.com/1/classes/SomeClass"] absoluteString] parameters:nil error:nil];
AFHTTPRequestOperation *operation1 = [manager HTTPRequestOperationWithRequest:request1 success:
^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"operation 1 success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"operation 1 failure");
}];
NSMutableURLRequest *request2 = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:[[NSURL URLWithString:#"https://api.parse.com/1/classes/OtherClass"] absoluteString] parameters:nil error:nil];
AFHTTPRequestOperation *operation2 = [manager HTTPRequestOperationWithRequest:request2 success:
^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"operation 2 success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"operation 2 failure");
}];
[completionOperation addDependency:operation1];
[completionOperation addDependency:operation2];
[manager.operationQueue addOperation:operation1];
[manager.operationQueue addOperation:operation2];
[manager.operationQueue addOperation:completionOperation];
- (void) test3:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
// block 1
NSString *string = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *urll = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:urll];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"OPERATION 1 %#",responseObject );
test_Sync = #"done";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
test_Sync = #"faile"; }];
//block 2
NSString *string2 = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *urll2 = [NSURL URLWithString:string2];
NSURLRequest *request2 = [NSURLRequest requestWithURL:urll2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject) {
// Print the response body in text
NSLog(#"Response: OPERATION 2 %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"Error: %#", error);
}];
// Add the operation to a queue
// It will start once added
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// Make operation2 depend on operation1
[operation addDependency:operation2];
[operationQueue addOperations:#[operation, operation2] waitUntilFinished:YES];
}

How to convert AFNetworking service invoke to use AFHTTPSessionManager

This is my current call to (asmx) SOAP web service:
NSString *soapMessage =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Save xmlns=\"http://www.myapp.com/\">"
"<par1>%i</par1>"
"<par2>%#</par2>"
"<par3>%#</par3>"
"</Save>"
"</soap:Body>"
"</soap:Envelope>", par1, par2, par3
];
NSURL *url = [NSURL URLWithString:#"http://....asmx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if([self.delegate respondsToSelector:#selector(myAppHTTPClientDelegate:didUpdateWithWeather:)]){
[self.delegate myAppHTTPClientDelegate:self didUpdateWithWeather:responseObject];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([self.delegate respondsToSelector:#selector(myAppHTTPClientDelegate:self:didFailWithError:)]){
[self.delegate myAppHTTPClientDelegate:self didFailWithError:error];
}
}];
[operation start];
But I need to change this to use AFHTTPSessionManager.
I suppose that I need to use this:
[operation POST:<#(NSString *)#> parameters:<#(id)#> constructingBodyWithBlock:<#^(id<AFMultipartFormData> formData)block#> success:<#^(NSURLSessionDataTask *task, id responseObject)success#> failure:<#^(NSURLSessionDataTask *task, NSError *error)failure#>]
But I am not clear about what parameters should I set?
UPDATE
NSDictionary *s_request = #{#"par1": [NSString stringWithFormat:#"%i", par1], #"par2": par2, #"par3": par3, #"par4": [NSString stringWithFormat:#"%i", par4], #"par5": par5};
AFHTTPSessionManager* s_manager = [[AFHTTPSessionManager alloc] init];
[s_manager POST:#"http://192.168.10.26/mywebservice/myservice.asmx?op=MethodName" parameters:s_request success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"DONE!");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"FAILED %#, %#", [error localizedDescription], [error localizedFailureReason]);
}];
This code always fail. Getting error 500. Do I just need to add method URL or I need to add complete soap message somewhere. What I miss here?
You need to pass parameter in Dictionary like in the following example:
NSDictionary *request = #{#"email": self.email.text, #"password": self.password.text};
[manager POST:login parameters:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"DONE!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed to log in: %#", operation.responseString);
}];

Trying to read html page from a web site using AFNetworking 2.0

I'm trying to have my app load an HTML web page into a "responseObject" that I can later parse.
Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/xhtml+xml"];
NSDictionary *parameters = #{#"ghinno": #"1151213"};
[manager GET:#"http://m.ghin.com/HLR.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTTP: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and this is the output. I should be seeing the html from the webpage. Can you help me understand what I am doing wrong?
Ah, the answer lies below...
Essentially, it was an encoding / decoding of the response object that was causing my issues. Here is the final solution: (notice the line beginning with "NSString)...
NSURL *URL = [NSURL URLWithString:#"http://m.ghin.com/HLR.aspx?ghinno=1151213"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[op start];