AFNetworking AFHTTPRequestOperation responseObject convert to NSXMLParser. The parser doesn't contain the all http information - nsxmlparser

I have a problem about AFNetworking to get HTML web page.
I had a url:
NSString *url = #"http://www.w3schools.com/";
Also I had a method:
- (void)AFNReturnXMLString:(NSString *)string{
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Make sure to set the responseSerializer correctly
op.responseSerializer = [AFXMLParserResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Get XMLParser Object
NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
[XMLParser setShouldProcessNamespaces:YES];
NSLog(#"%#", XMLParser);
// Leave these commented for now (you first need to add the delegate methods)
XMLParser.delegate = self;
[XMLParser parse];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error Fucking: %#", error);
}];
[op start];}
I have already use the NSXMLParser delegate. When I ran the method, the variable "qName" only shows the root <html> and <head> tag, but does not show <body> and <body>'s sub node.
Also I used the following method in the block instead of NSXMLParser object:
// Get HTML String
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
The string shows all the pages content.
Do anyone meet such the problem before?

Related

json parsing of multiple url, one after another in sequence or where to write another function calling in JSONRequestOperationWithRequest

I have parsed json. The result of json stored in array which contain list of video ID.
Now I want to parse another json which retrieve detail of video and this json will be parsed in loop videoIDArray.count times
Here is code:
- (void)viewDidLoad
{
[super viewDidLoad];
videoIDArray = [[NSMutableArray alloc] init];
viewArray = [[NSMutableArray alloc] init];
//======Json Parsing
NSString *urlstring = [NSString stringWithFormat:#"https://myURL/youtubeList"];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *Request = [NSURLRequest requestWithURL:url];
conn = [[NSURLConnection alloc] initWithRequest:Request delegate:self];
if (conn) {
webdata = [[NSMutableData alloc] init];
}
//==========
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (connection==conn) {
[webdata setLength:0];
}
if (connection==conn2) {
[webdata2 setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connection==conn) {
[webdata appendData:data];
}
if (connection==conn2) {
[webdata2 appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//-------conn getting list of videoID
if (connection == conn) {
NSString *str = [[NSString alloc] initWithBytes:[webdata bytes] length:[webdata length] encoding:NSUTF8StringEncoding];
NSDictionary *Result = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
[videoIDArray addObjectsFromArray:[[[Result valueForKey:#"items"] valueForKey:#"id"] valueForKey:#"videoId"]];
NSLog(#"Video ID %#",videoIDArray);
//======conn2 is for getting detail of video base on videoID object
for (int i=0; i<videoIDArray.count; i++) {
NSString *urlstring = [NSString stringWithFormat:#"https://mydetailURL/videos/%#?v=2&alt=json",[videoIDArray objectAtIndex:i]];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *Request = [NSURLRequest requestWithURL:url];
conn2 = [[NSURLConnection alloc] initWithRequest:Request delegate:self];
if (conn2) {
webdata2 = [[NSMutableData alloc] init];
}
}
//==========
}
if (connection==conn2) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
[youtubeTableView reloadData];
NSString *str = [[NSString alloc] initWithBytes:[webdata bytes] length:[webdata length] encoding:NSUTF8StringEncoding];
NSDictionary *Result = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSLog(#"ResultConn2 %#",Result);
[viewArray addObject:[[[Result valueForKey:#"entry"] valueForKey:#"yt$statistics"] valueForKey:#"viewCount"]];
NSLog(#"View Array %#",viewArray);
}
}
Problem is: it is not parsing as many times as in loop, only for last one connectionDidFinishLoading method called and crashed..
Can somebody tell me how to do this?
Is there any other way to do this?
EDIT
With AFNetworking
i changed my code like:
for (int i=0; i<videoArray.count; i++) {
[self parseWithUrl:[videoArray objectAtIndex:i]];
}
-(void)parseWithUrl: (NSString *)urlstr
{
NSString *tstr=[urlstr stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://myURL/feeds/api/videos/%#?v=2&alt=json",tstr]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//instead of NSLog i want to return result
NSDictionary *result = (NSDictionary *)JSON;
NSLog(#"VideoResult %#",result);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}];
[operation start];
}
I want to write:
-(NSDictionary *)parseWithUrl: (NSString *)urlstr
Is it possible?
if Yes then suggest me where i should return result?
if i want to call another method after completing json then where to write call code
here is my code:
[self getData:self.weather];
my method called number of times which i don't want.
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.weather = (NSDictionary *)JSON;
[self getData:self.weather];
.....
.....
}
Your issue stems from the fact that each of these NSURLConnection connections run asynchronously and therefore you're running many requests concurrently, but your routine is using a single webData2, so your requests are tripping over each other.
If you want to stay with your current design, rather than having a for loop where you initiate all of the second set of requests, you should only request the first one. And then have the connectionDidFinishLoading for the second type of request initiate the next one. (You could manage this "next" process by keeping track of some numeric index indicating which request you're processing, incrementing it each time.)
But you ask how to do these requests sequentially, one after another. Is there any reason why you cannot do them concurrently (more accurately, when first request is done, then issue the detail requests for the individual videos concurrently). In that scenario, even better than the clumsy fix I outlined in the prior paragraph, a more logical solution is an NSOperation-based implementation that:
Uses a separate object for each connection so the individual requests don't interfere with each other;
Enjoys the concurrency of NSURLConnection, but constrains the number of concurrent requests to some reasonable number ... you will yield significant performance benefits by using concurrent requests; and
Is cancelable in case the user dismisses the view controller while all of these requests are in progress and you want to cancel the network requests.
If you're already familiar writing NSURLConnectionDataDelegate based code, wrapping that in an NSOperation is not much worse. (See Defining a Custom Operation Object in the Concurrency Programming Guide.) We can walk you through the steps to do that, but frankly much easier is to use AFNetworking. They've done the complicated stuff for you.
In your edit to your question, you ask whether it is possible to write:
- (NSDictionary *)parseWithUrl: (NSString *)urlstr
While it's technically possible to, you never want a method on the main queue waiting synchronously for a network request. If parseWithURL cannot do what it needs to do inside the success block of the AFNetworking call (e.g. you might initiate a [self.tableView reloadData] or whatever is needed for your UI), then have parseWithURL return the dictionary in a completion handler of its own, e.g.:
- (void)parseWithURL: (NSString *)urlstr completion:(void (^)(NSDictionary *))completion
{
...
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completion(JSON); // call the completion block here
} failure:...];
}
Finally I am done parsing synchronous multiple json parsing with help of AFNetworking
Success of json parsing call another method in AFNetworking done by: link
Here is Code:
- (void)getResponse:(void (^)(id result, NSError *error))block {
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success
block(JSON,nil); //call block here
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}];
// 5
[operation start];
}
calling will be:
[self getResponse:^(id result, NSError *error) {
//use result here
}];

How to wait response and parse XML done in afnetworking iOS

I want to wait until server reponse and parse XML done, then call another function. How can i do that? I used this code to send request to server and use NSXMLParser to parse XML response.
NSURL *url1 = [NSURL URLWithString:#"linkserver"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
NSDictionary *params1 = #{
#"a" : vd;
#"b" : #"all"
};
NSMutableURLRequest *afRequest = [httpClient requestWithMethod:#"GET" path:nil parameters:params1] ;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
[self parseXMLFile:parsexmlinput];// parse xml
[self getItemFromStatus];// wait to call another function at here???
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
Please give me any suggestion. Thanks much
You have to make your request synchronous.
refer code something like:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friends/ids.json?"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
check this tutorial Ray Wenderlich using AFnetworking.
Using blocks and callbacks
- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}
You can do it in synchronous way...
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:[url path] parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if(error) {
errorCallback(error, nil);
} else {
//parse the xml here
}
OR
You can achive it by adding [operation waitUntilFinished],after it's added to the operation queue.Refer this==>Can AFNetworking return data synchronously (inside a block)?
OR
EDIT: In case you don't want to use the AFNetworking library.I prefer this way.
NSString *action_Post =[[NSString alloc] initWithFormat:#"authToken=%#",theMutableString];
NSURL *action_Url =[NSURL URLWithString:#"ur url here"];
NSData *action_PostData = [action_Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *action_postLength = [NSString stringWithFormat:#"%d", [action_PostData length]];//your parameter to be posted here
NSMutableURLRequest *action_Request = [[NSMutableURLRequest alloc] init];
[action_Request setURL:action_Url];
[action_Request setHTTPMethod:#"POST"];
[action_Request setValue:action_postLength forHTTPHeaderField:#"Content-Length"];
[action_Request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[action_Request setHTTPBody:action_PostData];
NSURLResponse *action_response;
NSData *action_Result = [NSURLConnection sendSynchronousRequest:action_Request returningResponse:&action_response error:&error];
if (!action_Result)
{
NSLog(#"Error");
}
else
{
//Parse your xml here
//call ur function
}
Modify it according to your GET/PUT methods.But i suggest you to go for POST method,as it is refered to be as secured one.

How to avoid delay of webservice(ASIHTTPRequest) response in iPhone?

In my iPhone app handling web service for storing and retrieving data.Now i am using the following code for web service handling.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"1" forKey:#"id"];
[request setTag:100];
[request setDelegate:self];
[request startAsynchronous];
By this code i got response in 'requestFinished' method.My problem is web service response is very delay(depends upon internet speed).How to make response from web service very fast?Please help me.
I think you want to send json objects by post method..delay is depend on your server(how fast it handle request and response back) but i suggest you to use progress bar and blocks to handle network request..
loadingHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
loadingHUD.labelText = NSLocalizedString(#"Downloading", nil);
loadingHUD.mode=MBProgressHUDModeAnnularDeterminate;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
// Add your filename to the directory to create your saved file location
NSString* destPath = [documentDirectory stringByAppendingPathComponent:[fileName stringByAppendingString:#".mov"]];
NSURL *url = [NSURL URLWithString:mainURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:postURL parameters:postRequest];
NSLog(#"postRequest: %#", postRequest);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:destPath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Successfully downloaded file to %#",[[NSString alloc] initWithData:operation.responseData encoding:NSASCIIStringEncoding]);
// Give alert that downloading successful.
NSLog(#"Successfully downloaded file to %#", destPath);
NSLog(#"response: %#", operation.responseString); // Give alert that downloading successful.
// [self.target parserDidDownloadItem:destPath];
loadingHUD.detailsLabelText = [NSString stringWithFormat:#"%# %i%%",#"Downloading",100];
[loadingHUD hide:TRUE];
[DBHelper savePurchaseId:fileName];
[self movieReceived];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// Give alert that downloading failed
NSLog(#"Error: %#", error);
// [self.target parserDidFailToDownloadItem:error];
[loadingHUD hide:TRUE];
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
// Progress
progress = ((float)totalBytesWritten) / fileSize;
loadingHUD.progress = progress;
}];
[operation start];
}
We cant control the internet speed due to the different network provider or environment when the client is using your app.
But you can put your web-services to run in background without effecting your main function.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code for webservices calling
dispatch_async(dispatch_get_main_queue(), ^{
//functions after your webservices done, for example reload the table or hide the loading bar.
});
});

Asynchronously getting data instead of using initWithContentsOfURL

I am currently using this code to get data from a URL:
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];
I was wondering how I could gather this data asynchronously so that my app does not freeze everytime I need to execute this. Thanks!
The simplest way is available in os5 like this:
NSString *stringfromFB;
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
stringfromFB = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]; // note the retain count here.
} else {
// handle error
}
}];
If you're stuck in os<5 for some reason, you'll need to start your connection with a delegate, and implement the delegate protocol as illustrated here (and many places elsewhere).
You can do it with GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url]
});
// Do not alloc init URL obj. for local use.
NSString *urlString = #"put your url string here";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above delegate methods are of NSURLConnectionDelegate, where you need to handle all things like response error etc.. It is by default provided so we can directly override it without
I have use once in my project It will work for async request but If you received number of images as well then also use IconDownloader or EGOImageView which implements the lazy loading of image and make much low chances of freezing of app.
if you don’t want to wait for a connection to complete loading a url, you can load it asynchronously using NSURLConnection.
[NSURLConnection connectionWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:yourUrlString]]
delegate:self];
Now that NSURLConnection is deprecated you need to use NSURLSession.
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == STATUS_OK) {
// use data
}
else {
NSLog(#"Network Session Error: %#", [networkError localizedFailureReason]);
}
}];
[task resume];

AFNetworking POST to REST webservice

Brief backstory, our previous developer used ASIHTTPRequest to make POST requests and retrieve data from our webservice. For reasons unknown this portion of our app stopped working. Seemed like good enough time to future proof and go with AFNetworking. REST webservice runs on the CakePHP framework.
In short I am not receiving the request response string using AFNetworking.
I know the webservice works because I am able to successfully post data and receive the proper response using curl:
curl -d "data[Model][field0]=field0value&data[Model][field1]=field1value" https://example.com/api/class/function.plist
Per the previous developer's instructions I came up with the following.
#import "AFHTTPRequestOperation.h"
…
- (IBAction)loginButtonPressed {
NSURL *url = [NSURL URLWithString:#"https://example.com/api/class/function.plist"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[usernameTextField text] forHTTPHeaderField:#"data[User][email]"];
[request setValue:[passwordTextField text] forHTTPHeaderField:#"data[User][password]"];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(#"response string: %# ", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
}];
[operation start];
}
output:
operation hasAcceptableStatusCode: 200
response string: a blank plist file
attempted solution 1:
AFNetworking Post Request
the proposed solution uses a function of AFHTTPRequestOperation called operationWithRequest. However, when I attempt to use said solution I get a warning "Class method '+operationWithRequest:completion:' not found (return type defaults to 'id'"
attempted solution 2: NSURLConnection. output: I'm able to print the success log messaged but not the response string.
*update - returns blank plist.
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = #"data[User][email]=username#example.com&data[User][password]=awesomepassword";
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
// *update - returns blank plist
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData %#",str);
if (error == nil && response.statusCode == 200) {
// Process response
NSLog(#"success");//returns success code of 200 but blank
NSLog(#"resp %#", response );
} else {
// Process error
NSLog(#"error");
}
These are the essential (stripping out conditions I've made for my own use) lines that ended up satisfying my request to the web service. Thanks for the suggestions #8vius and #mattt !
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"https://www.example.com/api/class"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"https://www.example.com/api/class/function" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Use AFHTTPClient -postPath:parameters:success:failure:, passing your parameters (nested dictionaries/arrays are fine). If you're expecting a plist back, be sure to have the client register AFPropertyListRequestOperation.
In any case, setValue:forHTTPHeaderField: is not what you want here. HTTP headers are for specifying information about the request itself; data is part of the request body. AFHTTPClient automatically converts parameters into either a query string for GET requests or an HTTP body for POST, et al.