Why doesn't stringByReplacingPercentEscapesUsingEncoding: convert L%C3%A9on back to Léon? - iphone

I have the following:
modifiedTitle = #"Léon";
modifiedTitle = [modifiedTitle stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", modifiedTitle);
Converted, it now shows as L%C3%A9on.
When I run the following it doesn't convert it back:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
[searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", searchText);
It still shows as L%C3%A9on.
Anyone know why?

Because stringByReplacingPercentEscapesUsingEncoding: returns a new string. Try this:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
NSString *newText = [searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", newText);

Related

Remove '\' from the string in IOS application

I am getting a url as string from json response with backslash character. I want to remove the '\' character from the url. I build up the code but it is not working. The code is here:
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#" ,encodedString);
// here encodedString is a url which is showing crctly in output and need to trim the \ character.
// NSString* str = [NSString stringWithFormat: #"encodedString"];
// str = [str stringByReplacingOccurrencesOfString:#"?" withString:#""];
// NSLog(#"Response ==> %#" , str);
encodedString = [encodedString stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"Response ==> %#" ,encodedString);
but I am not able to remove the characters.
If you want to remove the spaces and \ character, it is better to remove them from responseData.
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
responseData = [responseData stringByReplacingOccurrencesOfString:#" " withString:#""];
responseData = [responseData stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
try this:
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"\\"];
encodedString = [[encodedString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", encodedString);
Hope this will help
Try this way;
Assuming your string contains a \, in string used double as for escaping the next \
NSMutableString *string=[NSMutableString stringWithString:#"hi this i\\s good"];
//NSMutableString *string=[NSMutableString stringWithString:encodedString];
[string replaceOccurrencesOfString:#"\\" withString:#"" options:1 range:NSMakeRange(0, string.length)];
NSLog(#"%#",string);

Parsing HTML <Tag> into ios

i am Parsing HTML Tag into iOS using Hpple. i am able to parse the data where the HTML Tag is
<div id="NewsPageSubTitle">
<p><**span** hi how are you>
Using ios code:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p/span ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but in few case i don't have span, imean the string in html is accessed by tag "p" directly like:
<div id="NewsPageSubTitle">
<p>< hi how are you>
Here I am using ios code as:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but here i am getting a blank data in response.
can any one let me know how to solve the problem?
Since sometimes the para tag has span and sometimes it does not, I would suggest trying to handle that by looping over the children
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
TFHpple * tutorialsParser = [[TFHpple alloc] initWithHTMLData:data];
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageSubTitle']";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
for (TFHppleElement * element in tutorialsNodes) {
NSLog(#"%#", element);
NSLog(#"%#", [element tagName]);
NSLog(#"%#", [element attributes]);
NSLog(#"%#", [element children]);
for (TFHppleElement *childElement in [element children]) {
NSLog(#"%#", childElement);
}
}
Check with this: https://github.com/mwaterfall/MWFeedParser
This will provide the HTML Parser for iphone sdk.
More help on:
this blog and here.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"image" ofType:#"html" inDirectory:#"New Folder 2"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSString *htmlString = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
TFHpple * Parser = [[TFHpple alloc] initWithHTMLData:data];
NSString *query = #"//p";
NSArray *nodes = [Parser searchWithXPathQuery:query];
for (TFHppleElement *item in nodes)
{
NSLog(#"Title : %#", item.content);
NSLog(#"URL : %#", [item.attributes valueForKey:#"href"]);
}

Change parts of an NSString

I have a urlString that is: http://www.youtube.com/watch?v=5kdEhVtNFPo
I want to be able to change it into this: http://www.youtube.com/v/5kdEhVtNFPo
How would I go about doing that? I'm not sure if I should use the instance methods substringWithRange: or substringFromIndex:
I tried this which removes the first part and just leaves the video id (it removes http://www.youtube.com/watch?v=) now I just need to add http://www.youtube.com/v/ to the start of the string.
NSString *newUrlString = [urlString substringFromIndex:31];
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"v/"];
Please note that this only works as long as the URL won't contain more instances of the string "watch?v=".
I'll propose a different way that may be more flexible on the inputs you give it:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:#"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:#"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:#"v"]) {
newURLString = [NSString stringWithFormat:#"%#://%#:%#/%#/%#", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
To be flexible enough, you could use NSRegularExpression:
NSString *str = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = #"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = #"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(#"Replaced: %#", newStr);
Another alternative :
NSString *str3 = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:#"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:#"v/"];
NSLog(#"%#",outputString);
}

Cocoa error 256, When using initWithContentsOfURL:

i getting data from my site:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
contents have Cocoa error 256. where i wrong?
The issue is in Hebrew characters, you should html-escape them, also try request with English characters instead, to see if it works
- (void)yourMethod
{
NSString *name = #"שימרגוליס";
name = AFURLEncodedStringFromStringWithEncoding(name, NSUTF8StringEncoding);
NSString *website = [NSString stringWithFormat:#"http://www.ba-cafe.com/fbconnect.php?email=%#&name=%#&pass=SwHyK17!",#"email#mail.com",name];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
}
Where AFURLEncodedStringFromStringWithEncodingis a function from AFNetworking framework
Check the Console log for NSLog(#"%#", website);
You will see something like this:
http://www.mysite.com/fbconnect.php?email=thetrimmedname&name=emailaddress&pass=***
So do this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", [jsonObject objectForKey:#"email"], nameTrimmmed ];
instead of this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
This is because of the dot in the email address.
Look right here:
Error while trying to access Google translate with NSURL

.Pls file parsing

Iam creating and radio application in which i have to check the authentication and after successful login i get .pls file in which there is actual url which has to be played so
anybody know how to parse .pls file and get the url inside the .pls file.
In my case I have a WWEMAC.pls file in main bundle. In which more than one url exist and I have to extract only those URLs and add them in array in string format. Following code worked for me.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"WWEMAC" ofType:#"pls"];
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&errorReading] componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
NSString *completeDataInStr = [linesOfText componentsJoinedByString:#" "];
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detector matchesInString:completeDataInStr options:0 range:NSMakeRange(0, [completeDataInStr length])];
for (NSTextCheckingResult *match in matches)
{
NSString *str = [NSString stringWithFormat:#"%#",match.URL];
NSLog(#"URL str = %#",str);
}
return matches;