Which way is faster to load webpages in uiwebivew
using
Loading NSData into a UIWebView
OR
using Load Request URL?
Network requests take time. There's no point in trying to optimize a few milliseconds off this type of code. Write the code that is most readable / maintainable and it will serve you better.
You could put the webpage, scripts, css, and images in your app bundle; get a URL that points to it (file://...) and use that. Within your webpage, you can use AJAX to pull in some dynamic data, etc.
That'd be a better path to optimize; but it all depends on your situation.
If you have the option of using loadRequest, I'd recommend it. Let the OS take the work off your hands.
edit:
PS: UIWebView tends to take it's time about displaying data; even when no network is involved.
I often set the webview's alpha to 0 in IB or viewDidLoad; then fade it in when the content is ready.
Inside your webViewDidFinishLoad: method, add this:
if (0.0f == webview.alpha) {
[UIView animateWithDuration:0.4f
animations:^{
webview.alpha = 1.0f;
}];
}
Their is really isn't any "technical" way to load Webview faster, But I would recommend you use:
Load Request URL
Load Request URL Code:
#interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}
#property (nonatomic, retain) UIWebView *webView;
#end
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.google.com";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
Related
I know this question has been asked a couple of times before. I m trying to zoom in / out the uiwebview. How exactly do i do this? I tried setting 'webView.scalesPageToFit=YES;' but its not working.
I also tried this How do I enable the zoom in/out option in a UIWebView? but yet im not able to achieve the zoom in / out
Code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[actorUrlArray objectAtIndex:_rowNumberInActivity]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
webView.scalesPageToFit=YES;
what am i missing out here?
NOTE : I'm loading the iphone app on the ipad to check the app. Can that be a problem??
If its the meta tag problem. how do i set them? i tried this code.. but its not working.. i know nothing about javascript.. so im not sure whether this is correct or not..
NSString* js =
#"var meta = document.createElement('meta'); \" \"meta.setAttribute( 'name', 'viewport' ); \" \"meta.setAttribute( 'content', 'width = device-width, initial-scale = 5.0, user-scalable = yes' ); \" \"document.getElementsByTagName('head')[0].appendChild(meta)";
[webView stringByEvaluatingJavaScriptFromString: js];
Zooming in and out and Pinch are built in feature of UIWebView. You don't need to write any code to achieve that.
just simply set the property.
scalesPageToFit=YES
for any pinching and zooming to work on a UIWebView
I'm making an iPad browser, and I have a little problem. When I go to google, for example, I write the google direction in a textField. The problem is that when I change the web page, it still says http://www.google.com/. Here's my code:
-(IBAction)buttonpressed2:(id)sender {
url = [NSURL URLWithString:[textField text]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[webView isEqual:textField.text];
}
How can I make the textField show the page that I'm watching right now, and not the first url typed in the field?
First, make sure when you set up the webView, you assign the UIWebViewDelegate to self
Then, implement the delegate method: webViewDidFinishLoad, as such:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSURLRequest *currentRequest = [webView request];
NSURL *currentURL = [currentRequest URL];
//This will log the current url
NSLog(#"Current URL is %#", currentURL.absoluteString);
//Then to display it in the textField
textfield.text = currentURL.absoluteString;
}
Edit:
A delegate is a special set of methods that wait for an event to happen. When that event happens, the appropiate method is called. The method above is one of the delegate methods for a UIWebView - When a specific event happens with the webView, in this case when the webViewDidFinishLoad, that method is automtically called and we can respond as such. In order to set the delegate, we can proceed one of two ways:
If you created the webView in code, this is with something like this:
UIWebView *webView = [[UIWebView alloc] init...]
then all you need to do is add the following line of code:
webView.delegate = self;
However, you might have also created the webView in the interface builder - If that's the case, click on the webView and the linker tab, and drag the delegate option over to "File's Owner".
and thats it.
Your class should implement the UIWebViewDelegate protocol. Then in the method webView:shouldStartLoadWithRequest:navigationType: you can do this:
[textField setText:[[request URL] absoluteString]];
This way the value in the textField will be updated whenever you navigate to a new url.
Sorry for the long question, but I have been stuck on this for days and have exhausted all other help.
Currently, I have a tab bar application with four tabs. In the second tab (SecondViewController), I have a segmented controller at the top that should switch between "videos" and "images". The videos page should have around 5 youtube videos loaded in UIWebView using the code here. The images view should contain around 5 thumbnails that, when clicked on, open into a larger picture. My problem is that I have tried out many different ways of accomplishing this, and none seem to work to any extent. Really the main thing I am looking for here is the recommended way of going about switching between two views using a segmented controller and if it is possible to load the views from different files (videosView.h/m and imagesView.h/m).
In SecondViewController.m, I have the app respond to the UISegmentedController using the following, though I have absolutely no idea if this is even close to correct.
- (IBAction)segmentedControlChanged
{
switch (segmentedControl.selectedSegmentIndex)
{case 0:
[self.view addSubview:videosView.view];
[imagesView.view removeFromSuperview];
NSLog(#"1");
break;
case 1:
[self.view addSubview:imagesView.view];
[videosView.view removeFromSuperview];
NSLog(#"2");
break;
default:
break;
}
}
In videosView.h, I only have the following:
#import <UIKit/UIKit.h>
#interface videosView : UIWebView
{
}
- (videosView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame;
#end
In videosView.m, I have the following, though I am getting a warning on the initWithFrame line.
- (videosView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame;
{
if (self = [super init])
{
// Create webview with requested frame size
self = [[UIWebView alloc] initWithFrame:frame];
// HTML to embed YouTube video
NSString *youTubeVideoHTML = #"<html><head>\
<body style=\"margin:0\">\
<embed id=\"yt\" src=\"%#\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
// Populate HTML with the URL and requested frame size
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, urlString, frame.size.width, frame.size.height];
// Load the html into the webview
[self loadHTMLString:html baseURL:nil];
}
return self;
}
#end
imagesView is made, but has no added code it in currently, as I am just trying to get the videos sorted out first.
My recommendation:
Use one view controller and have the view controller contain both views. You are already doing that.
You can still use separate files (subclasses of UIView).
Do not use addSubview: and removeFromSuperView:, but rather set these "container" view as hidden as appropriate.
Also, in the segmentedControlChanged method, do all the other necessary switching tasks, such as canceling open URL connections etc.
Do the initialization of the web content of the container views in viewDidLoad rather than in the initializer. Make sure you do not freeze the UI but use asynchronous loading.
EDIT: Adding subclassing code.
in SecondViewController.h:
#include VideosView.h
...
#property (nonatomic, retain) VideosView *videoView;
in SecondViewController.m
-(void)viewDidLoad {
self.videosView = [[VideosView alloc] init];
// add to superview etc.
}
Whenever you want to execute view specific code, just call any method you define in VideosView.h and implement in .m.
[self.videosView playVideo];
I m using ASIHTTP Request sample source code for downloading urls.
My question is that how to pause and resume the downloading files.
Please Help.
Deprecation Notice
ASIHTTP was deprecated around 2011, if you want network connectivity now, you should look up AFNetworking for ObjC or Alamofire for Swift, or stick to the native support:
For native support, in iOS 7 Apple added the NSURLSession, which can start download tasks (NSURLSessionDownloadTask), and these can be cancelled and restarted, check the method downloadTaskWithResumeData(_:) from NSURLSession, that has a very good explanation.
ASIHTTP is no longer needed, if you gotta are keeping a legacy app running, well, good luck.
Original Answer
Posted on 2011
ASI itself can resume a download from a file using [myASIRequest setAllowResumeForFileDownloads:YES];, check out the How-to-Use for an example.
Edit: Ok, there's no easy way to pause a download (a [myRequest pause] would be ideal). After reading and trying for a while, turns out that cancelling the request and resending it again is the only way.
For example, here's an example class I made:
#interface TestViewController : UIViewController <ASIHTTPRequestDelegate>
{
ASIHTTPRequest *requestImage;
UIImageView *imageViewDownload;
}
#property (nonatomic, retain) IBOutlet UIImageView *imageViewDownload;
- (IBAction)didPressPauseButton:(id)sender;
- (IBAction)didPressResumeButton:(id)sender;
To start (or restart) the download:
- (IBAction)didPressResumeButton:(id)sender
{
if (requestImage)
return;
NSLog(#"Resumed");
// Request
requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:#"http://www.myheadhealth.com/_IMAGES/cheese.jpg"]];
// Using a temporary destination path just for show.
// Better pick a suitable path for your download.
NSString *destinationDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"cheese.jpg"];
NSString *temporaryDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"cheese.jpg-part"];
requestImage.downloadDestinationPath = destinationDownloadPath;
requestImage.temporaryFileDownloadPath = temporaryDownloadPath;
requestImage.allowResumeForFileDownloads = YES;
requestImage.delegate = self;
[requestImage startAsynchronous];
}
In the exmaple above, I'm loading a random image of cheese I found, and storing a temporary download, and a full download.
Canceling the request will keep the contents of the temporary file intact, in fact, I made an UIImageView, and when pressing "Cancel" I could see a part of the downloaded file. If you want to try it out:
- (void)didPressPauseButton:(id)sender
{
if (requestImage)
{
// An imageView I made to check out the contents of the temporary file.
imageViewDownload.image = [UIImage imageWithContentsOfFile:requestImage.temporaryFileDownloadPath];
[requestImage clearDelegatesAndCancel];
requestImage = nil;
NSLog(#"Canceled");
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
imageViewDownload.image = [UIImage imageWithContentsOfFile:request.downloadDestinationPath];
requestImage = nil;
}
I have been trying to load the url http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true into a webview but it shows up an error 'Entity nbsp not found'.
The link works properly over Safari (Machine as well as simulator) but doesnt load properly when loaded through a webview. Can someone point me as to how to do it?
#define kEventsCalenderLink #"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"
NSURL *eventsURL = [NSURL URLWithString:kEventsCalenderLink];
eventsWebView.delegate = self;
[eventsWebView loadRequest:[NSURLRequest requestWithURL:eventsURL]];
The server is serving that page with the Content-Type of "application/xhtml+xml" to the Simulator version of Safari. Safari is interpreting the page as strict XML, which does not have an entity.
Unfortunately, UIWebView manipulates its HTTP headers behind the scenes, and it's seemingly impossible to configure it to make a request that will cause your server to serve content as "text/html"
The one workaround I would suggest is to retrieve the content with an NSURLConnection, then feed it to your web view with the loadData:MIMEType:textEncodingName:baseURL: method, being sure to pass "text/html" as the MIME type.
This may also necessitate intercepting future requests via the webView:shouldStartLoadWithRequest:navigationType: delegate method (in order to cancel them and load them in the manner described above to prevent similar problems).
Or, if you have control of the server, you could configure it to serve HTML with the appropriate content type. Or convert the content to use proper XML entities.
Do it in this way:
NSString *kEventsCalenderLink #"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"
NSLog(#"%#",kEventsCalenderLink);
eventsWebView.delegate = self;
eventsWebView.userInteractionEnabled = true;
[eventsWebView loadRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:kEventsCalenderLink]]];
You have only defined the URL which you haven't mentioned that it's string type.
Here is the sample code which i implemented.Hope it would help you
- (void)loadView
{
UIView *vew=[[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.view=vew;
//self.title=#"sanjay";
//self.navigationItem.title=#"afdsfasd";
self.view.backgroundColor=[UIColor redColor];
[vew release];
UIButton *smsbtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
smsbtn.frame=CGRectMake(50, 280, 100, 50);
[smsbtn setTitle:#"SMS APP" forState:UIControlStateNormal];
[smsbtn setTitleEdgeInsets:UIEdgeInsetsZero];
[smsbtn addTarget:self action:#selector(loadsms) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:smsbtn];
}
-(void)loadsms
{
NSString *url = [NSString stringWithFormat:#"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]];
}
This code is working dude.Try this out.I have implemented this for you only.