Add double quote to NSString attach to the variable [duplicate] - ios

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to initialize NSString as text with double quotes
How can I add tan actual double quote to a variable inside on NSString to be used in NSDictionary?
Example
NSString *ename=#"John Doe";
NSDictionary *profile=#{#"Profile":#{"Name":ename}};
I need to display like this "Profile":{"Name":"John Doe"}

I need to display like this "Profile":{"Name":"John Doe"}
Do you want to create JSON format? Then you can use the built-in class NSJSONSerialization:
NSString *ename = #"John Doe";
NSDictionary *profile = #{#"Profile":#{#"Name":ename}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:profile options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"Profile":{"Name":"John Doe"}}

Use escape charater \ ...
NSString *ename=#"This is double \" quote \"";
If you are asking for adding quotes in Key of dictionary, then you have to add some special character, (non-alphabet and non-numerical) only then key shows double quotes.
[... description] simply wraps things in quotes for display that have non-alphanumeric characters in them.
And there is no difference between "abc" and abc in debugger. This is used only for dubugging and the actual value is always a NSString #"abc".

Check this
NSString *string=#"This is test \" for \"";
Hope it helps you..

Related

How to show JSON response in iPhone using the objective c by dynamically adding " \" to the keys?

I am having a sample code which helps me to print the JSON response. In this I manually added the \ slash symbol before keys and values so it helps me to print the JSON . The code is :
NSString *jsonString = #"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
Now the problem is once the JSON string gets longer I have to manually add the \ before every key.
Can someone help of how I can add "" before the keys as shown in the code above using some looping code?
Any help will be appreciated.
It's really not clear what you're trying to do - but maybe this will work...
Use:
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement;
The target will be ", and you'll need to escape it like this:
#"\""
The replacement will be \", escaped like this:
#"\\\""
So, this:
NSString *jsonString = #"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
NSLog(#"%#", [jsonString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""]);
will output this to the debug console:
2022-10-11 12:35:58.958881-0400 YourProj[6562:7795515] [{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]
When receiving json from remote, it might look like this:
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSString *js = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", [js stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""]);

Convert NSString to NSUTF32StringEncoding [duplicate]

This question already has answers here:
NSString to treat "regular english alphabets" and characters like emoji or japanese uniformly
(2 answers)
Closed 8 years ago.
I have an NSString that internally uses UTF16 encoding. I want to covert it to use UTF32 , so that
๐Ÿ˜„ or q both take single index. Currenty ๐Ÿ˜„ takes 2.
How to do this ?. Even if I can convert to some other type from NSString it will work. Bottom line is to have ๐Ÿ˜„ or q take equal number of indexes in an array.
Did you try :
NSData *data = [string dataUsingEncoding:NSUTF32StringEncoding];
NSString *convertedString = [[NSString alloc] initWithData:data encoding:NSUTF32StringEncoding];
Have you tried [[NSString alloc]initWithData:encoding:]?
Example would be:
NSData *data = [sourceStr dataUsingEncoding:NSUTF16StringEncoding];
Create your NSUTF32StringEncoded string from the data above
NSString *encodedStr = [[NSString alloc]initWithData:data encoding:NSUTF32StringEncoding];

Encode JSON data for URL

In iOS, I want to send JSON data in URL to make service call. I tried following code snipped but Encoded URL seems wrong. Because in JSON there is a colon character (:) between key and value and comma character (,) for separation. But, i am not able to encode colon(:) as %3A and comma(,) as %2C
Code Snippet:
- (NSURL *)getEncodedUrl {
// Build dictionnary with parameters
NSString *abc = #"abc";
NSNumber *limitNumber = [NSNumber numberWithInt:2];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:limitNumber forKey:#"limit"];
[dictionnary setObject:abc forKey:#"abc"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
if (!jsonData) {
debug("Json error %#",error);
return nil;
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
debug("Json op %#",JSONString);
NSString* params = [JSONString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://baseUrl.com?param=#",params]];
debug("URL = %#",url);
return url;
}
}
OUTPUT:~
URL = http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D
(Include colon and comma characters)
But I want following o/p:
http://baseUrl.com?param=%7B%22abc%22%3A%22abc%22%2C%22limit%22%3A2%7D
(No colon and comma characters)
Online Encoding-Decoding Site that I am referring as of now.
http://www.url-encode-decode.com/
you can simply use
NSString *url = #"http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D";
NSString *encodeImgUrl = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'd recommend that you send the JSON as POST data instead of the GET that you're using. It'd be more straightforward to package it as MIME data and any encoding you do would be easier to understand.
So you are trying to generate the query portion of a URL here. Colons are a perfectly legitimate character to include in URL queries. I wrote an article covering the intricacies of escaping URL queries in Cocoa:
http://www.mikeabdullah.net/escaping-url-queries-in-cocoa.html
Since you're keen to perform extra escaping, I suggest taking my sample code and extending it to specially ask for : and ; characters to be escaped too.
I made small mistake in API call that is why I am getting wrong result. There is no need to encode colon(:) as %3A and comma(,) as %2C.
One more thing I would like to share with you. You can use base64 string instead of encoding JSON part.

iOS modify string to have no line spaces

I am pulling tweets from Twitter and using this to convert it into an array:
NSArray *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
Some of the tweets have a large number of new lines and white space, which has become increasingly annoying for the sake of layout.
I want to turn any strings that have multiple lines into a single lined string.
Here is an example string that I need to convert:
I used #ECSliding library with my project but i canโ€™t used with
#UITableView plz provide me the way if u know it.
#kbegeman
& thank u ;
As you can see this mention has a bunch of white space and couple extra lines.
I have tried using this:
NSString *tweet = [currentTweet objectForKey:#"text"];
NSString *trimmedTweet = [tweet stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
And I also tried this:
myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:#"\n" withString:#""];
myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:#" " withString:#""];
Unfortunately, this does not work. Does it have something to do with the way I am reading in the JSON? Am I using that method wrong? Is there any other solution anyone can think of? Any help would be great, thanks!
That method stringByTrimmingCharactersInSet trims chars from the start and end of the receiver. You'll probably want something like:
NSString *trimmedTweet = [tweet stringByReplacingOccurrencesOfString:#"\n" withString:#" "];

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'ุฃู†ูƒ ูˆุงู‡ู…'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya ุฃูŠุฏุช ุงู„ุซูˆุฑุฉ ุงู„ุณูˆุฑูŠุฉ ู…ู†ุฐ ุจุฏุงูŠุชู‡ุง ูˆุงุฑุฌุน ู„ู„ูŠูˆุชูˆุจ ูˆุงูƒุชุจ( ุณูˆุฑูŠุง ุงู„ุณูˆูŠุฏุงู† )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "ุฃู†ูƒ ูˆุงู‡ู…", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources