I am trying to embed a link in a twee sent out from iPhone. The URL ends with a closing parentheses. That parentheses gets dropped and causes the t.co link to fail. I have tried encoding, tagging with href. Nothing seems to bring that closing parentheses into the resulting URL. See what I tried last, it failed for having too many characters. Why didn't it get shortened?:
if (tweetsEnabled && twitToSendTo != nil) {
// Build the string
NSString *mapURL = [NSString stringWithFormat:#"http://maps.google.com/maps?q=%#,%#+(%#)",newLogEvent.lattitude,newLogEvent.longitude,eventString];
NSString *encodedURL = [mapURL encodeString:NSUTF8StringEncoding];
NSString *tweetString = [NSString stringWithFormat:#"%#\n<a href>=\"%#\"></a>",note,encodedURL];
NSLog(#"%#",tweetString);
// Send it
[self performSelectorOnMainThread:#selector(postToTwitterWithString:) withObject:tweetString waitUntilDone:NO];
}
In its simplest form,without encoding, without the tags and without the +(%#), the link works. It displays as a t.co shortened link and brings up the webpage as intended. But I need the string in the parentheses to give text to the label and it seems it should be very easy to get that in.
Here is the output of the NSLog:
2012-08-14 09:57:43:551 app[2683:34071] -[logger insertLogEvent:withLocation:isArrival:] [Line 641] Arrival logged for Home
<a href>="http%3A%2F%2Fmaps.google.com%2Fmaps%3Fq%3D26.17071170827948%2C-80.16628238379971%2B%28Arrival%29"></a>
This worked:
// Build the string
NSString *mapURL = [NSString stringWithFormat:#"http://maps.google.com/maps?q=%#,%#+%%28%#%%29",newLogEvent.lattitude,newLogEvent.longitude,eventString];
NSString *tweetString = [NSString stringWithFormat:#"%#\n%#",note,mapURL];
I am not now encoding the entire string but only the parenthesis. This handy post, How to add percent sign to NSString , is where I found the correct way to get the percent signs in for the encoding.
Related
Hi i'm doing my assignment and I want to get some information from this website:. I used TFHpple.h from Raywenderlich tutorial .Every thing went fine until I try to get the view count(this number: 8.024.835 ) but in my code it return this number "
" I NSLOG its element.raw then I see this code:
<p>
Số lượt xem:
<span class="color-fuchsia" id="PageViews"/>
Yêu thích:
<span class="color-hotpink" id="LikeCount"/>
</p>
but when I use firebug to its html, it display like this:
<p>
Số lượt xem:
<span id="PageViews" class="color-fuchsia">8.024.835</span>
Yêu thích:
<span id="LikeCount" class="color-hotpink">1.565</span>
</p>
How to get the correct value please help me.
this is my code to parse and nslog the html.
-(void) GetBookViewCount{
NSURL *url = [NSURL URLWithString:#“http://blogtruyen.com/truyen/conan”];
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple *parser = [TFHpple hppleWithHTMLData:htmlData];
NSString* XpathQueryString = #"//div[#class='description']/p";
NSArray *Nodes = [parser searchWithXPathQuery:XpathQueryString];
for (TFHppleElement *element in Nodes) {
NSLog(#"%#",element.raw);
}
}
It looks like there a bunch of odd whitespace characters in between the two spans there.
This number here:
Looks like an ascii code for a symbol (though I can't find one that matches), so when you parse the code it might be breaking when you hit those characters. I'm not familiar with TFHpple.h but you may need to implement some input sanitization (stripping out those characters).
I am getting a weird error on XCODE: expected '[' error and my build fails. This is the code
[descWeb loadHTMLString:[NSString stringWithFormat:#"<html><body p style='color:black' text="#000000" face="HelveticaNeue" size="5">%</body></html>",strtemp] baseURL: nil];
This is the whole code block
[descWeb removeFromSuperview];
descWeb = [[UIWebView alloc]init];
descWeb.delegate = self;
descWeb.tag = 1;
[descWeb setOpaque:NO];
[descWeb setBackgroundColor:[UIColor clearColor]];
descWeb.frame = CGRectMake(3, 7, 314, 350);
[descWeb loadHTMLString:[NSString stringWithFormat:#"<html><body p style='color:black' text="#000000" face="HelveticaNeue" size="5">%</body></html>",strtemp] baseURL: nil];
[scrollView addSubview:descWeb];
Thank you for looking and your help
You need to add slashes to the quotation marks.
NSString *string = #"A quotation mark: \"";
NSLog(#"%#", string );
Output:
A quotation mark: "
You're mixing single and double quotes, so the stringWithFormat argument currently ends with text=", and Xcode can't balance the ['s and ]'s after this line:
[descWeb loadHTMLString:[NSString stringWithFormat:#"<html><body p style='color:black' text="#000000" face="HelveticaNeue" size="5">%</body></html>",strtemp] baseURL: nil];
Try using single quotes ' instead of double " inside your HTML.
What the others have said, about escaping the double quotes (and missing an #) is correct.
Another option though, that may keep your code cleaner and is less tedious than escaping the double quotes, is to keep all of your HTML in .html files and load the contents of those files instead.
For example, create a file in your project called desc.html with the HTML you need in there. Then change your code to:
__autoreleasing NSError* error = nil;
NSStringEncoding encoding = 0;
NSString* htmlString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"desc" ofType:#"html"] usedEncoding:&encoding error:&error];
if (!htmlString)
{
NSLog(#"Error: %#", error);
return;
}
[descWeb loadHTMLString:[NSString stringWithFormat:htmlString, strtemp] baseURL:nil];
Besides keeping your project cleaner, this also makes it easier for you or someone else (designer etc) to update the HTML without changing your code.
Basically I need to parse td(table data) from this html file.I need to get the right xpath.I am using raywenderlich as a model for this task, and here is the code I have so far.
NSURL *tutorialsUrl = [NSURL URLWithString:#"http://example.com/events];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
// 2
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
// 3
NSString *tutorialsXpathQueryString = #"This is where I need to enter my xpath to rerieve the table data";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
I have the html path to this element thanks to firebug,which I will post below.
/<html lang="en">/<body>/div id="page" class="container">/<div class="span-19">/<div id="content">/<div>/<table id=yw0 class="detail-view">/<tbody>/<tr class="even">/<td>moo</td>/
I need the text moo to be parsed. Any help will be deeply appreciated.
this is the x path I get from firebug as well, but it didn't work at all.
/html/body/div/div[4]/div/div/table/tbody/tr[2]/td
At first, you need to get substrings, where each substring contains one element that needs to be extracted:
NSArray *split = [text componentsSeparatedByString:#"<td>"];
In array "split", first object contains nothing you want, so you will not work with it anymore. Now, for each substring in this array (except first one) you need to search for substring with "/td" tag:
NSRange range = [string rangeOfString:#"</td>"];
and then remove it and everything what is behind it:
- (NSString *)substringToIndex:(NSUInteger)anIndex //you will get index by searching for "</td>" as mentioned
EDIT:
Another possibility is to use componentsSeparatedByString even instead of 2nd and 3rd step for mentioned tag and in first item of each array, you will have wanted text.
EDIT2: (whole code)
NSString* originalText = #" /<html lang=""en"">/<body>/div id=""page"" class=""container"">/<div class=""span-19"">/<div id=""content"">/<div>/<table id=yw0 class=""detail-view"">/<tbody>/<tr class=""even"">/<td>moo1</td><td>moo2</td>/";
NSArray* separatedParts = [originalText componentsSeparatedByString:#"<td>"];
NSMutableArray* arrayOfResults = [[NSMutableArray alloc] init];
for (int i = 1; i < separatedParts.count; i++) {
NSRange range = [[separatedParts objectAtIndex:i] rangeOfString:#"</td>"];
NSString *partialResult = [[separatedParts objectAtIndex:i] substringToIndex:range.location];
[arrayOfResults addObject:partialResult];
}
I have slightly altered original text to show that its really working for table with more items inside
I'm trying to parse an HTML page with a lot of tables. I've searched the net on how to parse HTML with Objective C and I found hpple. I'd look for a tutorial which lead me to:
http://www.raywenderlich.com/14172/how-to-parse-html-on-ios
With this tutorial I tried to parse some forum news which has a lot of tables from this site (Hebrew): news forum
I tried to parse the news title, but I don't know what to write in my code. Every time I try to reach the path I get, "Nodes was nil."
The code of my latest attempt is:
NSURL *contributorsUrl = [NSURL URLWithString:#"http://rotter.net/cgi-bin/listforum.pl"];
NSData *contributorsHtmlData = [NSData dataWithContentsOfURL:contributorsUrl];
// 2
TFHpple *contributorsParser = [TFHpple hppleWithHTMLData:contributorsHtmlData];
// 3
NSString *contributorsXpathQueryString = #"//body/div/center/center/table[#cellspacing=0]/tbody/tr/td/table[#cellspacing=1]/tbody/tr[#bgcolor='#FDFDFD']/td[#align='right']/font[#class='text15bn']/font[#face='Arial']/a/b";
NSArray *contributorsNodes = [contributorsParser searchWithXPathQuery:contributorsXpathQueryString];
// 4
NSMutableArray *newContributors = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in contributorsNodes) {
// 5
Contributor *contributor = [[Contributor alloc] init];
[newContributors addObject:contributor];
// 6
Could somebody guide me through to getting the titles?
Not sure if that's the option for you, but if desired table have unique id's you could use a messy approach: load that html into UIWebView and get contents via – stringByEvaluatingJavaScriptFromString: like this:
// desired table container's id is "msg"
NSString* value = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('msg').innerHTML"];
Rather than converting HTML to an attributed string, I need to convert it back to HTML. This can easily be done on Mac as can be seen here: http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/
Unfortuately, the method dataFromRange:documentAttributes: is only available on Mac via the NSAttributedString AppKit Additions.
My question is how can you do this on iOS?
Not the 'easy' way, but what about iterating through the attributes of the string using:
- (void)enumerateAttributesInRange:(NSRange)enumerationRange
options:(NSAttributedStringEnumerationOptions)opts
usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block
Have an NSMutableString variable to accumulate the HTML (lets call it 'html'). In the block, you would construct the HTML manually using strings. For instance if the text attributes 'attrs' specify red, bold text:
[html appendFormat:#"<span style='color:red; font-weight: bold;'>%#</span>", [originalStr substringWithRange:range]]
EDIT: Stumbled across this yesterday:
NSAttributedString+HTMLFromRange category from "UliKit"
(https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m)
Looks like it will do what you want.
Use the below code. it works well.
NSAttributedString *s = ...;
NSDictionary *documentAttributes = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];