Log ASIFormDataRequest body as NSString - objective-c

I'm making a multipart request to server using ASIFormDataRequest, and I want to review the post body myself before the request is actually made. Is there any way I can print it to console or something like that?

Turned out that I just needed to
#define DEBUG_FORM_DATA_REQUEST 1
After that, the library logs all post body to console (except for binary data, which is truncated).

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setStartedBlock:^{
NSLog(#"setStartedBlock", request.requestHeaders);
}];
...
[request startAsynchronous];
The StartedBlock is the very last callback before the connection is actually made to the server.
You can log your entire header using what I posted or if you want just the post data you can use the NSLog james had.

You can try:
NSLog(#"%#", dataRequest.postData);
If you can include some code it would be helpful.

I can't comment answers right now so I'll create an answer:
As James Paolantonio said, you can NSLog dataRequest.postData, but only thing you need to do: make this property public by moving code
#property (retain) NSMutableArray *postData;
from ASIFormDataRequest.m to ASIFormDataRequest.h

Related

Post an NSString with spaces to an online form

I have the following code:
NSString * myName = #"Sjakelien Vleeschbaardt";
NSString *urlString= [NSString stringWithFormat:#"http://www.myhost.nl/createUser.php?name=%#", myName];
NSString *url =[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
With the URL, I store myName in an online mySQL database.
I understand, that a URL shouldn't contain spaces, and that these spaces should be escaped. As a result of above code, myName ends up in the database, encapsulated with 'single quotes'.
The question is, where/when should I compensate for this problem?
In the code above? Maybe I should use a different encoding?
Server side? Can mySQL or PHP fix this before storing?
Upon retrieving the data, by bluntly removing the quotes? And what if somebody's name is O'Hara?
UPDATE: MY BAD
I'm awfully sorry.
I discovered that what I simplified in my example as "NSString * myName=" in my real code is represented by something that introduces the single quotes.
I hope somebody makes the same mistake, and can find some comfort here.

Escaping NSURL characters

Im working on a library for the LinkedIn api. In some cases i need to send a escaped url.
Im using CFURLCreateStringByAddingPercentEscapes for this task and seems to work find for me.
Why this is not a valid URL?
NSURL *base = [NSURL URLWithString:#"https://api.linkedin.com"];
NSString *r = #"/v1/people/url={www.linkedin.com%2Fin%2Fbilby91}";
NSURL finalUrl = [NSURL URLWithString:r relativeToURL:base];
finalUrl is always null and i think is correctly escaped. The original url is www.linkedin.com/Fin/bilby91
Thanks
add this
NSString *r = [#"/v1/people/url={www.linkedin.com%2Fin%2Fbilby91}" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
The problem was that this characters '{' '}' need to be encoded even though they are not reserved. Some characters including the ones before are considered unsafe and can be misunderstood in the url so its better to always encode them.
[NSString stringWithFormat:#"%#",[r stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
use this, this may help u

How can I convert an NSString with printer commands into NSData

I need to send a series of printer commands to a Sato barcode printer. For example:
<ESC>A
<ESC>H0120
<ESC>V0060
<ESC>$B,180,180,0
<ESC>$=Information
...
I have an open tcp/ip connection to the printer and simply want to write an NSData object, such as:
[connection write:data error:error];
wheras data is an NSData object. I realize that I can insert the escape into a string using the binary value with \x1B. For example:
NSString *printString=[[NSString alloc]initWithString:#"\x1BA\X1BH0120\X1BV0060\X1B$B,180,180,0/X1B$=Information"];
The problem I'm having is that I don't know how to translate my string to NSData for the write.
I appreciate any suggestions.
You can simply do:
NSData *data = [printString dataUsingEncoding:NSUTF8StringEncoding];
Choose the encoding that best suits your needs, apart from that it's pretty straightforward.
I'll give an update on some of my findings in case someone stumbles upon a similar problem in the future. My problem was that I needed to send a series of printer commands to a Sato barcode printer. Sato uses a proprietary language that requires syntax like above whereas I needed to send commands like <ESC>A and <ESC>Z. I had an open tcp/ip connection and kept trying several methods to send the commands with no luck. I though the problem was in my translation to NSData. I was close, but not close enough. The problem turned out to be in my translation from a file to an NSString...not when I was converting the NSString to NSData. I also had problems trying to use \x "escapes" to send the binary equivalent of <ESC>. I finally settled on using the octal equivalent.
// load the appropriate file as a string
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sato.txt"];
NSError *firstError=nil;
NSString *satoData=[[NSString alloc]initWithContentsOfFile:filePath encoding:NSNonLossyASCIIStringEncoding error:&firstError]; // the NSNonLossyASCIIStringEncoding was the key to correcting my problem here.
satoData=[satoData stringByReplacingOccurrencesOfString:#"Description" withString:self.description];
satoData=[satoData stringByReplacingOccurrencesOfString:#"ItemID" withString:self.itemId];
satoData=[satoData stringByReplacingOccurrencesOfString:#"Quantity" withString:self.printQty];
NSDate *now=[NSDate date];
NSString *formattedDate=[NSDateFormatter localizedStringFromDate:now dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
satoData=[satoData stringByReplacingOccurrencesOfString:#"Date" withString:formattedDate];
NSData *data=[satoData dataUsingEncoding:NSUTF8StringEncoding];
[connection write:data error:error];
Here is a sample of some of the contents of the sato.txt file
\033A\033#E5\033Z
\033A\033H0120\033V0060\033$B,180,180,0\033$=ItemID
The \033 is the octal escapes for <ESC>

fetching data from URL in objective c

I am making iPad application, in which, I am fetching data from a URL. Sometimes, I retrieved Null instead.
In my URL i am passing my id dynamically, for eg: in this code i passed id = PNB,
here is the code snippet:
NSMutableString*str;
NSString *urlAddress = #”http://ipad.idealake.com/stockquote.aspx?id=PNB”;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
str=[NSMutableString alloc] initWithContentsOfURL:url]; //(here compiler shows me warning initWithContentsOfURL is deprected)
NSLog(#"str=%#",str);
When I do NSLog of str, it shows me null value,
output: str=null
However, when I pass id=SUNPHARMA or id=AMBUJA it shows me proper output but when i pass id=TCS or id=LT it again shows me null value in my str. What went wrong?
you have to trim your id , and try...
The reason for getting nil is probably because the id argument is sometimes wrong (TCS or LT). Double check them, the URL probably hasn't any information to give in response.
About the warning, as stated in the doc, the initWithContentsOfURL: method is deprecated since iOS 2.0, you are encouraged to use initWithContentsOfURL:encoding:error: instead.
PLease use ASIHTTPRequest LIB to solve all your problem. They do download data to memory or directly to a file on disk, cache responses and download progress indicators for operation queues. http://allseeing-i.com/ASIHTTPRequest/

passing JSON from ASIHTTPRequest to django

I've exhausted other threads, so I'm posting this question here. Please pardon any newbie mistakes I've made along the way. I've been reading a lot, and I think I'm getting confused.
The Goal:
I'm trying to pass data from a form in objective-c to my django web service. In an effort to assist with this, I've employed the ASIHTTPRequest class to facilitate information transfer. Once sent to the web service, I'd like to save that data to my sqlite3 database.
Procedure:
On the Objective-C side:
I've stored the inputted form data and their respective keys in an NSDictionary, like this:
NSDictionary *personInfo = [NSDictionary dictionaryWithObjectsAndKeys:firstName.text, #"fName", middleName.text, #"mName", lastName.text, #"lName", nil];
I've added it to my ASIHTTPRequest in a different class by using a delegate. I've made the NSDictionary the same as above in the code block below for simplicity, like so:
NSString *jsonPerson = [personInfo JSONRepresentation];
[request addRequestHeader: #"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonPerson dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request startAsynchronous];
And a NSLog shows the string I'm passing to look like this, which validates at least in JSONLint
{"mName":"Arthur","lName":"Smith","fName":"Bob"}
Because I'm seeing what appears to be valid JSON coming from my ASIHTTPRequest, and actions are running from requestfinished: rather than requestfailed:, I'm making the assumption that the problem more than likely isn't on the Objective-C side, but rather on the django side.
Here's what I've tried so far:
json.loads(request.POST)
>>expected string or buffer
json.loads('request.POST')
>>no JSON object to decode
json.loads(request.raw_post_data)
>>mNamelNamefName
incoming = request.POST
>>{"mName":"Arthur","lName":"Smith","fName":"Bob"}
incoming = request.POST
onlyValues = incoming.iterlists()
>>(u'{"mName":"Arthur","lName":"Smith","fName":"Bob"}', [u''])
...and a smattering of other seemingly far-fetched variations. I've kept a log, and can elaborate. The only hope I've been able to find is in the last example; it looks like it's treating the entire string as the key, rather than breaking up each dict object and key as I would have expected.
I realize this is terribly elementary and I don't normally ask, but this problem has me particularly stumped. I do also remember reading somewhere that python won't recognize the double-quotes around each object and key, that to get it to something django likes, each should be surrounded by single-quotes. I just don't have any idea how to get them that way.
Thanks!
This might be a little cumbersome but you may try some simple regexp in objective c just to see if that is really the case
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\"" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *json = [regex stringByReplacingMatchesInString:jsonPerson options:0 range:NSMakeRange(0, [jsonPerson length]) withTemplate:#"'"];
There might be some errors because I didn't run the code.