URL string escape representation in objective-c? ("percent encoding") - objective-c

I want to make a very simple task in objective-c under IOS5: convert URL string to its escaped representation.
I tried a lot of ways to do it but neither seemed to work.
I can not make stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding work. It converts letters like áíűőüöúóé but does not convert others like =.
I'd like to have a function like Uri.EscapeDataString ( http://msdn.microsoft.com/en-us/library/system.uri.escapedatastring.aspx ) in .net.
Thanks!

You could add a category to NSString that does something like
- (NSString *)ps_stringByAddingPercentEscapes;
{
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
(CFStringRef)#":/?#[]#!$&’()*+,;=",
kCFStringEncodingUTF8) autorelease];
}
Replace #":/?#[]#!$&’()*+,;=" for the chars that you care about.

Related

How to convert NSString into hexDecimal value

I have following line of code and I want to convert into HexDecimal value.
NSString *hexDecimal = #"€";
I want the result to be hexDecimalValue = 0x20ac.
NSScanner can do this. Here an example method:
- (NSNumber *)scanHex:(NSString *)aString {
NSScanner *sc=[NSScanner scannerWithString:aString];
if(![sc scanString:#"&#x" intoString:NULL]) return nil;
unsigned long long val;
if(![sc scanHexLongLong:&val]) return nil;
return [NSNumber numberWithUnsignedLongLong:val];
}
This method will return nil if aString does not have the &#x you list, or if that is not followed by a valid hex string. Otherwise it returns a NSNumber object with the desired value.
Looks like you have HTML/XML escaped entities. What you really want to use is the Core Foundation function CFStringTransform.
For that you'll want to have an NSMutableString and bridge it to CFMutableString.
The secret sauce is that this CF function wraps the ICU (International Components for Unicode) library's string transform.
The ICU docs will give you more possible transforms. But for this, you want Hex-Any as your transform if I recall correctly.

how do i do: label.text = (#"some string" + _label2.text);

I am completely new to Objective-C and although i have some experience with java and C#, I just can't get this to work.
My code is:
- (IBAction)btnClickMe_Clicked:(id)sender {
Label_1.text = (#"some string" + _Label_2.text);
}
I am also curious as to why Label_1 does not need an underscore infront of it, like _Label_2 does?
To concatenate strings, you use
Label_1.text = [#"Some string" stringByAppendingString:_Label_2.text];
You can use %# to append your additionnals strings with stringWithFormat
Label_1.text = [NSString stringWithFormat: #"Some string %#", _Label_2.text];
More example : Apple - Formatting String Objects
NSString provides a vast variety of methods for string manipulations. Amongst them are several ways for conatination.
You should get familiar with the factory method stringWithFormat. It is one of the most powerful and especially good at a bit more complex requirements.
In your case:
Label_1.text = [NSString stringWithFormat:#"Some string%#", _Label_2.text);
or
Label_1.text = [NSString stringWithFormat:#"%#g%#", #"Some string", _Label_2.text);
The format string corresponds to the usual standard c printf format string plus the %# tag which is replaced by any objects description value. So you could have an NSNumber there or even an NSArray or so. However, the description of NSArray, NSDictionary, NSSet etc. may not really be useful for production but come quite handy for debugging. NSLog() uses the same format.

How to encode or decode URL in objective-c

Is there something like
+(NSString *) URLencode: (NSString *) someString
+(NSString *) URLdecode: (NSString *) someString
If so, how to implement it?
Note to downvoters. This is NOT a simple question. I need something that can comprehensively do this. For example:
NSString * test = #"汉字马拉松是";
NSString * encoded = [test stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
PO(encoded);
PO(test);
Will yield the following:
2012-06-04 16:04:22.709 BadgerNew[2266:17003] <0xcd890 GrabClass.m:(930)> encoded (null)
2012-06-04 16:04:22.710 BadgerNew[2266:17003] <0xcd890 GrabClass.m:(931)> test 汉字马拉松是
I want my encoding to be able to URL encode EVERYTHING including japanese language, etc.
So I want encoded to contain something along %E6%B1%89%E5%AD%97%E9%A9%AC%E6%8B%89%E6%9D%BE%E6%98%AF
There are 2 different methods in http://mobiledevelopertips.com/networking/a-better-url-encoding-method.html
None are good enough.
I need to be able to encode ALL strings, including japanese/chinese characters.
Update: I followed H2CO3 answer and do this:
NSString * test = #"汉字马拉松是";
NSString * encoded = [test stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
PO(encoded);
PO(test);
PO(encoded);
Work as expected.
You probably want to take a look at the stringByAddingPercentEscapesUsingEncoding and stringByReplacingPercentEscapesUsingEncoding methods.
Encoding example (using ASCII):
NSString* encodedString =
[originalString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
Decoding example (using ASCII):
NSString* originalString =
[encodedString stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
EDIT:
If this doesn't give the desired results try replacing NSASCIIStringEncoding with NSUTF8StringEncoding.
Also you might want to try the variant of above methods :
NSString * encodedString =
(NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)originalString,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
Which will work better in some cases
It's natural that Chinese and Japanese characters don't work with ASCII string encoding. If you try to escape the string by Apple's methods, which you definitely should to avoid code duplication, store the result as a Unicode string. Use one of the following encodings:
NSUTF8StringEncoding
NSUTF16StringEncoding
NSShiftJISStringEncoding (not Unicode, Japanese-specific)

How to get a single NSString character from an NSString

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.
This is the code I use to get a single character at index it:
[[s substringToIndex:i] substringToIndex:1]
Is there a better way to do it?
This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.
NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
If you just want to get one character from an a NSString, you can try this.
- (unichar)characterAtIndex:(NSUInteger)index;
Used like so:
NSString *originalString = #"hello";
int index = 2;
NSString *theCharacter = [NSString stringWithFormat:#"%c", [originalString characterAtIndex:index-1]];
//returns "e".
Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.
Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.
NSMutableString *myString=[NSMutableString stringWithFormat:#"Malayalam"];
NSMutableString *revString=#"";
for (int i=0; i<myString.length; i++) {
revString=[NSMutableString stringWithFormat:#"%c%#",[myString characterAtIndex:i],revString];
}
NSLog(#"%#",revString);

How do you convert C String to NSString?

I have been able to find methods like -[NSString stringWithCString:encoding:] but they do not seem to play well when the cstring is a pointer.
First up, don't use initWithCString, it has been deprecated.
Couple of ways you can do this:
const *char cString = "Hello";
NSString *myNSString = [NSString stringWithUTF8String:cString];
If you need another encoding like ASCII:
const *char cString = "Hello";
NSString *myNSString = [NSString stringWithCString:cString encoding:NSASCIIStringEncoding];
If you want to see all the string encodings available, in Xcode, hold command + option then double click on NSASCIIStringEncoding in the above code block.
You will be able to see where Apple have declared their enumeration for the string encoding types. Bit quicker than trying to find it in the documentation.
Some other ones you might need:
NSASCIIStringEncoding
NSUnicodeStringEncoding // same as NSUTF16StringEncoding
NSUTF32StringEncoding
Checkout Apple's NSString Class Reference (encodings are at the bottom of the page)
With modern Objective-C (since Xcode 5 at least) you can just do:
char const* cString = "Hello";
NSString *myNSString = #(cString);
stringWithCString:encoding: creates an NSString from a given C string. To create a C string from an NSString, use either the UTF8String method (generally preferred) or cStringUsingEncoding: (if you need an encoding other than UTF-8).