Display a preview of the website - html

I need to display a preview of the website with given url in the single image(e.g. like Facebook do in Messenger when you sending a url to someone). Is there any way to achieve that without actually loading the html file and reading it's metadata?

Try this,
NSString *urlStr = #"http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
NSURL *url=[NSURL URLWithString: urlStr];
NSData *data=[NSData dataWithContentsOfURL:url];
UIImage *image=[[UIImage alloc] initWithData:data];
UIImageView *imagview = [[UIImageView alloc]initWithImage:image];
imagview.frame = CGRectMake(250, 500, 100, 100);
[self.view addSubview:imagview];
This will give just thumb or image.
You can use URLEmbeddedView Library for more functionality. I think this is the library what you want.

Related

Scan for images in website - Xcode

I am making an app which will give me the latest news, and the image. I achieve the text bit by making a scanner like this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://stackoverflow.com/questions/22671347/nsuinteger-should-not-be-used-in-format-strings"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<p>" intoString:NULL];
[scanner scanUpToString:#"</p>" intoString:&token];
int length = 3;
token = [token substringFromIndex:length];
textView.text = token;
Now I was wondering if I could use the same type of code to scan the website to find the first image and put it an image view. Also it don't have to be same type of code , post what ever you know and any method.
Summary is.
Want a piece of code that will scan a webpage, pick up the first image and place it in a image view.
Thanks for the people who take the time to help me.
THANKS AGAIN!!!
BYE!!!
NSScanner its not a HTML parser only intended for scanning values from NSString object. If you doing the odd scan you probably could get away with it, but it doesn't seem like...
The CORRECT approach is to use Libxml2 library included in Xcode which is only written is C which doesn't have any Objective-C/Swift wrapper. Libxml2 is the XML C parser and toolkit developed for the Gnome project. Alternatively i would recommend using open-source project such as HTMLReader. Its a HTML parser with CSS selectors in Objective-C and Foundation. It parses HTML just like a browser and is all written in Objective-c.
Example (using HTMLReader):
HTMLDocument *document = [HTMLDocument documentWithString:html]; // get your html string
NSLog(#"IMG: %#", [document firstNodeMatchingSelector:#"img"].textContent); // => image returned here
To find images just change the tag to < img > and your set!!
IF your using Libxml2 take a look at HTMLparser.c header file to parse and retrieve HTML ltags

Image not being displayed in UIImageView pulled from website

I have an app which is pulling the image and displaying it in a UIImageView. I have code that I know is working for pulling the images so I think it has to do something with the HTML. I triple check all of the connections in xcode and all are connected. If you could tell me why the image is not being pulled, that would be great! I am pulling from this website if you want to go look at all of the HTML yourself, but I want the "Right now" image.
Code to pull image:
- (void)viewDidLoad {
[super viewDidLoad];
self.urlForFeelsLike = #"http://www.weather.com/weather/today/CAXX0518:1:CA";
NSURL *myURL2 = [NSURL URLWithString: [self.urlForFeelsLike stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request2 = [NSURLRequest requestWithURL:myURL2];
[webViewForFeelLike loadRequest:request2];
webViewForFeelLike.delegate = self;
timer1 = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(loadImageForCurrentCondition) userInfo:nil repeats:YES];
}
-(void)loadImageForCurrentCondition {
js = #"document.getElementsByClassName('wx-weather-icon')[0].src;";
imgLink = [webViewForFeelLike stringByEvaluatingJavaScriptFromString:js];
imgURL = [NSURL URLWithString:imgLink];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
data = [NSData dataWithContentsOfURL:imgURL];
[self performSelectorOnMainThread:#selector(setImageViewImage) withObject:data waitUntilDone:YES];
});
}
- (void)setImageViewImage {
imgData = [NSData dataWithContentsOfURL:imgURL];
image = [UIImage imageWithData:imgData];
dispatch_async(dispatch_get_main_queue(),^{
if (image == nil) {
}
else {
[currentConditionImageView setImage:image];
}
});
NSLog(#"Weather image reloaded");
}
HTML line I am pulling from:
<div class="wx-data-part wx-first"><img src="http://s.imwx.com/v.20131006.214956/img/wxicon/120/26.png" height="120" width="120" alt="Cloudy" class="wx-weather-icon">
Your JavaScript is wrong.
document.getElementsByClassName('wx-weather-icon') //Always returns an array, so you want:
document.getElementsByClassName('wx-weather-icon')[0].src;
On another note:
dcorbatta is right below as well, you're using UIWebView incorrectly here. Also, if you're using a UIWebView just to get that image, you're doing things in a very slow, unnecessarily intensive way. UIWebView spends a lot of memory rendering and parsing (it's intended for browsing), when something simpler would accomplish the same feat faster and more efficiently. I'd recommend loading the page as an HTML string, and parsing that string instead.
Why do you use an NSTimer? You can use the WebView delegate method: webViewDidFinishLoad:
And why do you extract the image url from the html? The image src going to change in a near future?
As i have seen the link you gave. i Checked the css&HTML of the link the are not using the "Rightnow" image. with our web view we can create backgrounds. and you css code is good it is loading cloud image exactly.
i used the link [link]http://s.imwx.com/v.20131006.214956/img/wxicon/120/26.png where this is a cloud image.. go to w3schools site and type/paste
[link]http://www.w3schools.com/css/tryit.asp?filename=trycss_default

Implementing 'Download to Computer' functionality of browser

I am trying to download a mp3 file at a given link using NSURLConnection. However, I usually get time-out errors. Entering the link into the browser shows the default player, however the music file is not loaded either:
However, if I create the following simple HTML file:
<html>
<body>
Download
</body>
</html>
And then load the file into Safari, right click on the Download link, then select Download to Computer (or whathever it's called in English), Safari downloads the file.
Any ideas on how I can implement this in my own app?
I tried using
NSData *data = [NSData dataWithContentsOfURL:url];
and
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) { /.../ }];`
without success.
Seems like you're trying to hit a fly with a sledgehammer, using "NSURLConnection".
Try doing something a wee bit more high level such as
NSData * mp3data = [[NSData alloc] initWithContentsOfURL:options:error: ];
(the added benefit here is that you can get useful errors back via the "error:" parameter you pass into the method.
Here's an example on what you need to do:
NSURL* url = [NSURL URLWithString:yourMp3URLString];
//URL of the mp3 file
NSString* fileName = [NSString stringWithFormat:#"%#.mp3", mp3Name];
//NSString with the name of the mp3
NSString* destinationPath = [filePathString stringByAppendingPathComponent:fileName];
//NSString with the filePathString (NSString with path destination, you could
//change it to something like this #"User/Desktop")
//and add the NSString filename to the end of it
//so, if we have like User/Desktop it will become User/Desktop/mp3Name.mp3
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLDownload* download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
[download setDestination:destinationPath allowOverwrite:NO];
//create the URLRequest and Download the mp3 to the destinationPath

Injecting local files into UIWebView without breaking links

I am working on an iOS app that needs to display webpages from a server inside a UIWebView while injecting relevant local png and css files as needed in order to speed up load time. Here is the code I am using to try to do this:
NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/index.html"]]];
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
[myWebView loadHTMLString:myFileHtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
My problem is that some of the webpages have buttons in them that link to other webpages on the server, and because the UIWebView is only loading a string, the buttons when tapped don't cause the UIWebView to load the new webpage URL like it would if I had used the loadRequest method.
My question is how can I get the the UIWebView to behave like it is loading a request while still injecting local files from the baseurl?
Thanks
The relative links in the button cannot work, because the linked pages are on a remote server and not on the device's file system. However you can use a UIWebViewDelegate method to make it work:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSString *localRootPath = [NSString stringWithFormat:#"file://%#", [[NSBundle mainBundle] bundlePath]];
NSString *remoteRootPath = #"http://yourdomain.com";
NSString *remotePath = [[request.URL absoluteString] stringByReplacingOccurrencesOfString:localRootPath withString:remoteRootPath];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:remotePath]]];
// or you can use your own loading mechanism here
return NO;
}
return YES;
}
This method intercepts all requests from your WebView. If the request was triggered by a user tap / click the URL gets modified from a relative URL to a absolute URL so it can be loaded from the server. Don't forget to set the delegate on the WebView or this method will not be called.
NSURLPRotocol is a handler for NSURLConnection and will give you the opportunity to intercept the calls to the server and substitute your own content.
1) Derive a class from NSURlProtocol
2) Call NSURLProtocol registerClass: in your application:didFinishLaunchingWithOption
3) Read the documentation on implement these methods as necessary:
initWithRequest:cachedResponse:client:,
startLoading,
URLProtocol:didReceiveResponse:cacheStoragePolicy:
URLProtocolDidFinishLoading:

Reading HTML content from a UIWebView

Is it possible to read the raw HTML content of a web page that has been loaded into a UIWebView?
If not, is there another way to pull raw HTML content from a web page in the iPhone SDK (such as an equivalent of the .NET WebClient::openRead)?
The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error: method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:
NSString *googleString = #"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
After running this code, googlePage will contain the HTML for www.google.com, and error will contain any errors encountered in the fetch. (You should check the contents of error after the fetch.)
Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the request from the view, then do the fetch as before:
NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString: method, as such:
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"];
This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.
Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *page as the result of a call to stringWithContentsOfURL:encoding:error:. You can then push that string into the web view using loadHTMLString:baseURL:, assuming you also held on to the NSURL you requested:
[yourWebView loadHTMLString:page baseURL:requestURL];
I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString, is somewhat ambiguous, and the docs don't say much about it).
For more info:
UIWebView class reference
NSString class reference
NSURL class reference
if you want to extract the contents of an already-loaded UIWebView, -stringByEvaluatingJavaScriptFromString. For example:
NSString *html = [webView stringByEvaluatingJavaScriptFromString: #"document.body.innerHTML"];
To get the whole HTML raw data (with <head> and <body>):
NSString *html = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.
Also note that the #"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use #"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.
To read:-
NSString *html = [myWebView stringByEvaluatingJavaScriptFromString: #"document.getElementById('your div id').textContent"];
NSLog(html);
To modify:-
html = [myWebView stringByEvaluatingJavaScriptFromString: #"document.getElementById('your div id').textContent=''"];
In Swift v3:
let doc = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)
I use a swift extension like this:
extension UIWebView {
var htmlContent:String? {
return self.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
}
}
you should try this:
document.documentElement.outerHTML
UIWebView
get HTML from UIWebView`
let content = uiWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")
set HTML into UIWebView
//Do not forget to extend a class from `UIWebViewDelegate` and nil the delegate
func someFunction() {
let uiWebView = UIWebView()
uiWebView.loadHTMLString("<html><body></body></html>", baseURL: nil)
uiWebView.delegate = self as? UIWebViewDelegate
}
func webViewDidFinishLoad(_ webView: UIWebView) {
//ready to be processed
}
[get/set HTML from WKWebView]