post to server ,replace ASIFormDataRequest to AFnetworking - ios

i want to do a post request in afnetworking
this is my code whit ASI:
NSURL *mainurl = [NSURL URLWithString:#"xxxx/api/xxx/"];
ASIFormDataRequest *requestt = [ASIFormDataRequest requestWithURL:mainurl];
[requestt addPostValue:GETUnicidentifire forKey:#"UniqueId"];
[requestt addPostValue:JsonOrderDetail forKey:#"jsonProduct"];
[requestt addPostValue:BranchId forKey:#"BranchId"];
[requestt addPostValue:OrderToTime forKey:#"OrderToTime"];
[requestt setCompletionBlock:^{
// Process the response
}];
[requestt setFailedBlock:^{
NSError *error = [requestt error];
how can i do the same thong in AFnetworking ?

Not an exact answer, but here's a very similar POST request from my application:
-(void)setGpsLocation:(CLLocation*)location success:(TPScopeInterfaceSuccess)success failure:(TPScopeInterfaceFailure)failure
{
[_manager POST:#"gps/"
parameters:#{
#"lat":#(location.coordinate.latitude),
#"lon":#(location.coordinate.longitude),
#"height":#(location.altitude),
}
constructingBodyWithBlock:nil
success:success
failure:failure];
}
_manager is an instance of AFHTTPRequestOperationManager initialized as:
_manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.168.1.1/"]];

Related

Download one file at a time using afnetworking

I have an array which contains different URLs. I want to download one file with a progress bar, than start the next one and so on.
Here is my code that I have so far;
-(void) func:(NSArray *) arry
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 900;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSMutableArray * downloadedUrl = [[NSMutableArray alloc] init];
for (NSString * str in arry) {
NSURL *URL = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL (NSURL targetPath, NSURLResponse response) {
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
return [tmpDirURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse response, NSURL filePath, NSError *error) {
if(error)
{
NSLog(#"File Not Dowloaded %#",error);
}
}];
[downloadTask resume];
}
}
How would you download one file at a time with a progress bar and then remove the url from array?
Declare one global NSMutableArray of file and used that in the function like below.
-(void) downloadFile {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 900;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:[self.fileArr firstObject]]; //Here self.fileArr is your global mutable array
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL (NSURL targetPath, NSURLResponse response) {
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
return [tmpDirURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse response, NSURL filePath, NSError *error) {
if(error)
{
NSLog(#"File Not Dowloaded %#",error);
[self downloadFile];
}
else {
[self.fileArr removeObjectAtIndex:0];
if (self.fileArr.count > 0) {
[self downloadFile];
}
}
}];
[downloadTask resume];
}
Now call this function but before that initialize self.fileArr and after that call downloadFile method.
Hope this will help you.
Give limit the queue to one Operation at a time,
For that, Try to adding dependencies between each operation before you queue them.
If you add dependency between two operations say operation1 and operation2 before adding to queue then the operation2 will not start until operation1 is finished or cancelled.
Do it like:
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// Make operation2 depend on operation1
[operation2 addDependency:operation1];
[operationQueue addOperations:#[operation1, operation2, operation3] waitUntilFinished:NO];
UPDATE
// Create a http operation
NSURL *url = [NSURL URLWithString:#"http://yoururl"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
// Add the operation to a queue
// It will start once added
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperation:operation];
hope it help you..!

How send text to HTTP POST?

In my app I am using this code for sending parameters name, email, website url and comment in blog...Probably some value are wrong setting...Someone can help me solved? I'm going crazy!! Thanks in advance!
-(void)invia{
[self.connessione cancel];
NSURL *indirizzo = [NSURL URLWithString:#"http://*********ina.altervista.org/********/feed/"];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[indirizzo standardizedURL]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:#"POST"];
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSString *dati_postati=[NSString stringWithFormat:#"%#",parametri];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[dati_postati dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connessione = connection;
//start the connection
[connection start];
[self dismissViewControllerAnimated:YES completion:nil];
campoCommento.text=nil;
campoEmail.text=nil;
campoSito.text=nil;
campoNome.text=nil;
}
EDIT:
#Rich I've tried to read the API documentation for the web service, more precisely the part which concern "Create a Comment on a Post",I think my site ID concern the article is "gnutella"...I do not think there is a numeric id...from which I extract the id?
UPDATE:
I've extract Post ID from article...is 1757
I've tried with this URL without success
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/gnutella/1757/"];
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/gnutella/1757/replies/new"];
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/wp-admin/post.php?post=1757&action=edit"];
Another code method:
#define kSendCommentJSON #"?json=respond.submit_comment"
NSURL *completeURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://zenzeroincucina.altervista.org/gnutella/feed/"]];
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:completeURL];
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"" parameters:parametri constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Completed Successfullly");
//[self commentPostSuccess];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed misurable %#", [error description]);
//[self commentPostFailed];
}];
[operation start];
I've tried with this method...not yet!!
Console return successfully but text is not sent correctly...
Also tested on device(for exclusion a possible bug)...nothing!
You need to send the parameters correctly in the format key=value&key=value, not just as description of a NSDictionary.
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSMutableArray *values = [NSMutableArray new];
[parametri enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// Create an encoded parameter pair -> k=v
NSString *p = [NSString stringWithFormat:#"%#=%#", key, [[obj description] stringByAddingPercentEscapesUsingEncoding:NSUTF8Encoding]];
[values addObject:p];
}];
NSString *dati_postati = [values componentsJoinedByString:#"&"];
UPDATE:
So after looking at the POST request that is sent (on this page:
HTTP POST http://zenzeroincucina.altervista.org/wp-comments-post.php
Host: zenzeroincucina.altervista.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://zenzeroincucina.altervista.org/gnutella/
Cookie: __cfduid=d1ef25815caa898a777114c04c4d37bfc1398261681664; av_device_cookie=computer; av_mobile_cookie=desktop; PHPSESSID=b27e99a06qrkkd2lenppt9p1i6; __utma=178781179.1711693902.1398262580.1398262580.1398262580.1; __utmc=178781179; __utmz=178781179.1398262580.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 201
author=Test&email=test%40stack.com&url=stackoverflow.com&comment=Test&captcha_code=dw3P&submit=Submit+Comment&comment_post_ID=1757&comment_post_ID=1757&comment_parent=0&akismet_comment_nonce=f8393add8f
This doesn't massively help however as you need to include the captcha.
What you want to use is the WordPress API for posting comments. I played around with this but I don't have your site ID.
Try this out:
-(void)invia{
[self.connessione cancel];
NSString *param = [NSString stringWithFormat:#"url=%#&author=%#&email=%#&content=%#",campoSito.text,campoNome.text,campoEmail.text,campoCommento.text];
NSURL *indirizzo = [NSURL URLWithString:[NSString stringWithFormat:#"http://*********ina.altervista.org/********/feed?%#",param]];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[indirizzo standardizedURL]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:#"POST"];
NSString *dati_postati=[NSString stringWithFormat:#"%#",parametri];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[dati_postati dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connessione = connection;
//start the connection
[connection start];
[self dismissViewControllerAnimated:YES completion:nil];
campoCommento.text=nil;
campoEmail.text=nil;
campoSito.text=nil;
campoNome.text=nil;
}

ASIFormDataRequest POST Request Issue

im using this code to post data to my server
NSURL *mainurl = [NSURL URLWithString:#"http://xxxxxxxxxx/api/PhonePaymentApi/Transaction/"];
NSString * postdata = [[NSString alloc]initWithFormat:#"UniqueId=%#&jsonProduct=%#&BranchId=%#&OrderToTime=%#",GETUnicidentifire,JsonOrderDetail,BranchId,OrderToTime];
ASIFormDataRequest *requestt = [ASIFormDataRequest requestWithURL:mainurl];
[requestt setRequestMethod:#"POST"];
[requestt addRequestHeader:#"application/x-www-form-urlencoded" value:#"Content-Type"];
[requestt appendPostData:[postdata dataUsingEncoding:NSUTF8StringEncoding]];
NSString * theurl = [NSString stringWithFormat:#"%#",mainurl];
NSURLRequest *thereqest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:theurl]];
[NSURLConnection connectionWithRequest:thereqest delegate:self];
in the method
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"%#",error);
}
im geting:
{Message:The requested resource does not support http method 'GET'.}
what im doing Wrong ?
You are mixing things up here. You build an ASIFormDataRequest, but you don't actually send it. What you do send is an NSURLConnection.
It's been a long time since I've used ASI, but this might help:
NSURL *mainurl = [NSURL URLWithString:#"http://xxxxxxxxxx/api/PhonePaymentApi/Transaction/"];
ASIFormDataRequest *requestt = [ASIFormDataRequest requestWithURL:mainurl];
[requestt addPostValue:GETUnicidentifire forKey:#"UniqueId";
[requestt addPostValue:JsonOrderDetail forKey:#"jsonProduct";
[requestt addPostValue:BranchId forKey:#"BranchId";
[requestt addPostValue:OrderToTime forKey:#"OrderToTime";
[requestt setCompletionBlock:^{
// Process the response
}];
[requestt setFailedBlock:^{
NSError *error = [requestt error];
NSLog(#"%#",error);
}];
[requestt startAsynchronous];
As a word of advice, replace ASI with something like AFNetworking. ASI is no longer being developed.

AFNetworking - Upload video along with other parameters

I want to upload video to web service along with some other parameters. I want to upload userID, videoID and video to web service. While uploading, all the parameters other than video is being sent to web service. I've checked at web service end, and the video is not coming with the request. I am using the following code.
- (void)uploadVideoAtLocalPath:(NSString *)videoPath videoID:(NSString *)videoID userID:(NSString *)userID {
NSString *strServerURL = #"www.mysite.com/user/uploadVideo";
NSURL *URL = [NSURL URLWithString:strServerURL];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:URL];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// userID
NSData *userIDData = [userID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:userIDData name:#"userID"];
// videoID
NSData *videoIDData = [videoID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:videoIDData name:#"videoID"];
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
[request setURL:URL];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[AFHTTPRequestOperation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)]];
[operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response String: %#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[client enqueueHTTPRequestOperation:operation];
}
Could anyone let me know whether I am doing it correct? If not, could anyone please tell me how to upload video to web service along with other parameters?
Thanks Everyone!
I'm not well in this method. I had the same issue. But, i have fixed it like mixing of POST & GET methods. I just sent my parameters as GET method like below -
NSString *strServerURL = [NSString stringWithFormat:#"www.mysite.com/user/uploadVideo&userID=%d&videoID=%d", 1, 55];
and, sent my video data in POST method as per your method -
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
You better try to modify your webservice and try like above way. It should works.
Cheers!

Translating from ASIHTTPRequest to AFNetworking , on iOS

What i want to do is post a json file to my server. I finally did that using ASIHTTPRequest and my code is :
NSURL *url = [NSURL URLWithString:#"http://foo.foo.foo"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"PUT"];
[request addRequestHeader:#"Authorization" value:#"Basic dslfkdsfdsflsdkfslkgflksflksdlfkg"];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSLog(#"%#", [request responseString]);
What i need now is the exact above code translated to AFNetworking. Any ideas??
Thank you for reading my post :)
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://foo.foo.foo"]];
client.parameterEncoding = AFJSONParameterEncoding;
[client registerHTTPOperationClass:[AFJSONRequestionOperation class]];
[client setAuthorizationHeaderWithUsername:... password:...];
[client putPath:#"/path/to/resource" parameters:(_your JSON object as a dictionary_)
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", [request responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources