stringByReplacingOccurrencesOfString not functioning correctly - html

I created a small app which will get html from website and turn that into string. Now I want to delete some text from that string but it is not deleting that text. Here is my code that I wrote.
-(void)dk {
NSString *myURLString = #"http://bountyboulevardss.eq.edu.au/?cat=3&feed=rss2";
NSURL *myURL = [NSURL URLWithString:myURLString];
NSError *error = nil;
NSString *myHTMLString = [NSString stringWithContentsOfURL:myURL encoding: NSUTF8StringEncoding error:&error];
[myHTMLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if (error != nil)
{
NSLog(#"Error : %#", error);
}
else
{
}
[myHTMLString stringByReplacingOccurrencesOfString:#"<title>Bounty Boulevard » » Latest News</title>" withString:#""];
NSString *newString = myHTMLString;
NSScanner *scanner = [NSScanner scannerWithString:newString];
NSString *token = nil;
[scanner scanUpToString:#"<title>" intoString:NULL];
[scanner scanUpToString:#"</title>" intoString:&token];
headline.text = token;
NSLog(#"%#", myHTMLString);
}
Like you see in the beginning I try to delete the first title in the text and then I scan for the title I still keep getting the title I deleted. I checked in log and it is not deleting. I don't know what I am doing wrong. Sorry guys if this is really easy. Thanks for helping.

Not an Objective-C expert myself, but I guess you need to assign the replaced value back to the variable:
myHTMLString = [myHTMLString stringByReplacingOccurrencesOfString:#"<title>Bounty Boulevard » » Latest News</title>" withString:#""];
So, in general the idiomatic way to replace a string and keeping the result in the same variable is:
str = [str stringByReplacingOccurrencesOfString....];
This is confirmed by the stringByReplacingOccurencesOfString doc which states that this method "returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.".

Related

how to get the html format data in json in objective-c

The HTML data contains multiple lines with different anchor tags. The body on JSON like below format:
"description": "<div><b>Hiiiiiii,</b> officially known as <b>Hiiiiiii,</b>
Well you need this method to strip down the HTML tags from the string.
First you get the whole string in a variable like NSSting *wholeHtml = [jsonDictionary objectForKey:#"description"];.
-(NSString *) stringByStrippingHTML:(NSString *)inputString {
NSRange r;
NSString *toReturn;
while ((r = [inputString rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
toReturn = [inputString stringByReplacingCharactersInRange:r withString:#""];
return toReturn;
}
Then you call this method like this : NSString *outputString = [self stringByStrippingHTML:wholeHtml]; and you will get the required string in the variable outputString. You can also create a catagory of NSString and that would make your work more easy.
1 Take a string and store JSON key's description value in it .
eg: NSString str=[JSON value for key :#"description"];
2 Now Take a WebView and give this string to it .
eg:UIWebView webView = [[UIWebView alloc] init];
[webView loadHTMLString:str baseURL:nil];

Converting NSString to NSData for use in XCODE

I am getting data from the Yummly API and I would like to use it as though it were serialized JSON data. However, it is currently a string, and I cannot figure out how to turn it to data correctly. The code is as following:
NSString *searchParameters = #"basil"; //should be from text box
//NSError *error1 = nil;
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSString *searchResults = [NSString stringWithContentsOfURL:searchURL encoding:NSUTF8StringEncoding error:nil];
// Here, the search results are formatted just like a normal JSON file,
// For example:
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
// however it is a string, so I tried to convert it to data
NSData *URLData = [searchResults dataUsingEncoding:NSUTF8StringEncoding];
URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Somewhere over the last four lines, it didn't do what it was supposed to and there is no data in the data object. Any advice or quick hints in the right direction are much appreciated! Thank you1
Look at the error being returned from the NSJSONSerialization object like
NSError *error;
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
This might give you a hint of what's wrong. This should work though.
And why exactly are you doing URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];? You don't need to copy the data, if that's why you're doing that.
Plus, it seems like you're assuming to get an array as the top level object (judging by
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
but this is a dictionary. Basically you probably want a dictionary, not array. This it should be
/* {
"totalMatchCount":777306,
"facetCounts":{}
}
*/
But the error getting returned will tell you that.
It looks like you're over-complicating things a bit. You do not need to bring in this data as an NSString at all. Instead, just bring it in as NSData and hand that to the parser.
Try:
NSString *searchParameters = #"basil"; //should be from text box
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSData *URLData = [NSData dataWithContentsOfURL:searchURL];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Note that you'll want to verify that the parsed JSON object is indeed an array as expected, and is not/does not contain [NSNull null].

iOS Parsing JSON Woes

I've been bashing my head against a wall for a bit.
I have a rails back-end that is returning JSON to my iOS app. I'm using rails' default return for rendering my object in JSON for me automatically. I'm having trouble with the errors it returns.
The JSON I get for errors is {"errors":{"email":["can't be blank"],"password":["can't be blank"]}}.
I use ASI for handling the request.
-(void) requestFinished:(ASIFormDataRequest *)request {
NSDictionary *data = [[request responseString] JSONValue];
Doing the above code make data become:
{
errors =
{
email = (
"can't be blank"
);
password = (
"can't be blank"
);
};
}
Now this gives me issues trying to parse it out. I'd like to be able to access each element of errors, and its associated value.
When I try to loop through the elements, I do something like:
for (NSDictionary *error in [data objectForKey:#"errors"])
This will give me email and password, but they are of type __NSCFString, not NSDictionary. I haven't been able to find a way to get the value for either email or password. Does anyone have an idea on how to parse this out?
Thanks!
This should work, note that response has the same structure than your 'data' NSDictionary.
NSDictionary *fields = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSArray alloc] initWithObjects:#"one", #"two", nil],
#"A",
[[NSArray alloc] initWithObjects:#"three", #"four", nil],
#"B",
nil];
NSDictionary *response = [[NSDictionary alloc] initWithObjectsAndKeys:fields, #"errors", nil];
NSLog(#"Dictionary: %#", [response objectForKey:#"errors"]);
for (NSString *field in [response objectForKey:#"errors"])
for (NSString* error in [response valueForKeyPath:[NSString stringWithFormat:#"errors.%#", field]])
NSLog(#"%# %#", field, error);
The output will look like this:
Dictionary: {
A = (
one,
two
);
B = (
three,
four
);
}
A one
A two
B three
B four
Well i dont have Mac right now but i'm trying to help you if it doesnt work let me know i will correct it tomorrow.
-(void) requestFinished:(ASIFormDataRequest *)request
{
NSArray *data = [[request responseString] JSONValue];
NSDictionary *dict = [data objectAtIndex:0];
NSDictionary *dict2 = [dict valueForKey:#"errors"];
NSLog(#"email = %#, password = %#",[dict2 valueForKey:#"email"], [dict2 valueForKey:#"password"]);
}

If Statement Always Going to Else Method?

The following code works almost perfectly. I am connecting to a mysql server on my localhost from Xcode using php in the middle. This in the end will be a login system:
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/Check.php?user=%#&pass=%#",txtName.text,passName.text];
// to execute php code
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
NSError *e;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
// to receive the returned value
NSString *strResult = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#",strResult);
NSString *success = #"Success";
if ([strResult isEqualToString:success]) {
NSLog(#"I realize that the two strings are the same");
}
else {
NSLog(#"The two strings are not the same");
}
The strResult prints out in the debugger the following items that I am telling the php file to echo back to me for the different conditions, (if the username and password is right or wrong)
However, for some reason the if statement part of the code is always going to the else method even though in the output it specifically says that the string, strResult, is containing the word "Success".
This is so irritating because I can see that both strings, (strResult and success), are equal to each other but for some reason Xcode cannot.
Your strResult might contain whitespace at the end. Try logging like this to get a hex dump of the characters in the string:
NSLog(#"strResult = %#", [strResult dataUsingEncoding:NSUTF8StringEncoding]);
NSLog(#"success = %#", [success dataUsingEncoding:NSUTF8StringEncoding]);
OR
NSLog(#"%u",strResult.length);
If it is a whitespace problem, you can trim it using the answer here: What's the best way to trim whitespace from a string in Cocoa Touch?

how to escape string for UIWebView?

I pull json data from a server. It contains a dictionary with text that I insert into a html template.
How do I properly escape this string?
NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json someEscapeMethod]; /////// HOW TO ESCAPE THIS ?
NSString* script = [NSString stringWithFormat:#"process('%#')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];
I currently do like this, but I'm not sure wether the escaping is sufficiently
NSString* json_escaped = [json stringByReplacingOccurrencesOfString:#"'" withString:#"\\'"];
I now encode it this way, but the overhead is huge.
NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* script = [NSString stringWithFormat:#"process('%#')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];
And decode it in javascript like this
function process(json_escaped) {
var json = decodeURIComponent(json_escaped);
alert('json: ' + json.toString());
}
I'm still looking for a better solution with less overhead.
Update
I have recently learned that there exists several frameworks for bridging objective-c with javascript.
The "Escaping Characters in a String" section of NSRegularExpression may work.