String encode in objective c - ios

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

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

iphone - app crash in a form

In my app, I have a view where user have to fill a form. But, sometime the app crash here, in this function, that simple cacth the value field and built a url to give
-(NSString*)urlToUpload{
NSString *string1 =[[NSString alloc]init];
string1= [NSString stringWithFormat:#"?nombre="];
NSString *string2 = [string1 stringByAppendingString:nameAdded];
//crash here
NSString *string3 = [string2 stringByAppendingString:#"&horario="];
NSString *string4 = [string3 stringByAppendingString:horarioAdded];
NSString *string5 = [string4 stringByAppendingString:#"&info="];
NSString *string6 = [string5 stringByAppendingString:infoAdded];
NSString *string7 = [string6 stringByAppendingString:#"&offerta="];
NSString *string8 = [string7 stringByAppendingString:offertaAdded];
NSString *lat_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.latitude] autorelease];
NSString *lon_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.longitude] autorelease];
NSString *string9 = [string8 stringByAppendingString:#"&latitude="];
NSString *string10 = [string9 stringByAppendingString:lat_string];
NSString *string11 = [string10 stringByAppendingString:#"&longitude="];
NSString *string12 = [string11 stringByAppendingString:lon_string];
NSString *url1 = [NSString stringWithFormat:#"http://myserverside/mysql_up.php"];
NSString *url = [url1 stringByAppendingString:string12];
return url;
}
EDIT:
It seems problem appers on nameAdded when there is a white space into textField(i.e. MisterB not crash, Mister B yes ).
But I am using:
nameAdded =[[nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and NSLOg give of nameAdded is Mister%20B.
The crash still appearing...
Just use a single stringWithFormat::
- (NSString *)urlToUpload {
NSString *url = [NSString stringWithFormat:#"http://myserverside/mysql_up.php?nombre=%#&horario=%#&info=%#&offerta=%#&latitude=%f&longitude=%f",
[nameAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[horarioAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[infoAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[offertaAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
locationToUpload2.latitude, locationToUpload2.longitude];
return url;
}
Make sure the referenced variables are valid.
In your original code there is no need to alloc/init an NSString then assign another string to the same variable. That's a memory leak (string1).
If you really want to structure your code the way you have it, at least use an NSMutableString and append to that one mutable string. Creating over a dozen NSString variables is the wrong way to do it.
Updated: Ensure each of the strings added to the URL are properly escaped.
It looks like nameAdded may be the cause of your problems. Is it nil at that point?
Also
You are allocating a string, setting it to string1 and then immediately setting string1 to the class function stringWithFormat which allocates another string. Also you are using stringWithFormat but you aren't using any format so you could simply use NSString *string1 = #"?nombre=";
Rather than declaring all of those variables you should just use NSMutableString and build it all in one variabl

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

How to pass * () $ etc in NSUrl?

I tried to pass these characters to server, for example *()$
I have coded the NSUrl this way:
NSString *partialURL = [NSString stringWithFormat:#"/%#", commentBody];
NSString *fullURL = [NSString stringWithFormat:#"%#%#", CONST_URL, partialURL];
NSString *encStr = [fullURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encStr];
But then, the commentBody passed in the url still has *()$ things and not encoded into utf8.
What is the correct way to do it?
Thanks!
NSString * test = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)validUrl,
NULL,
(CFStringRef)#";/?:#&=$+{}<>,",
kCFStringEncodingUTF8);
UPDATE
Hi #Rendy. Sorry for the quickie reply yesterday. I only had time to past a 1-liner before jumping off and had hoped it would be enough for you to correct the issue you were having.
You always want to encode the parameters of the URL. IF you have a URL that is a parameter to another URL or embedded in some XML; you'll want to encode the entire url (which means parameters get double-encoded - because you take a "valid" URL and escape it so it becomes a valid parameter in another URL (ie, : and & get escaped, so parameters don't mix together.)
If you like, you can add additional chars to the string below and they'll be replaced with percent-encoded values. I believe the string below already has you covered for the invalid values.
Here's a category on NSString:
#implementation NSString (encode)
+ (NSString*)stringEncodedAsUrlParameter:(NSString *)string
{
NSString *newString = NSMakeCollectable(
[(NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef)string,
NULL, /* charactersToLeaveUnescaped */
CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"),
kCFStringEncodingUTF8
) autorelease]
);
if (newString) {
return newString;
}
return #"";
}
- (NSString*)stringByEncodingAsUrlParameter
{
return [NSString stringEncodedAsUrlParameter:self];
}
#end
Call it like this:
NSString * escapedParameters = [NSString stringEncodedAsUrlParameter:unescapedParameters];
Or:
NSString * escapedParameters = [unescapedParameters stringByEncodingAsUrlParameter];
Then add your properly escaped parameters to the end of your URL. If you encode the whole URL, you'll encode the "http://" portion and it won't work.
I originally copied the above from ASIHttpRequest, but any bugs added are mine.
Hope that helps! Best of luck!!

IOS stringByReplacingOccurrencesOfString coming back null

I've been banging my head against the wall on this, I must be missing something. This code is called just after I base64 encode some encrypted text. At the point where I call NSLog signature is always valid. However sometimes the rest works great and other times removePlus or finalSig come back null. Also I'm using Xcode 4.5, ios6 and I have ARC enabled for the project. I feel like maybe something is getting auto released before I want it to, or something like that. If anyone has any ideas any help is appreciated.
// Get the data out of the context
char *outputBuffer;
long outputLength = BIO_get_mem_data(context, &outputBuffer);
NSMutableString *signature = [[NSMutableString alloc] init];
[signature appendString:[NSMutableString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]];
NSLog(#"Base64 Pre Encoded: %#", signature);
signature = [[signature stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding] mutableCopy];
NSMutableString *removePlus = [[signature stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"] mutableCopy];
NSString *finalSig = [removePlus stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"];
//now we create the url request portion
NSMutableString *variables = [[NSMutableString alloc] init];
//set the variables we're going
[variables appendString:finalSig];
Try swapping your code for the following, as I imagine it will show you exactly where your problem is:
// Get the data out of the context
char *outputBuffer;
long outputLength = BIO_get_mem_data(context, &outputBuffer);
outputBuffer[outputLength] = '\0';
if(outputLength != strlen(outputBuffer)) NSLog(#"SOMETHING VERY WRONG");
NSString * signature = [NSString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]];
NSLog(#"Base64 Pre Encoded: %#", signature);
signature = [[signature stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSLog(#"Base64 Post Encoded: %#", signature);
signature = [signature stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSLog(#"Base64 Remove '+': %#", signature);
signature = [removePlus stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"];
NSLog(#"Base64 Remove '=': %#", signature);
//now we create the url request portion
NSMutableString *variables = [NSMutableString alloc] initWithString:signature];
…
//set the variables we're going
[variables appendString:finalSig];
Turns out that NSString * signature = [NSString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]]; requires a null terminated string and my string was not. Anyway this was a more effective way to create the string:
NSData *myRequestData = [ NSData dataWithBytes: [ variables UTF8String ] length: [ variables length ] ];

Resources