NSURL string content to a label - ios

Im trying to read some values from a local url when i press a button and i send the value to a label. as soon as i launch the app and i press the button for the first time i get the value. but the second time i press the button the label get no text even though the NSLog message continues to display the value. any idea?
here is the code:
- (IBAction)refresh:(id)sender {
NSArray *listItems;
NSString *msg;
NSStringEncoding encoding;
NSURL *url = [NSURL URLWithString:#"http://192.168.1.177"];
NSData *data = [NSData dataWithContentsOfURL:url];
msg = [[NSString alloc] initWithData:data encoding:encoding];
listItems = [msg componentsSeparatedByString:#" "];
label.text = listItems[0];
NSLog(listItems[0]);
}

Your encoding variable is never initialized with a value, so it has the default value of 0, which is not a valid value of NSStringEncoding according to NSString.h. If you run the static analyzer (Command-Shift-B in Xcode), you will get a message that has an uninitialized value when it is used.
Change this line:
msg = [[NSString alloc] initWithData:data encoding:encoding];
to this:
msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
(Substitute the appropriate encoding, but NSUTF8StringEncoding is a good first guess.)
You should also use a format string to log:
NSLog(#"%#", listItems[0]);

Related

How to show special character in UILabel iOS

I am trying to implement an app where I would like to show some text in Spanish format. For example I would like to show "España" but in my label it shows "Espa√ɬ±a" and also it changes the text for some of other text.
How to get rid of these. If anybody could help. Thanks.
Edit: When i am getting my response it logs that Below result
Message = (
"Espa\U221a\U00c9\U00ac\U00b1a:1.3\U221a\U00c7\U00ac\U00a2/min"
);
But when i extract the value according to key from Dictionary it shows
España:1.3¢/min
It means when i am getting the value from dictionary it cant do proper decoding.
how to resolve this. Any idea..?
First convert your response String to NSData using NSUTF8StringEncoding encoding, then again convert the same data to finalString like below.
NSString *string = #"España"; //Your response String goes here
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *finalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
lblTemp.text = finalString;
UPDATE 1
I think there is some error from your response, Please see below
NSString *string = #"Nu\\u0161a Florjan\\u010di\\u010d";
NSString *finalString = [NSString
stringWithCString:[string cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"finalString = %#", finalString);
Output of above code is,
finalString = Nuša Florjančič
UPDATE 2
If you want output string like "España", your desired response should be "Espa\u00F1a", Find below,
NSString *string = #"Espa\\u00F1a";
NSString *finalString = [NSString
stringWithCString:[string cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"%#",finalString);
Output is España

Song title by stream wrong Encoding

I'm working on a simple radio stream app for ios. I'm retriving song title with a KVO Observation of:
if ([keyPath isEqualToString:#"timedMetadata"])
{
for (AVMetadataItem* metadata in playerItem.timedMetadata)
{
if([metadata.commonKey isEqualToString:#"title"]){
}
}
}
With this code i can get the title. Anyway whe there are some characthers i have this result:
deep grounder feat virÃ;g
instead of
deep grounder feat viràg
So i'm trying any solution to print the correct result in the screen. I have also tried:
NSString *StringaPassata=[NSString stringWithFormat:#"%#",#"deep grounder feat virÃ;g"];
NSData *data = [stringFromUTFString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
The string remain the same... I have not control on the server that output the stream. To test the conversion i store in a NSString the string that cause the problem when it is downloaded from the server.
How i can convert to the string to the correct "à" ?
Try This Snippet I Have tried it
NSString *strYourKey = #"deep grounder feat viràg";
NSData *data = [strYourKey dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *dataToString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Your Converted Text is : %#", dataToString);
Output
[12134:168898] Your Converted Text is : deep grounder feat virag

String encode in objective c

I am very new to Objective-C.
I want to get the encoded content for a NSString. In java I can do that as follows,
String str = "https://www.google.co.in/#q=ios+sqlite+crud+example";
String encodedParam = URLEncoder.encode(str, "UTF-8");
I am using http://www.tutorialspoint.com/compile_objective-c_online.php to test the codes posted in stackoverflow. There is no solution yet. I know its trivial one. Struggling to find a way though.
tried with following function, and it says following error while compile,
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
Error,
sh-4.3$ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/System/Library/Libraries -lgnustep-base -lobjc *.m -o main
main.m: In function 'main':
main.m:7:14: error: 'urlEncodeUsingEncoding' undeclared (first use in this function)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
^
main.m:7:14: note: each undeclared identifier is reported only once for each function it appears in
main.m:7:36: error: expected ';' before ':' token
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
Edit as per the answers,
Suggested by Patrick, I used the code as follows,
NSString *storedURL = #"google.com/?search&q=this";
NSString *urlstring = [NSString stringWithFormat:#"http://%#/",storedURL];
NSURL *url = [NSURL URLWithString:urlstring];
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
NSLog (my_string);
Nothing printed in console... Is it my NSLog is right?
Suggested by lightwolf, my code is looks like below,
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog (encodedParam);
it prints the log, but value is same as the str..... not encoded... I want this str as
https%3A%2F%2Fwww.google.co.in%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to encode a specific range of characters you chould use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSLog (#"%#", encodedParam);
Note the invertedSet; In that way, you are encoding all characters except the set specified (all alphanumeric ones)
The result is
https%3A%2F%2Fwww%2Egoogle%2Eco%2Ein%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to use a specific set of characters you should use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSCharacterSet* set = [NSCharacterSet characterSetWithCharactersInString:#"!*'();#&=+$,?%#[]"];
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[set invertedSet]];
NSLog (#"%#", encodedParam);
In this case I intentionally missed / and : so the result is
https://www.google.co.in/%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
Maybe this is what you want
NSString *str = #"<html><head><title>First</title></head><body><p>Parsed HTML into a doc.</p></body></html>";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You have to encode only the params, not the entire URL of course

unable to show emoji's properly in UIlabel

I am trying to save the emojis to server and on later time receiving them.
I used the Following Code before
NSData *data = [strEmo dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *data1 = [strEmo dataUsingEncoding:NSUTF8StringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];
It generates the Hashcode for the Emoji. But decoding doesn't work. So I skipped the Idea of using this Code.
Then I used a third Party NSString+HTML.h Class. Which Sends and recieve emoji easily. But
Now the Problem is when there are so many emoji's the UIlabel on which I am showing the data, the emojis are distorted and If I saved 20 emojis it shows 12-13 only.
I have added the Pic for reference
where Yellow part is UIlabel with back colored Yellow
Buddy why are you changing the string in Data two times in a row just simply use this
NSString *uniText = [NSString stringWithUTF8String:[strEmo UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *readyString = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
First convert your string into constant C characters then convert it into string using UTF8 encoding, now convert it into NSData as (7-bit verbose ASCII to represent all Unicode characters) using NSNonLossyASCIIStringEncoding encoding and then again string ready to send with unicode characters. Hope this should work as it is working fine in my code.

EMoji Unicode for IOS

I call api and get the string which include the android java unicode in NSDictionary :
\ud83d\ude25\ud83d\ude1e\U2764\ud83d\ude2d
When get the the value above and assign to string, I just will get the string as:
\ud83d\ude25\ud83d\ude1e❤\ud83d\ude2d
I totally can not get the value \U2764 but get the value ❤
So I can not replace the code \U2764 to IOS unicode.
How can I get it \U2764? I convert into UTF-8.
Thanks
Edit:
This is get the directory from api (dic):
{
message = "\ud83d\ude25\ud83d\ude1e\U2764\ud83d\ude2d";
mesgid = "213133";
Thumbnail = "";
}
Then i get the message, but the dic2 string is still get \ud83d\ude25\ud83d\ude1e❤\ud83d\ude2d:
const char *cString = [[dic6 objectForKey:#"Message"] UTF8String];
NSString *dic2 = [[NSString alloc] initWithUTF8String:cString];
if ([dic2 rangeOfString:#"\\U"].location==NSNotFound && [dic2 rangeOfString:#"\\u"].location==NSNotFound)
{
NSLog(#"Substring Not Found");
}
else
{
NSLog(#"Substring Found");
}
I totally can not get the unicode.
Why?
try this
NSString *uniString = [NSString stringWithUTF8String:#"\ud83d\ude25\ud83d\ude1e❤\ud83d\ude2d
"];
Hopefully this will resolve your problem
char cString[] = "\ud83d\ude25\ud83d\ude1e\U2764\ud83d\ude2d";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Resources