prepend NSString? - objective-c

I am getting a JSON response from a web service but it is not wrapped by the [] tags required by the JSON parser I am using so I need to Append and Prepend those characters to my NSString before I pass that to the JSON parser.
Here is what I haver so far:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByAppendingFormat:#"]"];
The appending works perfectly now I just need to prepend the [ to this, can't seem to find this method.

Try this:
responseString = [NSString stringWithFormat:#"[%#]", responseString]
There are other ways of acheiving the same thing, I'm sure others will be able to provide more efficient methods, but if responseString isn't very large then the above should suffice.

Using a NSMutableString you can do it like this:
NSMutableString *str = [[NSMutableString alloc] initWithString:#"Overflow"];
[str insertString:#"Stack" atIndex:0];
After that the NSMutableString str will hold:
"StackOverflow"

Just for completeness:
responseString = [#"[" stringByAppendingString:responseString];
It sometimes surprises folks that you can message a string literal, until they think about it. ;)

Related

why will the following code not append one string to the other?

it is the question from my friends. I have research some code from the internet but no help, i think it should working, the question is right.
NNString *s = [[NNString alloc]initWithString:#"hello"];
[s appendString:#"there"];
NSString is immutable, you'd need to use an instance of NSMutableString in order to be able to append to it.
NSMutableString *s = [[NSMutableString alloc] initWithString:#"hello"];
[s appendString:#"there"];
Alternatively you could replace the instance using stringByApendingString:.
Try this if you want to keep the string immutable:
s = [s stringByAppendingString:#" there"];

Converting two double values to String and then making a string using the new strings

I am trying to convert two values to string and then make a new string containing the ones i made earlier so my service can accept them.
NSString *string1 = [ NSString stringWithFormat:#"%f", locationController.dblLatitude];
NSString *string2 = [ NSString stringWithFormat:#"%f", locationController.dblLongitude];
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
This is the code i am using atm. The problem is that both string1 and string2 appear to be ok but the string named body appears to not working.. :< Any help ?
body is not an NSString instance here, but NSData (because you're using `dataUsingEncoding:".
If you want to see concatenation of stings in system log you should write something like that:
NSString* bodyString = [NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2];
NSData* bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
and then you can NSLog(#"Body: %#", bodyString); to see it's contents and then use bodyData for making http request.
body is not an NSString; it is an NSData because of your call to dataUsingEncoding.
I believe this is happening because you are just logging the raw data. Try creating a string from the data and then logging it like this:
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);

Best way to parse a JSONP response

I am calling an API, which should return a JSON file. Here is the API link: http://sg.media-imdb.com/suggests/h/hello.json
The problem is: this JSON file has something wrapping the JSON response
imdb$hello(JSON)
So the best approch that I can see is to use a regex expression to extract only what I need. Something like: ~/\((.*)\)/.
However I would like to use the new JSON iOS5 API, which (as far as i know) only accepts NSData as input. So, I don't want to convert my response from NSData to NSString, parse that using regex, and put that in another NSData object.
Can anyone see a better/cleaner solution for that JSON parsing?
What you have isn't JSON, but JSONP. If you're not in JavaScript, I believe the correct way to handle is just as you say, preprocess and then parse.
NSError *jsonError = nil;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [jsonString rangeOfString:#"("];
range.location++;
range.length = [jsonString length] - range.location - 1;
jsonString = [jsonString substringWithRange:range ];
NSJSONSerialization *jsonResponse =
[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
Why don't you just do something like this before parsing the JSON?
response = [response stringByReplacingOccurrencesOfString:#"imdb$hello" withString:#""];
How regular is this string. It will always be there?
// Remove #"imdb$hello(" and #")" that wraps the response string.
NSRange JSONRange = NSMakeRange(11, [responseString length] - 12);
NSString *JSONString = [responseString substringWithRange:JSONRange];
// Now you can parse as normal…
You will need to craft the method of peeling away the wrapper with your own level of certainty.

create an UTF-8 string with BOM

I'm using MD5 function and Base64 Encoding to generate a User Secret (used to login to data layer of the used API)
I did the code in javascript and it's fine, but in Objective C I'm strugling with the BOM
my code is:
NSString *str = [[NSString alloc]
initWithFormat:#"%#%#%#%d",
[auth uppercaseString],
[user uppercaseString],
[pwd uppercaseString],
totalDaysSince2000];
NSString *sourceString = [[NSString alloc] initWithFormat:#"%02x%02x%02x%#",
0xEF,
0xBB,
0xBF,
str];
NSString *strMd5 = [sourceString MD5];
NSData *sourceData = [strMd5 dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedString = [[sourceData base64EncodedString] autorelease];
using the code above I'm getting into the memory:
(source: balexandre.com)
witch is not what I really need...
I even tried with
"%c%c%c%#", (char)239, (char)187, (char)191, str
with no luck...
using UTF8String does not seam to append the BOM automatically as in C# :-(
How can I append the BOM correctly ?
Try embedding the BOM directly in the format string as escaped character literals:
NSString *sourceString = [[NSString alloc] initWithFormat:#"\357\273\277%#", str];
You might have to add the BOM to the NSData object, not the NSString. Something like this:
char BOM[] = {0xEF, 0xBB, 0xBF};
NSMutableData* data = [NSMutableData data];
[data appendBytes:BOM length:3];
[data appendData:[strMd5 dataUsingEncoding:NSUTF8StringEncoding]];
I had similar issue with Swift and opening CSV fime in Excel.
This question also helped me a lot.
Simple solution for swift with CSV file:
let BOM = "\u{FEFF}"
csvFile.append(BOM)

Merge 5 NSStrings in Objective-C

I have multiple NSStrings and i wish to merge them into one other, here is my code so far...
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = #"Hey!<br>I just snipped my long url with My Cool App for iPhone in just a few seconds!<p><b>"+newURL+#"</b></p>";
If you know the number of your existing strings, you can just concat them:
NSString* longString = [firstString stringByAppendingString:secondString];
or:
NSString* longString = [NSString stringWithFormat:#"A string: %#, a float: %1.2f", #"string", 31415.9265];
If you have an arbitrary number of strings, you could put them in an NSArray and join them with:
NSArray* chunks = ... get an array, say by splitting it;
NSString* string = [chunks componentsJoinedByString: #" :-) "];
(Taken from http://borkware.com/quickies/one?topic=NSString)
Another good resource for string handling in Cocoa is: "String Programming Guide"
You can try
NSString *emailBody = [ NSString stringWithFormat: #"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newURL ];
Given that you've got multiple strings I recommend using an Array:
NSArray *array = [NSArray arrayWithObjects:#"URL", #"person", "body"];
NSString *combined = [array componentsJoinedByString:#""];
Formatting string has better readability and less error-prone:
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = [NSString stringWithFormat:#"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newUrl, newUrl];
You can concatenate strings in Cocoa using:
[NSString stringByAppendingString:]
Or you could use the [NSString stringWithFormat] method which will allow you to specify a C-style format string with a variable argument list to populate the escape sequences.