how to replace space with dash in objective-c? - ios

Hey folkks I'm working with an api that search about movies now the problem is when i type single word in UISearchBar it works but when I type space for another word it dose'nt work.Near query=%# when i type single word it works but when I type another word with space it won't
NSString *movieName=searchBar.text;
NSString *movieString = [NSString stringWithFormat:#"https://api.themoviedb.org/3/search/movie?query=%#&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

You don't need to replace Space with Dash you new to URL Encode your string
Below is an example of encoding your string to URL Encode
NSString *movieName=searchBar.text;
movieName = [movieName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];
NSString *movieString = [NSString stringWithFormat:#"https://api.themoviedb.org/3/search/movie?query=%#&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

Use
formattedString = [originalString stringByReplacingOccurrencesOfString:#" " withString:#"-"];

Please refer this code.
NSString *movieName=searchBar.text;
NSString* replacedMovieName = [movieName stringByReplacingOccurrencesOfString:#" " withString:#"_"];
Hope this helps.

No need replace space with dash, need to add Percent Escapes in string before creating NSURL.
Use NSString class method:
-(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
Like,
NSString *movieName=searchBar.text;
//This is what you need
movieName=[movieName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *movieString = [NSString stringWithFormat:#"https://api.themoviedb.org/3/search/movie?query=%#&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];
OR
Alternately you can do following(Not best approach):
NSString *movieName=searchBar.text;
//This is what you need
movieName = [movieName stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *movieString = [NSString stringWithFormat:#"https://api.themoviedb.org/3/search/movie?query=%#&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

NSString *movieName=searchBar.text;
movieName = [movieName stringByReplacingOccurrencesOfString:#" " withString:#"-"];//use vice-versa
NSString *movieString = [NSString stringWithFormat:#"https://api.themoviedb.org/3/search/movie?query=%#&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

Related

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

string modifications are not working?

This is my code and in my url string white spaces are not encoded by the code
NSString *str = item.fileArtPath;
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set];
[str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *urlString = [NSURL URLWithString:str];
for below string:
http://xx.xx.xx.xxx:xx/xx/xx/xx/xxx/Audio Adrenaline.jpg
^^^^^^^^^^^^^^^^^^^^
The white space after Audio is not converted to %20 after I used string replacement. And in Debugging urlString is nil why so?
From the NSString Class Reference
Returns a new string made from the receiver by replacing all
characters not in the specified set with percent encoded characters.
Meaning it doesn't permute the instance it's called on. You need to say something like str = [str stringByAddingPercentEncodingWithAllowedCharacters:set]; Same with [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Recall that NSString is immutable. Calling methods stringBy... returns the modified string, rather than modifying the original one. Therefore your code should be rewritten as follows:
str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *search = [searchBar.text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];

How can I remove CDATA from NSString programmatically?

Here is my string
<![CDATA[https://2134114018c95327dd42-9b7f7e536ddb2ed4dd0d87c2f0e46492.ssl.cf2.rackcdn.com/340x340/8663034_19227_$2014_03_28_10_30_34_3934.JPG]]>
I am stuck at this point. I just want to remove CDATA from this string. Is there amy quick work around for that ?
[str stringByReplacingOccurrencesOfString:#"CDATA" withString:#""];
this should help
EDIT:
NSString *haystack = #"<![CDATA[https://2134114018c95327dd42-9b7f7e536ddb2ed4dd0d87c2f0e46492.ssl.cf2.rackcdn.com/340x340/8663034_19227_$2014_03_28_10_30_34_3934.JPG]]>";
NSString *prefix = #"<![CDATA[";
NSString *suffix = #"]]>";
NSRange needleRange = NSMakeRange(prefix.length,
haystack.length - prefix.length - suffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
Needle is your url path

IOS NSString get characters before '#"

for example i have string like this:
NSString *one = B3#This is the first string
NSString *two = 1#This is the second string
How can i get the "B3" and "1" Character only (using objective C)
Thanks..
Turns out this is one way to do it:
NSRange range = [one rangeOfString:#"#" options:NSBackwardsSearch];
NSString *newString = [one substringToIndex:range.location];
Thanks for all the answers.
NSString* one = #"B3#";
NSString* two = #"1#";
NSString* result = [one stringByReplacingOccurrencesOfString:#"#" withString:#""];
NSString* result_2 = [two stringByReplacingOccurrencesOfString:#"#" withString:#""];
//if you need to marge
NSString* tot = [NSString stringWithFormat:#"%#%#",result,result_2];

editing occurrences is not working

i am trying to get the path to a certain file
and then open it in a webview. so i need to replace each space by '%20'
NSString *test=#"filename";
NSString *finalPath12 = [test stringByAppendingString:#".pdf"];
NSString *path1 = [[NSBundle mainBundle] bundlePath];
NSString *finalPath1 = [path1 stringByAppendingPathComponent:finalPath12];
NSString *file =#"file://";
NSString *htmlfilename1 = [file stringByAppendingString:finalPath1];
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
any string is working except #"%20".
this works perfectly for exemple:
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"string"];
but i need the #"%20". What am i missing ? Thanks
There is already [NSString stringByAddingPercentEscapesUsingEncoding:] (reference) for that very purpose.
However in your case, as you want a URL, you can replace all the lines in your question with:
NSURL *url = [[NSBundle mainBundle] urlForResource:#"filename" withExtension:#"pdf"];
You need to use #"%%20".
As first % is treated as escape/wild character.
Or use
stringByAddingPercentEscapesUsingEncoding:

Resources