iOS- Pull HTML id to display an image in an UIImageView - html

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];
});
});
}

Related

Sending base64 UIImages comes out empty

I'm trying to send an HTML email with embedded UIImages.
This is my code:
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:NSLocalizedString(#"Subject", #"Default Subject")];
// Build email body (HTML)
UIImage *emailImage = [UIImage imageNamed:#"image.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
NSString *base64String = [imageData base64EncodedString];
NSMutableString *emailBody = [[NSMutableString alloc] initWithString:#"<HTML>Hey,<br><br>Here's the image!"];
[emailBody appendString:[NSString stringWithFormat:#"<img src='data:image/png;base64,%#'></html>",base64String]];
[mailComposer setMessageBody:emailBody isHTML:YES];
[delegate.viewController presentModalViewController:mailComposer animated:YES];
When the Email Modal View Controller comes up I see the images just fine. But when I tried to view this email on my Mac and on my iPhone and the images comes out empty.

How to encode odd HTML characters with Xcode?

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;
}

show route in newly launch google map app

I'm looking for way to redirect user from our app to google map app to show route between two location. currently apple map is supporting route in united state only but i want to publish my app for other regions.
before few days apple launches google map app for ios, i want to redirect my user inside it.
right now i'm using following code to redirect user in apple maps :
NSString * myLocString = [NSString stringWithFormat:#"40.737893,-73.990173"];
NSString * destString = [NSString stringWithFormat:#"40.733893,-73.993173"];
NSString* queryString = [NSString stringWithFormat:#"saddr=%#&daddr=%#",myLocString,destString];
NSString* searchQuery = nil;
searchQuery = [queryString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* urlString = [NSString stringWithFormat:#"http://maps.apple.com/maps?%#",searchQuery];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
Simple way to achieve this :
BOOL openurlflag=[[UIApplication sharedApplication] canOpenURL:
[NSURL URLWithString:#"comgooglemaps://"]];
if (openurlflag==0)// open apple maps {
NSString * myLocString = [NSString stringWithFormat:#"40.737893,-73.990173"];
NSString * destString = [NSString stringWithFormat:#"40.733893,-73.993173"];
NSString* queryString = [NSString stringWithFormat:#"saddr=%#&daddr=%#",myLocString,destString];
NSString* searchQuery = nil;
searchQuery = [queryString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* urlString = [NSString stringWithFormat:#"http://maps.apple.com/maps?%#",searchQuery];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
} else if (openurlflag==1) // open google maps {
NSString * myLocString = [NSString stringWithFormat:#"40.737893,-73.990173"];
NSString * destString = [NSString stringWithFormat:#"40.733893,-73.993173"];
NSString* queryString = [NSString stringWithFormat:#"saddr=%#&daddr=%#&directionsmode=transit",myLocString,destString];
NSString* searchQuery = nil;
searchQuery = [queryString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* urlString = [NSString stringWithFormat:#"comgooglemaps://?%#",searchQuery];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; }
finally i got one link where you can do it by changing URLScheme.
https://developers.google.com/maps/documentation/ios/urlscheme

DTAttributedTextCell with clickable link

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.

MFMailComposeViewController csv attachment not being attached, but showing inline instead

I am having a problem with sending csv attachments via MFMailComposeViewController.
Sometimes they come through just fine, but for other users they don't come through as attachments, but rather as text inline in the email (with <br/> instead of line returns.) It's very strange. Anybody know what I'm doing wrong?
Here is a snippet of my code:
MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
mailComposeViewController.mailComposeDelegate = self;
NSString *csv = #"foo,bar,blah,hello";
NSData *csvData = [csv dataUsingEncoding:NSUTF8StringEncoding];
[mailComposeViewController addAttachmentData:csvData mimeType:#"text/csv" fileName:#"testing.csv"];
[mailComposeViewController setSubject:#"testing sending csv attachment"];
[mailComposeViewController setMessageBody:#"csv file should be attached" isHTML:NO];
[self presentModalViewController:mailComposeViewController animated:YES];
-(IBAction)btnPressed:(id)sender {
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *Path = [docDir stringByAppendingString:#"/CSVFile.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:Path];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"For csv file..."];
[controller setMessageBody:#"...csv file is hear.." isHTML:NO];
[controller addAttachmentData:csvData mimeType:#"text/csv" fileName:#"CSVFile.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];
}
Hi I put sample code for Creating CSV file and attach it with mail but make sure you have to add MessageUI.Framework and import its related header "MessageUI/MessageUI.h"
"MessageUI/MFMailComposeViewController.h" and deligate "MFMailComposeViewControllerDelegate"...I hope this wl useful for others
- (void)viewDidLoad {
arrCsv=[[NSArray alloc]initWithObjects:#"Hello",#"Hi",#"traun",#"fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/try.csv", documentsDirectory];
[[arrCsv componentsJoinedByString:#","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
-(ibAction)btnMail {
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *Path = [docDir stringByAppendingString:#"/CSVFile.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:Path];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"For csv file..."];
[controller setMessageBody:#"...csv file is hear.." isHTML:NO];
[controller addAttachmentData:csvData mimeType:#"text/csv" fileName:#"CSVFile.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{ message.hidden = NO;
switch (result)
{
case MFMailComposeResultCancelled:
message.text = #"Result: canceled";
break;
case MFMailComposeResultSaved:
message.text = #"Result: saved";
break;
case MFMailComposeResultSent:
message.text = #"Result: sent";
break;
case MFMailComposeResultFailed:
message.text = #"Result: failed";
break;
default:
message.text = #"Result: not sent";
break;
}
[self dismissModalViewControllerAnimated:YES];
}
set the mime type as "application/octet-stream" and that should do the trick to remove inline attachments (I still named the extension of my file i.e. pdf)
I believe the second parameter to setMessageBody:isHTML: must be YES for attachments to not show up inline.
Even if you set isHTML param to YES, your message body can be sent as plain/text if the message body can be represented as such. And attachments in plain/text messages are not always recognized correctly by some email clients (Outlook).
In my case adding a link in the message body helped. Formatting text as bold with HTML tags works too. Tricky!
Tested on iPod 1G 3.1.3.
This may not be the case here, but one thing to watch out for is that:
[NSString dataUsingEncoding:]
returns a valid but empty NSData object if the conversion to the specified encoding is not possible. Better to use the full version:
[NSString dataUsingEncoding: s allowLossyConversion: YES]
Or check the length of the returned data. It appears that zero-length data attachments are trimmed somewhere in the mail process.