Is there a way for NSString to display HTML character codes? - iphone

I have an NSString that has the following value:
"What#39;s up fellas!"
Is there a simple way to turn HTML char codes like #39; (equivalent to ') into an apostrophe etc?

check GTMNSString+HTML.h out :) It's a part of the Google Toolbox, an extension for iOS development.
taken from this question

Try this one, it works:
#import "NSString+HTML.h"
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *r = #"This is a '\'";
NSString *s = #"This is a &ltHTML-Tag&gt";
NSString *encodedstring = [r kv_encodeHTMLCharacterEntities];
NSString *decodedstring = [s kv_decodeHTMLCharacterEntities];
}

NSString has an UTF8 encode-decode function:
- (id)initWithUTF8String:(const char *)bytes
+ (id)stringWithUTF8String:(const char *)bytes
- (const char *)UTF8String
See the Class Reference here

Related

Converting UTF8 Hex string to regular UTF8 encoded NSString

I am getting UTF-8 (hex): Hc3b8rt back from a server instead of the string "Hørt".
I need to convert this response to regular UTF-8.
What I have tried:
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string UTF8String];
NSString *str = [NSString stringWithUTF8String:cfilename];
Thank you for your time!
There's no way you can decode this. As #JoachimIsaksson stated in the comments above, how can you tell if "abba" is exactly "abba" or two unicode chars?
use string encoding, NSISOLatin1StringEncoding
- (id)initWithCString:(const char *)nullTerminatedCString
encoding:(NSStringEncoding)encoding
Or shortly,
NSString *str = [NSString stringWithCString:cfilename
encoding:NSISOLatin1StringEncoding];
Edit after comments:
This is kind of strange. I have done some experiments after your comments and found some strange behaviour.
- (void) testStringEncodingOK {
NSString *string = #"h\u00c3\u00a5r";
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
This output: hår
But if you get the \U in capital, not \u, then I replaced them to \u. And then it did not work. Seem the ,
- (void) testStringEncodingConfused {
NSString *string = #"h\\U00c3\\U00a5r";
string = [string stringByReplacingOccurrencesOfString:#"\\U" withString:#"\\u"];
NSLog(#"Original string:%#", string); // now string = #"h\u00c3\u00a5r"
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
The output is, h\u00c3\u00a5r
Use below code..
const char *ch = [yourstring cStringUsingEncoding:NSISOLatin1StringEncoding];
 yourstring = [[NSString alloc]initWithCString:ch encoding:NSUTF8StringEncoding];
NSLog(#"%#",yourstring);
let me know it is working or not...
Happy Coding....
use this code
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *str = [NSString stringWithUTF8String:cfilename];
and tell if it is working or not.

Add text/data along with special characters as a parameter to api(url) in iphone

I am new to Obj-c. I am adding parameter like text (the text may have special characters also)to url. But the url is showing nil, it's not taking value from string.
For example:
NSString*strUrl=[NSString stringWithFormat:#"hi how#!#$%^^&*()_=+ r u <>,./ where r u"];
NSString *strMainUrl=[NSString stringWithFormat:#"http://google.com/API/index.php action=listIt&data=%#",strUrl];
NSString *encodeStr = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encodeStr];
NSLog(#" url is =%#",url);
But the url is showing nil value. It's not taking "encodeStr" value. How can I solve this problem.Please help me.
I tried with..
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
and also
strEncode=[strEncode stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
Modified example from here:
#import <Foundation/Foundation.h>
// In case you're unfamiliar, this is a category, which allows us to add methods
// to an existing class, even if we didn't create it. It's a nice alternative
// to subclassing.
//
// In this case, we're extending NSString
#interface NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
#end
#implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
#end
int main(int argc, char *argv[]) {
#autoreleasepool
{
NSString *raw = #"hi how#!#$%^^&*()_=+ r u <>,./ where r u";
// note also, that your string omits the '?' in the URL
NSString *url = [NSString stringWithFormat:#"http://google.com/API/index.php?action=listIt&data=%#",
[raw urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSURL *finalUrl = [NSURL URLWithString:url];
NSLog(#"%#", finalUrl);
}
}
Output:
http://google.com/API/index.php?action=listIt&data=hi%20how%40%21%23%24%25%5E%5E%26%2A%28%29_%3D%2B%20%20%20r%20u%20%3C%3E%2C.%2F%20where%20r%20u

How to convert unsigned char to NSString in iOS

Can anyone tell me how to convert an unsigned char to an NSString?
Here's the code I am using, but for some reason if I try to do anything with the NSString, like set a UITextView text, it gives me an error. The NSLog works correctly though. Thanks in advance.
- (void)onTagReceived:(unsigned char *)tag
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *myTag = [NSString stringWithFormat:#"%02x%02x%02x%02x%02x\n",tag[0],tag[1],tag[2],tag[3],tag[4]];
NSLog(#"currentTag: %#",myTag);
[displayTxt setText:myTag];
[pool release];
}
If tag is a C string (null-terminated, that is), then you can use [NSString stringWithUTF8String:(char *)tag]. If you want the hex values, then your code using %02x is fine.
#jtbandes: you are correct. The other way you can do this:
NSString *str = [NSString stringWithCString:tag length:strlen(tag)];

NSString issues

I have an NSString that gets assigned a string value. How do I take this NSString and insert #"-thumbnail" between the file's name and its extension?
In other words, how do I go from:
NSString *fileName = #"myFile.png";
to:
NSString *thumbnailName = [NSString someMagicFunction...]
NSLog(#"%#", thumbnailName); // Should Output "myFile-thumbnail.png"
The NSString additions for path components can come in handy, specifically: pathExtension and stringByDeletingPathExtension
Edit: see also: stringByAppendingPathExtension: (as pointed out by Dave DeLong)
NSString * ext = [fileName pathExtension];
NSString * baseName = [fileName stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:#"-thumbnail"];
NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext];
If you really want that magicFunction to exist, you can add a category method to NSString like so:
#interface NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;
#end
#implementation NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix
{
NSString * extension = [self pathExtension];
NSString * baseName = [self stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:suffix];
return [thumbBase stringByAppendingPathExtension:extension];
}
#end
To be used as follows:
NSString * thumbnailName = [fileName stringByAddingFileSuffix:#"-thumbnail"];
If you are certain of your filenames, you could also simply do:
[NSString stringByReplacingOccurrencesOfString:#"." withString:#"-thumbnail."]
But the path handling stuff is cleaner (doesn't care how many "." you have in the name) and good to know about for trickier cases.
We've got an opensource category for just that: -[NSString ks_stringWithPathSuffix:]

How to write this method in Objective-C?

I just started Objective-C recently, and this has once again gotten me to the point of asking SO for help. I need to rewrite this method so that I can call it using [self URLEncodedString];
This is what the method currently looks like -
- (NSString *)URLEncodedString {
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:#&=+$,/?%#[]"), kCFStringEncodingUTF8);
[result autorelease];
return result;
}
But I can't call it like [self URLEncodedString]; How can I rewrite it so that it would work for me to be able to call it using [self URLEncodedString];?
P.S. Calling it via [strValue URLEncodedString]; doesn't work, hence the reason I'm making this post.
Thanks for any help!
I think what you're asking for is to create an NSString category which will encode your string.
You need to create a new set of files, name them something that makes sense (NSString+URLEncoding).
In the .h file, you'll need something like this:
#interface NSString (URLEncoding)
- (NSString*)URLEncodedString;
#end
Then in your .m file:
#implementation NSString (URLEncoding)
- (NSString *)URLEncodedString {
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:#&=+$,/?%#[]"), kCFStringEncodingUTF8);
[result autorelease];
return result;
}
#end
When you want to use this method, you'll need to make sure you import "NSString+URLEncoding.h".
You can then do something like this:
NSString * firstString = #"Some string to be encoded %&^(&(!#£$%^&*";
NSString * encodedString = [firstString URLEncodedString];
Hope that helps.
Why not just use the NSString instance method stringByAddingPercentEscapesUsingEncoding?