I want to make table in HTML and embded in objective c and after load in HTML . I am using this code i am not getting table.
myArray=[[NSMutableArray alloc]init];
array=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSString *embedHtml=#"<html><head><title>First</title><style>table , td, table , tr, th{border:1px solid #333333;padding:2px;}</style></head><body><table ><tr><th>Col1</th><th>Col2</th><th>Col3</th><th>Col4</th><th>Col5</th></tr>";
for (int i=0; i<3; i++) {
thiss= [NSString stringWithFormat:#"<tr><td>Data1</td><td> %#</td><td>Data1</td><td>Data1</td><td>Data1</td></tr>",[array objectAtIndex:i]];
[myArray addObject:thiss];
}
thiss =[embedHtml stringByAppendingString:[myArray objectAtIndex:0]];
NSString *idd=[thiss stringByAppendingString:#"</table></body></html>"];
NSLog(#"%#",idd);
[webview loadHTMLString:idd baseURL:nil];
NSLog(#"%#",thiss);
Ok so from your comment the only problem you have, is that only the first row is shown. That is because you only add the first row to the html outside of the for loop:
for (int i=0; i<3; i++) {
thiss= [NSString stringWithFormat:#"<tr><td>Data1</td><td> %#</td><td>Data1</td><td>Data1</td><td>Data1</td></tr>",[array objectAtIndex:i]];
[myArray addObject:thiss];
}
thiss =[embedHtml stringByAppendingString:[myArray objectAtIndex:0]];
not sure for what you use the array. but adding the html directly to the string inside the for loop solves your problem: (cleaned code)
// creating values with shorter literal syntax
NSArray *values = #[#"1",#"2",#"3"];
// create mutable string
NSMutableString *embedHTML = [#"<html><head><title>First</title><style>table , td, table , tr, th{border:1px solid #333333;padding:2px;}</style></head><body><table ><tr><th>Col1</th><th>Col2</th><th>Col3</th><th>Col4</th><th>Col5</th></tr>" mutableCopy];
for (int i=0; i<3; i++) {
// create row html and append it to mutable embedHTML
NSString *rowHTML = [NSString stringWithFormat:#"<tr><td>Data1</td><td> %#</td><td>Data1</td><td>Data1</td><td>Data1</td></tr>", values[i]];
[embedHTML appendString:rowHTML];
}
// finish html
[embedHTML appendString:#"</table></body></html>"];
NSLog(#"%#", embedHTML);
[webview loadHTMLString:embedHTML baseURL:nil];
Also note, that if you have a fixed width values array, using for in loop is much simpler, understandable and maintainable than using for:
for (NSString *value in values) {
// create row html and append it to mutable embedHTML
NSString *rowHTML = [NSString stringWithFormat:#"<tr><td>Data1</td><td> %#</td><td>Data1</td><td>Data1</td><td>Data1</td></tr>", value];
[embedHTML appendString:rowHTML];
}
therefore there is no redundancy and as soon as you extend the values array your code keeps working as expected.
Related
I need to be able to pull the line of HTML below from my website and display the image in the imageView I have in my Storyboard. I already Have some code on how to pull text from the same website, could I use something like the other piece of code? Of course, without the striped part, that is only to get plain text. I would just load the link to the image, but the image changes depending on the song playing. I want to try and avoid just displaying the image in a UIWebView, I would much rather prefer displaying it in a UIImageView
HTML code:
<div id="album_cover">
<img height="160px" width="160px" id="imgcover" src="Link to image changed based on the song playing" alt="Loading..."></div>
Objective C code:
-(void)viewDidLoad {
self.urlForLink = #"http://cloudrad.io/pointzeroradio/player";
NSURL *myURL = [NSURL URLWithString: [self.urlForLink stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:myURL];
[webViewForRecents loadRequest:request];
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(recentTracksText) userInfo:nil repeats:YES];
}
-(void)recentTracksText {
NSString *textForBlog = [webViewForRecents stringByEvaluatingJavaScriptFromString:#"document.getElementById('current_song').textContent;"];
// Add this step for stripping the HTML from the text you received
self.strippedTextForBlog = [self stringByStrippingHTMLFromString:textForBlog];
continuousLabel.text = self.strippedTextForBlog;
}
Based off of elio.d answer. This works great for me and loads anywhere from 30 seconds to 3 minutes. If anyone has a way that will load quickly.
-(void)getImageCover {
NSString * js = #"document.getElementById('imgcover').src;";
NSString * imgLink = [webViewForRecents stringByEvaluatingJavaScriptFromString:js];
NSURL * imgURL = [NSURL URLWithString:imgLink];
dispatch_queue_t exampleQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(exampleQueue, ^{
NSData * imgData = [NSData dataWithContentsOfURL:imgURL];
UIImage * image = [UIImage imageWithData:imgData];
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
[imageView setImage:image];
});
});
}
I suppose that your div contains just an image
If so, this is how you could implement:
-(void)getImageCover {
NSString * js = #"document.getElementById("imgcover").src;"
NSString * imgLink = [webViewForRecents stringByEvaluatingString:js];
NSURL * imgURL = [NSURL urlWithString:imgLink];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData * imgData = [NSData dataWithContentsOfURL:imgURL];
UIImage * image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(),{
[imageView setImage:image];
});
});
}
I need to save a HTML page in my app, and when characters like "€" are found, the saved file displays them wrong.
I tried several encodings but none solves this, is there any solution?
I have also tried to replace the characters for the HTML name, but it still doesn't work.
Here's my code:
NSString *HTML = [web stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML;"];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:#"%#/%#", [path objectAtIndex:0],#"code.html"];
int enc_arr[] = {
NSISOLatin1StringEncoding, // ESP
NSUTF8StringEncoding, // UTF-8
NSShiftJISStringEncoding, // Shift_JIS
NSJapaneseEUCStringEncoding, // EUC-JP
NSISO2022JPStringEncoding, // JIS
NSASCIIStringEncoding // ASCII
};
NSData *urlData= nil;
for (int i=0; i<6; i++) {
urlData = [HTML dataUsingEncoding:enc_arr[i]];
if (urlData!=nil) {
break;
}
}
[urlData writeToFile:filePath atomically:YES];
See these methods of NSString:
- (NSStringEncoding)smallestEncoding
- (NSStringEncoding)fastestEncoding
or just use method below with flag set to YES :
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
but with this one you can loose some characters.
Ok I finally did it, it's not the best way but the only one that worked for me and without using external libraries:
-(NSString*)escapeHTML:(NSString*)code{
NSMutableArray *maExceptions = [[NSMutableArray alloc] initWithObjects: #"Œ", #"œ", #"Š", #"š", #"Ÿ", #"ƒ", #"‘", #"’", #"‚", #"“", #"”", #"„", #"†", #"‡", #"•", #"…", #"‰", #"€", #"™", nil];
for (int i=0; i<[maExceptions count]; i++) {
code = [code stringByReplacingOccurrencesOfString:[maExceptions objectAtIndex:i] withString:[NSString stringWithFormat:#"&#x%x;",[[maExceptions objectAtIndex:i] characterAtIndex:0]]];
}
return code;
}
I have some html data containing some img tags as follows:
img width=500 height=400
img width=400 height=250
img width=600 height=470
Height and width always changing. I have to replace that html data. I need to replace that html data to "img with=100" using Objective-C.
I wrote these but it's not matching
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/(img\\s)((width|height)(=)([0-9]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:myhtmldata
options:0
range:NSMakeRange(0, [myhtmldata length])];
NSString *modifiedString;
if (numberOfMatches > 0)
{
modifiedString = [regex stringByReplacingMatchesInString:myhtmldata
options:0
range:NSMakeRange(0, [myhtmldata length])
withTemplate:#"img width=30"];
}
Can you help me ?
If I infer the intent correctly from your sample code, you just want to use NSRegularExpression to change the width to 30. Then:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
#autoreleasepool {
NSError *regexError = nil;
NSRegularExpressionOptions options = 0;
NSString *sampleText = #"img width=500 height=400";
NSString *pattern = #"^(img\\s+)width=\\d+(\\s+height=\\d+)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:®exError];
sampleText = [expression stringByReplacingMatchesInString:sampleText
options:0
range:NSMakeRange(0,sampleText.length)
withTemplate:#"$1width=30$2"];
printf("%s\n",[sampleText UTF8String]);
}
}
prints img width=30 height=400 to the console.
EDIT:
You change change the regular expression to (img\s+width=)\d+\s+height=\d+ which when escaped properly will be:
#"(img\\s+width=)\\d+\\s+height=\\d+"
then change the template string to #"$130". IF you make those changes to the my original code, you should match all occurrences of the img tag embedded in HTML. For example, it should change:
<html>
<body>
<img width=500 height=400>
<img width=520 height=100>
</body>
</html>
to:
<html>
<body>
<img width=30>
<img width=30>
</body>
</html>
Is this what your specs call for?
I found a different method and it's working. Here is code :
NSArray* ary = [oldHtml componentsSeparatedByString:#"<img"];
NSString* newHtml = [ary objectAtIndex:0];
for (int i = 1; i < [ary count]; i++) {
newHtml = [newHtml stringByAppendingString:[#"<img width=300 " stringByAppendingString:[[ary objectAtIndex:i] substringFromIndex:[[ary objectAtIndex:i] rangeOfString:#"src"].location]]];
}
I'm trying to reuse DTAttributedTextCell with clickable link. I could get hold of the attributedstring but I'm not sure how i can get the frame for the text such that I can create a DTLinkButton.
Here's the sample code from the Demoapp:
- (void)configureCell:(DTAttributedTextCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *snippet = [_snippets objectAtIndex:indexPath.row];
NSString *title = [snippet objectForKey:#"Title"];
NSString *description = [snippet objectForKey:#"Description"];
NSString *html = [NSString stringWithFormat:#"<h3>%#</h3><p>%#</font>Test</p>", title, description];
[cell setHTMLString:html];
cell.attributedTextContextView.shouldDrawImages = YES;
}
Any pointers will be awesome.
I'm trying to remove text from html page, and I'm using this code:
NSRange *r;
while ((r = [commentsOnly rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound) {
commentsOnly = [commentsOnly stringByReplacingCharactersInRange:r withString:#""];
NSLog(#"clearing");
}
It removes html tags perfect, but how can I remove only one tag? For example, title or p. I don't want to remove only my tag. I want to remove start tag (<p>), info between two tags and close tag (<\p>).
If I understand your question, may be this will help you:
NSString *string = #"</body>", *htmlString = #"ddsfsdf_<body>_sdfsfd_<body>ffff</body></body>";
NSRange range = [htmlString rangeOfString:string];
if (range.location != NSNotFound)
{
range.length += range.location;
range.location = 0;
string = #"<body>";
NSRange rangeOpen = [htmlString rangeOfString:string options:NSBackwardsSearch range:range];
if (rangeOpen.location != NSNotFound)
{
range.length -= rangeOpen.location;
range.location = rangeOpen.location;
htmlString = [htmlString stringByReplacingCharactersInRange:range withString:#""];
NSLog(#"%#", htmlString);
}
}
Use stringByEvaluatingJavaScriptFromString: to execute JavaScript within the UIWebView to do this. This is much less work and is also much more reliable, as it will use WebKit's HTML parser instead of naïve string replacement.