CFURLCreateStringByAddingPercentEscapes, strange behavior? - iphone

I am trying to encode a URL, I've never done this before, so I'm confused when not getting the results expected.
I'm using CFURLCreateStringByAddingPercentEscapes to do this, but whats returning looks nothing like any online URL encoders/decoders e.g.
-(void)urlEncodedString{
NSString *str = #"\"Hi!! my name is John. \n What's your's?\"";
NSLog([(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)str, NULL, CFSTR("!$&'()*+,-./:;=?#_~"), kCFStringEncodingUTF8) autorelease]);
}
I was expecting something like:
%5C%22Hi%21%21%20my%20name%20is%20John.%20%5Cn%20What%27s%20your%27s%3F%5C%22
But instead I'm getting:
2i2212yame 0s2ohn3.786691E-27020A2hat º»åå2our 0.0000002
That can't be normal. I've been searching and tried everything, the way I did it apparently should work.
Can anyone point me in the right direction?

You are passing the result as the first string to NSLog which expects a string with formatting which uses the percent signs. You are essentially filling the string with random data in memory in place of each % escape. To fix this log using an Objective-C object specifier:
NSLog(#"%#", [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)str, NULL, CFSTR("!$&'()*+,-./:;=?#_~"), kCFStringEncodingUTF8) autorelease]);

Related

Strange BAD_EXC_ACCESS when declaring a string

Okay, all I am doing is setting an NSString to a value with this code:
NSString *stringURL = [NSString stringWithFormat:#"http://api.themoviedb.org/3/movie/%#/trailers?api_key=1523229ded5824dab8bb7840782db266",searchID];
This is a string that I then turning into a URL for querying the TMDB database. This line of code gives me a BAD_EXC_ACCESS and it is blowing my mind because using this sort of NSString construction is something I have done thousands of times without a problem.
The one other thing to note is that this line is being executed right after another query call is made. The weird thing is that call makes the stringURL the same way, yet it works fine.
Any help would be appreciated...
You need to use %i to log an NSInteger, not %#
You need to use the following
NSString *stringURL = [NSString stringWithFormat:#"http://api.themoviedb.org/3/movie/%d/trailers?api_key=1523229ded5824dab8bb7840782db266",searchID];
Because searchID has NSInteger type and you are using "%#"
If it's an NSInteger you need to use %ld or you will got a warning, you can also use %d and explicitly cast to int via (int)searchID

'?' in strings breaking my XML parser

The parsing of a file containing XML breaks when ever there is a string containing '?'. As an example you can see the line below.
<Radio id="32">
<stationName>BBC 5 Live</stationName>
<streamType>aac+</streamType>
<streamBandwidth>48kbps</streamBandwidth>
<streamURL>http://bbcmedia.ic.llnwd.net/stream/bbcmedia_he2_5live_q?s=1308038932&e=1308053332&h=868e4fa343b375695183f6a3bd0267d9</streamURL>
</Radio>
Is there some way to encode the '?' or what is the way thats generally used to handle this kind of problem, as I would imagine this would be encountered a lot.
The line of code that handles this (i believe) is :
[aRadio setValue:currentElementValue forKey:elementName];
Though I maybe that is not where it breaks.
Many Thanks,
-Code
Most probably, the problem is not the '?' character, but the '&' characters in your URL. The '&' character has a special meaning in XML (it is used to start entities like & or <), so the XML parser will fail if it doesn't find a valid entity. The way to go is to wrap the value in a CDATA section as deanWombourne suggests.
Try this. Convert it into UTF8
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
Then parse with this data...
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
There's a few ways of dealing with this.
1) Percent encode the string before sending from the server (your '?' would become '%3F') and decode the data when you receive in in your app. - see this answer for more details.
2) Use CDATA markers around this bit of data - see here for more details

decoding problem uiwebview

i am using uiwebview in my application. there are some links when user clicks a http search starts. it works fine but i have problems while getting "%58 den ysnky'ye tepki" it is given as "X'den ysnky'ye tepki". it has problems with % char.
identifier:%58'den%20ysnky'ye%20tepki
decoded identifier:X'den ysnky'ye tepki
i am using stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding to decode the string like that;
NSLog(#"identifier:%#", identifier);
identifier = [identifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"decoded identifier:%#", identifier);
how can i get the correct string?
thanks...
It looks like your string may not be encoded properly in the first place. %58 is the correct encoding for the letter “X” (see this ASCII table). As far as I can tell, therefore, the decode is behaving properly.
What are you expecting?

"Invalid" iphone string

I'm converting data (from a web page) to a string). The basic code works (but there's been some subtle change somewhere - maybe on server).
NSLog shows the expected string (maybe 1000 chars long). However, when I float over responseString, it shows "Invalid". Worse, parsing with componentsSeparatedByCharactersInSet does not work.
Ideas?
NSString *responseString;
responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog([NSString stringWithFormat:#"responsestring ='%#'",responseString]);
if ([responseString compare:#""] != NSOrderedSame) {
lines = [responseString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#";"]];
This may happen when the configuration is set to "Release" rather than "Debug" I think.
Do not trust what the debugger says, it is not accurate, this has happened to me and took me a while to realise that the xcode debugger is not always right and should not be trusted, so i no longer trust the debugger and i use nslog statements whenever it tries to tell me something is invalid. So dont worry about it it happens, and when it happened to me I was also parsing responses from some webservice.
Just to be clear -- my experience with seeing "Invalid" in the debugger means that the reference is to an already-released object.
Your question and the comments below seem to suggest that you are thinking "Invalid" is an actual string value -- but are you sure you don't just have a memory management probably?

Objective-C NSString: strange characters when logging

Hey all, I'm a total noob when it comes to Objective-C / iPhone development.
I'm trying to pull in text from a SQLite DB. I have a while loop that looks like this:
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
And within that loop, this prints to the log just fine:
NSLog(#"Text: %s",sqlite3_column_text(selectstmt, 1));
This does not work:
Category *categoryObj = [[Category alloc] initWithPrimaryKey:primaryKey];
categoryObj.categoryName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
NSLog(#"cat name: %s",categoryObj.categoryName);
When I run the above and look at the logs I see:
cat name: ‡}00å
I tried to write the field out to a label, thinking it might be something specific to the NSLog but nothing shows up there. Clearly I'm missing something fundamental but I'm at a loss for what it is.
Log your string with %# instead of %s and you'll be fine. NSStrings aren't pointers to characters, they're full-fledged objects, so you need to use the "object" placeholder in the log format string.
This has the added advantage of doing the right thing with non-ASCII strings and all of the other important things that NSString gives you.
Note that if you had just logged the result from SQLite directly instead of creating an NSString with it, then your %s would have been correct.
Remember: %s is for C strings, %# is for Objective-C objects.