I have HTML tags and entities in JSON, I don't know how to display it in my app. I tried removing new lines, I tried decoding html entities but nothing worked.
Below is an example of JSON I have:
{"Jobdesc":[{"jobid":"12281","job_title":"IOS Developer for Noida Location Job","job_desc":"<p><strong>Job Description</strong><br />
Dear Candidate <br />
I have an opening for IOS Developer for Noida Location for leading IT company. pli\ease find the JD below-<br />
JOB DESCRIPTION :-<br />
Industry :- IT <br />
Experience :- Min 1 Year<br />
Position :- IOS Developer<br />
Location :- Noida<br />
<br />
<strong>Job Responsibility :- </strong><br />
<br />
Design and build advanced applications for the iOS platform<br />
Collaborate with cross-functional teams to define, design, and ship new features</p>
<p>Working experience in iOS development<br />
Have published one or more iOS apps in the app store<br />
A deep familiarity with Objective-C and Cocoa Touch<br />
Experience working with iOS frameworks such as Core Data, Core Animation, Core Graphics and Core Text<br />
If you are interested in the above mentioned JD kindly share your resume with me and contact me on :-<br />
<br />
Thanks And Regards<br />
Pal Mittal<br />
Contact no :- 9200272001<br />
Email ID :- parul#india-shine.in<br />
<br />
<br />
Functional Area: Web / Mobile Technologies <br />
Industry: IT - Software <br />
Skills: IOS ipad <br />
Other Skills: IOS Developer Iphone Developer IOS Application Developer iphone Application Developer iphone<br />
<br />
Recruiter details <br />
Company Name: Employment Solution<br />
Email: pal#ishine.in<br />
Telephone: 9200272001</p>
","job_role":"IOS Developer","job_exp":"1-4 year","job_education":"MCA","job_location":"Delhi","job_address":"Delhi","j ob_company_name":"India Shine Employment Solution","job_company_url":"www.india- shine.in","job_company_email":"kumar178dilip#gmail.com","job_status":""}]}
Actually there are 2 approaches
Approach 1
Code
#interface NSAttributedString (HTML)
+ (instancetype)attributedStringWithHTMLString:(NSString *)htmlString;
#end
#implementation NSAttributedString (HTML)
+ (instancetype)attributedStringWithHTMLString:(NSString *)htmlString
{
NSDictionary *options = #{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute :#(NSUTF8StringEncoding) };
NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
#end
Usage
NSString *cleanString = [[NSAttributedString attributedStringWithHTMLString:question.title] string];
Approach 2
Check out NSString category for XMLEntities. There's methods to decode XML entities (including all HTML character references), encode XML entities, stripping tags and removing newlines and whitespace from a string:
- (NSString *)stringByStrippingTags;
- (NSString *)stringByDecodingXMLEntities; // Including all HTML character references
- (NSString *)stringByEncodingXMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
You can use UIWebView and show it like this:
let htmlString = //HTML String
webView.delegate = self
webView.scalesPageToFit = true
webView.contentMode = .scaleAspectFit
webView.loadHTMLString(htmlString, baseURL: nil)
Related
I'm trying to embed a booking system widget to my bolt homepage (the one and only homepage, using base-2018 theme). I paste it into the Content window, selecting Source first. Bolt seems to interpret what is going on, as various tags and IDs are highlighted in the code.
The widget code is roughly so:
<div id="bokun [blabla]">Loading...</div>
<p><script type="text/javascript"><br />
var w15;<br />
(function(d, t) {<br />
var host = 'widgets.bokun.io';<br />
var frameUrl = 'https://' + host + '/widgets/15';<br />
var s = d.createElement(t), options = {'host': host, 'frameUrl': frameUrl, 'widgetHash':'w15', 'autoResize':true,'height':'','width':'100%', 'minHeight': 0,'async':true, 'ssl':true, 'affiliateTrackingCode': '', 'transientSession': true, 'cookieLifetime': 43200 };<br />
s.src = 'https://' + host + '/assets/javascripts/widgets/embedder.js';<br />
s.onload = s.onreadystatechange = function() {<br />
var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;<br />
try {<br />
w15 = new BokunWidgetEmbedder(); w15.initialize(options); w15.display();<br />
} catch (e) {}<br />
};<br />
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);<br />
})(document, 'script');<br />
</script></p>
I have only edited out the unique ID this widget has. Otherwise, this is copied from the provider and works on my current Wordpress site...ALTHOUGH when I paste it into Wordpress, the editor notifies me that "there's something wrong" and offers me to correct it.
How do I insert this? Do I need to create a .js file and reference it in compliance with Twig standards and if so, how do I? I should also note that the widget will redirect to a different page within the same site once you press something within it. Thank you.
Bolt version: 3.6.5
You need to add every tag and attribute that you need into the `config.yml.
I used the code below but it only gets me the text between one, when it should get me the text between 5 <p> and </p>
> var myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
while let idRange = myHTMLString.range(of: "post-51"){
myHTMLString=myHTMLString.substring(from: idRange.upperBound)
if let paraRange = myHTMLString.range(of: "<p>"){
myHTMLString=myHTMLString.substring(from: paraRange.upperBound)
if let paraCloseRange = myHTMLString.range(of: "</p>"){
HTMLData = myHTMLString.substring(to: paraCloseRange.lowerBound)
textViewer.text = HTMLData
myHTMLString = myHTMLString.substring(from: paraCloseRange.upperBound)
}else{
//Handle paragraph close tag not found
print("Handle paragraph close tag not found")
}
}else{
//Handle paragraph start tag not found
print("Handle paragraph start tag not found")
}
}
The full HTML string is:`
<!-- main content -->
<div id="content" class="main-content-inner col-sm-12 col-md-9">
<header>
<h1 class="page-title">Community</h1>
</header>
<article id="post-51" class="post-51 page type-page status-publish hentry">
<!-- .entry-header -->
<div class="entry-content">
<h1>Your Experience, Your Programs</h1>
<p>The Purdue Honors College is dedicated to providing meaningful opportunities to enhance the honors student experience. We are building an interdisciplinary community of scholars by adding value through specialized programming and events that are connected to our pillars. The Honors College strives to create an environment in which every student can feel connected, learn, and grow as they each pursue greatness. To reach your full potential in the Honors College, students should attend at least three honors programs per semester outside of the regular curriculum requirements. We invite you to be a part of one of our many upcoming events as we ignite the imagination of our community and forge the future of our college.</p>
<hr />
<h3>Events Calendar</h3>
<p>The Honors College hosts events to keep students engaged with their peers and the Honors College faculty.</p>
<p>Click here to learn more about upcoming events in the Honors College.</p>
<hr />
<h3>Honors College and Residences</h3>
<p>The new 324,000-square-foot Honors College and Residences is the first of its kind in the state of Indiana. It encourages scholarship and connects students with faculty while being emblematic of the Mission of the Purdue Honors College: from the locally sourced building materials to LEED certification and interactive learning spaces.</p>
<p>Click here to learn more about the new Honors College and Residences buildings.</p>
<hr />
<h3>Honors Network News</h3>
<p>Click here to view the Honors Network News archive.</p>
<hr />
<h3>News</h3>
<p>Stay up to date with news about the Honors College. Learn about the awesome things our students are doing and follow the Honors College on social media.</p>
<p>Click here to view more news about the Honors College.</p>
<hr />
<h3>Photo Gallery</h3>
<p>Click here to view photos of Honors College events.</p>
<hr />
<h3>Published Works</h3>
<p>Click here to view the published works of the Honors College.</p>
<hr />
<h3>Signature Programs</h3>
<p>Click here to learn more about Signature Programs from the Honors College.</p>
<hr />
</div><!-- .entry-content -->
</article><!-- #post-## -->
`
Change you code to this to loop though all after you find the id. Take a look at my comment that it's very import to break the while loop after certain condition is met.
var myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
if let idRange = myHTMLString.range(of: "post-51"){
myHTMLString=myHTMLString.substring(from: idRange.upperBound)
while let paraRange = myHTMLString.range(of: "<p>"){
myHTMLString=myHTMLString.substring(from: paraRange.upperBound)
if let paraCloseRange = myHTMLString.range(of: "</p>"){
HTMLData = myHTMLString.substring(to: paraCloseRange.lowerBound)
textViewer.text = HTMLData
//AFTER YOU GET THE NEEDED INFORMATION, DO A break HERE to get out of while loop or you will loop through all <p>
myHTMLString = myHTMLString.substring(from: paraCloseRange.upperBound)
}else{
//Handle paragraph close tag not found
print("Handle paragraph close tag not found")
}
}
}else{
print("Handle id not found")
}
I think that using an off-screen web view to temporarily load the HTML and retrieve the contents you're after is not out of the question. Here's an example of how to do that:
class ViewController: UIViewController {
// Declared as a property of the class to ensure it is not freed
// from memory (because we're not adding it to the view hierarchy).
let webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
webView.loadHTMLString("<html><head></head><body><div id=\"hello\"><p>First</p><p>Second</p><p>Third</p></div></body></html>", baseURL: nil)
}
}
extension ViewController: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
let result = webView.stringByEvaluatingJavaScript(from: "Array.prototype.slice.call(document.getElementById('hello').getElementsByTagName('p')).map(function(p) { return p.innerHTML }).join('|')")
print(result)
}
}
Note that stringByEvaluatingJavaScript can't handle array responses, so we concatenate the contents of the p tags with a pipe | character to return it to Swift. You can then split the string on the pipes to get an array back. You can change the delimiter to anything that you're sure will never be present naturally inside the p tags.
Also, Array.prototype.slice.call is just to convert the HTMLCollection that getElementsByTagName returns into an array.
Hey I am sitting in front of Spring Integration for several days without speedy progress. Hope you can help me:
My trace:
Client.Input (POJO)
-> Client.[tcp-outbound].defaultserializer
-> Server.[tcp-inbound].defaultserializer
-> Server.[http-outbound] -> transform(POJO-to-Json)
-> Spring MVC Controller : return same POJO (automatic transform to json)
-> Server -> transform(Json-to-POJO)
-> Server -> defaultserializer
-> Client -> defaultserializer
Here the configuration:
Client-Side:
<int:channel id="input" />
<int-ip:tcp-connection-factory id="client"
type="client"
host="192.168.178.28"
port="5678"
serializer="javaSerializer"
deserializer="javaDeserializer"/>
<int-ip:tcp-outbound-gateway id="outboundGateway"
request-channel="input"
connection-factory="client"
request-timeout="10000"
reply-timeout="10000"/>
Server-Side:
<int-ip:tcp-connection-factory id="connectionFactory"
type="server"
port="6000"
serializer="javaSerializer"
deserializer="javaDeserializer"/>
<int-ip:tcp-inbound-gateway id="inboundGateway"
connection-factory="connectionFactory"
request-channel="requestChannel"
reply-channel="outboundChannel"/>
<int:channel id="requestChannel" />
<int:channel id="toMvcChannel" />
<int:channel id="toTcpChannel" />
<int:channel id="outboundChannel" />
<int:object-to-json-transformer input-channel="requestChannel"
output-channel="toMvcChannel"/>
<int:header-enricher input-channel="toMvcChannel">
<int:header name="Content-Type" value="application/json" />
</int:header-enricher>
<int-http:outbound-gateway
url="http://localhost:10100/arx/dataset/receiveGateway"
request-channel="toMvcChannel"
reply-channel="toTcpChannel"/>
<int:json-to-object-transformer input-channel="toTcpChannel"
output-channel="outboundChannel"/>
SimpleGateway:
public interface SimpleGateway {
public DefinitionServer send(DefinitionServer definition);}
I cannot understand why I get the error message below on Client side ON RECEIVE (last step in the routing):
No converter found capable of converting from type [java.lang.String] to type [...DefinitionServer]
Thanks in advance!
The string stored in sqlite database with type blob. I read the data by NSData and try to get NSString from it. The string is Vietnamese string, i think it encode by UTF-8.
My Function:
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ; -> Return nil
NSString* newStr = [NSString stringWithUTF8String:[data bytes]]; -> return nil
I try to replace encoding type by each of all type and with NSASCIIStringEncoding I get string i think It's the nearest the string I want.
The string is HTML string, i show it in the UIWebview.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="Stylesheet" type="text/css" href="../images/dic.css"><div class="m5t" id="mtd_0"><div class="p10l ovf"><div><div class="w fl">absolve</div><div class="p5l fl cB">[Éb'zÉlv]</div></div></div><div><div class="p10"><div id="partofspeech_0"><div class="ub"><span>ngoại Äá»ng từ</span></div><div class="m"><span> ( </span>to absolve somebody from <span> / </span>on something <span>) bà o chữa cho ai khá»i bá» tá»i; tuyên bá» ngÆ°á»i nà o không bá» trách cứ hoặc không bá» rà ng buá»c và o má»t lá»i hứa, má»t nghÄ©a vụ; xoá tá»i, miá»n trách</span></div><div class="e">to absolve someone from blame </div><div class="em"><span> miá»n trách ai, tuyên bá» ai không có lá»i</span></div><div class="e">be absolved from the guilt </div><div class="em"><span> Äược tuyên án vô tá»i</span></div><div class="e">the court absolved the accused man <span> (</span>from all responsibility for her death <span>)</span></div><div class="em"><span> toà tuyên bá» ngÆ°á»i Äà n ông bá» cáo không có tá»i (không chá»u trách nhiá»m gì vá» cái chết của cô ấy)</span></div><div class="m"><span> tuyên bá» tha cho ai</span></div><div class="e">to absolve repentant sinners </div><div class="em"><span> tha tá»i cho những kẻ có tá»i nhÆ°ng Äã Än nÄn</span></div></div></div></div></div>`
String show in UIWebview is the same the string above.
Sorry, I don't post image. Please help me.
I'm trying to change the value of an element in a <input type="checkbox"> from null to checked.
How would I do this from objective-C (iOS application)?
Here's the relevant HTML of the page
<td align="right" width="15%" class="darkNeutral">
<input id="chk_Assignments" type="checkbox" class="ShowAll" />
<label for="chk_Assignments">Show All</label>
</td>
I was thinking I'd use POST or something, but I'm not sure how to access the element, add a checked attribute, and set the value of the attribute to "checked".
NSString *javaScript = #"document.getElementById('chk_Assignments').setAttribute('checked', 'checked');";
// Make the UIWebView method call
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];
NSLog(#"javascript result: %#", response);
If HTML page got jQuery included, the javascript could be simplified:
NSString *javaScript = #"$('#chk_Assignments').attr('checked', 'checked');";
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];
NSLog(#"javascript result: %#", response);