Objective-C URL encoding issues - objective-c

I am creating a URL string like so:
[Items appendString:[object objectForKey:#"Items"]];
[Items appendString:#"*"];
[Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)];
//This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT
//add Items to URL
NSString *fullURL = [NSString stringWithFormat:#"https://example.com?Items=%#, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
but it returns like so:
Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT
how do I get it return like this:
%20%26%20 instead of %20&%20 for the & ?

I think the issue is that the method tries to be too clever - it only does as much as is necessary to get a legal URL and because you don't have a question mark in your string, it probably thinks it is OK to leave the ampersands in.
Try constructing the whole URL and do the escaping on the whole URL.
NSString *fullURL = [[#"https://example.com?Items=" stringByAppendingString: items]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Or perhaps use stringByAddingPercentEncodingWithAllowedCharacters:.

Try this.
fullURL=[fullURL stringByReplacingOccurrencesOfString:#"&" withString:#"%26"];
NSLog(#"fullURL: %# ...", fullURL);

Use CFURLCreateStringByAddingPercentEscapes() for getting UTF8stringencoding of characters
NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:#&=+$,/?%#[]"), kCFStringEncodingUTF8))

Related

Append variables to string in Objective-C [duplicate]

How can I combine "stringURL" and "stringSearch" together?
- (IBAction)search:(id)sender;{
stringURL = #"http://www.websitehere.com/index.php?s=";
stringSearch = search.text;
/* Something such as:
stringURL_ = stringURL + stringSearch */
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringURL_]]];
}
Philippe gave a good example.
You can also use plain stringWithFormat: method.
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This way you can manipulate string even more by putting somethig inbetween the strings like:
NSString *combined = [NSString stringWithFormat:#"%#/someMethod.php?%#", stringURL, stringSearch];
NSString* combinedString = [stringUrl stringByAppendingString: search.text];
NSString * combined = [stringURL stringByAppendingString:stringSearch];
Instead of stringByAppendingString:, you could also use
NSString *combined = [NSString stringWithFormat: #"%#%#",
stringURL, stringSearch];
This is especially interesting/convenient if you have more than one string to append. Otherwise, the stringbyAppendingString: method is probably the better choice.
You can use stringByAppendingString:
stringURL = [#"http://www.websitehere.com/index.php?s="
stringByAppendingString:search.text];
If you want to have some control about the format of the parameter you should assemble
your URL string with
[NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text]
This solution is charming because you can append almost anything which can be inserted into a printf-style format.
I would not have given the answer of such general question.
There are many answers of same type question have already given. First find the answer of your question from existing question.
NSString* myURLString = [NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text];

componentsSeparatedByString:#"\r\n" does not work on NSString

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
NSString *URLString = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray *temp = [URLString componentsSeparatedByString:#"\r\n"];
return YES;}
that does not split the string, though preview shows \r\n are still in the string.
Any suggestions?
input URL sample- myapp://bla\r\nbla
here is string after replacing % esc and splitting by '\r\n':
here is url before replacing % esc:
I suspect replacing percent escapes has got to do something with it.
As per Eduardo but closer to your code, the following:
NSString *URLString = #"myapp://bla\r\nbla";
NSArray *temp = [URLString componentsSeparatedByString:#"\r\n"];
NSLog(#"%#", temp);
Outputs:
2014-03-20 12:05:17.247 Untitled 3[437:507] (
"myapp://bla",
bla
)
Is it possible your incoming string contains the literal four-character sequence \r\n, which would be written as #"\\r\\n" rather than the sequence of two control codes, \r\n?
Try the following
NSArray *temp = [URLString componentsSeparatedByString:#"\\r\\n"];
Your initial URLString can't contain CR LF. It simply contain two-symbol literals '\r' and '\n'
Does it shows "\r\n" in preview? This works:
NSLog(#"%#", [#"abc\r\ndef" componentsSeparatedByString:#"\r\n"]);
If your code does not work, are you sure your string doesn't contains "\\r\\n" instead of "\r\n"?
EDIT: SO "unescaped" my double-slashes

in objective-c is there any easy way to add backslash in front of special characters?

Note: Not sure why this is marked as duplicate as I clearly stated that I don't want to use stringByReplacingOccurrencesOfString over and over again.
I have a question regarding the special character filename.
I have implemented a program, so that when you open a file or multiple files, the program will read all these filenames and local path and store them into the NSMutableArray. This part works perfectly without a problem.
My program also need to use NSTask to manipulate these files. However, the problem is, sometimes filename will contain special characters, for example, /Users/josh/Desktop/Screen Shot 2013-03-19 at 2.05.06 PM.png.
I have to replace space with backslash and space
NSString *urlPath = [[self url] path];
urlPath = [urlPath stringByReplacingOccurrencesOfString:#"(" withString:#"\\("];
urlPath = [urlPath stringByReplacingOccurrencesOfString:#")" withString:#"\\)"];
urlPath = [urlPath stringByReplacingOccurrencesOfString:#" " withString:#"\\ "];
to: /Users/josh/Desktop/Screen\ Shot\ 2013-03-19\ at\ 2.05.06\ PM.png
so that I can manipulate the file properly.
Same for the ( and ). I also need to add backslash before that.
but there are too many special characters. ie.
/Users/josh/Desktop/~!##$?:<,.>%^&*()_+`-={}[]\|'';.txt
I need to change to:
/Users/josh/Desktop/\~\!#\#\$\?\:\<\,.\>\%^\&\*\(\)_+\`-\=\{\}\[\]\\\|\'\'\;.txt
and not to mention other special characters (ie. accent)
Is there any easy way to put a backslash in front of each special character, as I don't want to keep calling stringByReplacingOccurrencesOfString over and over again.
As described in NSTask's documentation for the setArguments: method, there should be no need to do special quoting:
Discussion
The NSTask object converts both path and the strings in
arguments to appropriate C-style strings (using
fileSystemRepresentation) before passing them to the task via argv[].
The strings in arguments do not undergo shell expansion, so you do not
need to do special quoting, and shell variables, such as $PWD, are not
resolved.
If you feel it is necessary, can you please provide some examples of the commands you want to run in the NSTask?
[UPDATE]: I see in the comments that you indeed are using the NSTask to execute a bash shell with -c, which I had wondered about. I've generally used NSTask to execute the command directly rather than going through the shell, like this:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/bin/ls"];
[task setArguments:[NSArray arrayWithObjects:#"-l", self.url.path, nil]];
Can you give a more accurate example of the actual command you want to run? For example, are you piping a series of commands together? Perhaps there might be an alternate way to achieve the same results without the need for using the bash shell...
I think you may be able to use an NSRegularExpressionSearch search.
It would look something like this
+ (NSString *) addBackslashes: (NSString *) string
{
// First convert the name string to a pure ASCII string
NSData *asciiData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *asciiString = [[[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding] lowercaseString];
// Define the characters that we will replace
NSString *searchCharacters = #"PUT IN ALL OF YOUR SPECIAL CHARACTERS HERE";
// example NSString *searchCharacters = #"!##$%&*()";
// replace them
NSString *regExPattern = [NSString stringWithFormat:#"[%#]", searchCharacters];
string = [asciiString stringByReplacingOccurrencesOfString:regExPattern withString: [NSString stringWithFormat:#"\\%#", regExPattern] options:NSRegularExpressionSearch range:NSMakeRange(0, asciiString.length)];
return string;
}
you could maintain a set of strings that need to be escaped and use NSScanner to build the new string by iterating the the source string and each time a problematic character is found u first add \\ to a destination string and continue coping the next chars.
NSString *sourceString = #"/Users/josh/Desktop/\"Screen Shot\" 2013-03-19 at 2\\05\\06 PM.png";
NSMutableString *destString = [#"" mutableCopy];
NSCharacterSet *escapeCharsSet = [NSCharacterSet characterSetWithCharactersInString:#" ()\\"];
NSScanner *scanner = [NSScanner scannerWithString:sourceString];
while (![scanner isAtEnd]) {
NSString *tempString;
[scanner scanUpToCharactersFromSet:escapeCharsSet intoString:&tempString];
if([scanner isAtEnd]){
[destString appendString:tempString];
}
else {
[destString appendFormat:#"%#\\%#", tempString, [sourceString substringWithRange:NSMakeRange([scanner scanLocation], 1)]];
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
NSLog(#"\n%#\n%#", sourceString, destString);
result:
/Users/josh/Desktop/Screen Shot 2013-03-19 at 2.05.06 PM.png
/Users/josh/Desktop/Screen\ Shot\ 2013-03-19\ at\ 2.05.06\ PM.png

Extracting an NSString from both Parenthesis and Quotations

I have a string that is returned from a WebAPI call that looks like this:
(
"username#domain.com"
)
As a workaround, I am trying to extract just the email address i.e. username#domain.com
I am not sure what the best approach to do this is as I'm extracting the data within the parenthesis and the quotations.
Any pointers (no pun intended) are appreciated.
The easiest way is to use stringByTrimmingCharactersInSet::
NSString *source = /* your source */;
NSCharacterSet *charSet =
[NSCharacterSet characterSetWithCharactersInString:#" \"()\n"];
NSString *email = [source stringByTrimmingCharactersInSet:charSet];
Harder one involves NSRegularExpression.
An even easier one, if you know that the string always starts with (" and ends by "):
NSString *email = [response substringWithRange:NSMakeRange(2, [response length] - 4)];

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.