UIWebView loadRequest reuse gives flickering effect - ios

I have multiple pdf files. Based on user input i am loading the pdf using UIWebView. On first loadRequest it loads the pdf properly. From second call to LoadRequest onwards its showing some flickering effect while loading the new pdf.. Meaning that starts blur display of content and slowly display content properly in few secs.
Code snippet below:
- (void) loadDocument: (NSString *) documentName
{
NSString * path = [[NSBundle mainBundle] pathForResource: documentName ofType: self.docType];
NSURL * url = [NSURL fileURLWithPath: path];
request = [NSURLRequest requestWithURL: url];
[PdfWebView loadRequest: request];
}
- (void) loadNewDoc:(int)segIndex
{
switch (mPageIndex)
{
case 0:
[self loadDocument:#"PDF_0"];
break;
case 1:
[self loadDocument:#"PDF_1"];
break;
case 2:
[self loadDocument:#"PDF_2"];
break;
default:
break;
}
}

You can clear the web view before starting the new request by using
[yourwebview loadHTMLString:#"<html><head></head><body></body></html>" baseURL:nil];
Or even
[yourwebview stringByEvaluatingJavaScriptFromString:#"document.open();document.close();"];
This may remove the flickering effect

for me, this helped (its robovm java code):
UIView.transition(_wv, 0.5, UIViewAnimationOptions.TransitionCrossDissolve, new Runnable() {
#Override
public void run() {
_wv.loadData(new NSData(pdf), "application/pdf", "utf-8", null);
}
}, null);

Related

Some DOC Documents are not Displaying in iOS?

It's a weird problem, there are many different type files on my list such as pdf, ppt, xls etc, everything works fine with them but some doc files are not displaying.
I use WebView, UIDocumentInteractionController, QLPreviewController to display the files but I have the same problem. Like this
When I use webview I have this screen
The files size are OK, i mean not too big and there is no problem while opening in computer. I tested the app in a real device, same problem..
Here is the similar problem and i think that there is a bug in ios as they said
How to manage memory within a QLPreviewController
But I believe that there should be a solution, is it a memory problem? I use Xamarin.iOS and this is my code
QLPreviewItemBundle prevItem = new QLPreviewItemBundle(info.FileName, info.FilePath);
QLPreviewController previewController = new QLPreviewController();
previewController.DataSource = new PreviewControllerDS(prevItem);
NavigationController.PushViewController(previewController, true);
and this is for UIDocumentInteractionController
var documentPath = docInfo.FilePath;
UIDocumentInteractionController interationController = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(documentPath));
interationController.Name = docInfo.FileName;
interationController.ViewControllerForPreview = (controller) => NavigationController;
interationController.DidEndPreview += (sender, e) =>
{
interationController.Dispose(); interationController = null;
};
InvokeOnMainThread(() => interationController.PresentPreview(true));
Try using this method,
-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
// Calling -loadDocument:inView:
[self loadDocument:#"mydocument.rtfd.zip" inView:self.myWebview];

iOS 7 UIWebView inconsistent Loading

In my project I have 2 UIWebViews that are IBOutlets and created in the main.storyboard.
One I load by calling a method on ViewDidAppear. It appears perfectly and hits all it's delegate methods. We will call this ViewA
The other is supposed to be Hidden and appear and load when the user taps a button. We will call this ViewB. But once I submit the request, nothing happens, none of the delegate methods get called.
ViewA loads perfectly. If I try to load ViewB on ViewDidAppear, it also loads.
EDIT: Moving the ViewA and ViewB load method calls to the ButtonPress method calls both successfully.
EDIT: Code
-(void)loadCarouselWebView //ViewA
{
NSString *urlString = [NSString stringWithFormat:#"%#%#",[[JSONReader sharedInstance] baseURLToLoad:environmentURLPublicKey],[[JSONReader sharedInstance] URLToLoad:kCarouselURLkey]];
NSURL *url = [NSURL URLWithString: urlString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
self.carouselWebView.delegate = self;
[self.carouselWebView loadRequest: requestObj];
}
-(void)loadFullWebView:(int)index //ViewB
{
NSString *gameURL;
switch (index) {
case 1:
gameURL = game1Constant;
break;
case 2:
gameURL = game2Constant;
break;
case 3:
gameURL = game3Constant;
default:
break;
}
NSString *urlString = [NSString stringWithFormat:#"%#%#",[[JSONReader sharedInstance] baseURLToLoad:environmentURLKey],[[JSONReader sharedInstance] URLToLoad:gameURL]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
self.fullWebView.delegate = self;
[self.fullWebView loadRequest: requestObj];
}
- (IBAction)gameButtonPushed:(id)sender {
[[self fullWebView] setHidden:NO];
[[self backNavButton] setHidden:NO];
[self loadFullWebView:[sender tag]];
[self loadCarouselWebView];//Added for debugging
}
EDIT: ONLY Loading ViewB on button tap works. If I add Load ViewA on ViewDidAppear then ViewB will not load.
In a surprise twist, there is nothing wrong with the UIWebView.
It was my fault for not reading the code carefully enough.
Someone coded a one time counter into the shouldStartLoadingRequest delegate method that I missed. So only one request was allowed to load.
Thats like 2 days burned there, great stuff! >:E

Can not open webpage using UIWebView

I'm writing an app which lets users open up youtube exercise/fitness videos from a table view. So, I want to pass in a given website address for each cell in the table view. The code executes without errors but in the simulator does not open any webpage when I select a cell. Here is the code of the implementation file:
- (void)viewDidLoad
{
[super viewDidLoad];
//Create a URL object
NSURL *url = [NSURL URLWithString:urlAddress];
//Switch values based on exerciseNumber
switch (exerciseNumber) {
case 0:{
self.title = #"Straight Leg Raise";
urlAddress = #"http://www.youtube.com/watch?v=sb_2OVC4TuM";
}
break;
case 1:{
self.title = #"Supine Hip Abduction with Elastic Band";
urlAddress = #"http://www.youtube.com/watch?v=9gnmbjrjEuM";
break;
}
default:{
self.title = #"No Exercise Selected";
urlAddress = #"http://www.rehabview.com";
break;
}
}
//Create a URL request object
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//load the request in the UIWebView
[webView loadRequest:request];
}
Any idea what I am doing wrong? Thanks in advance.
Create your NSURL object after your switch statement that sets the urlAddress string.

How to use local resources to speed up webview in iOS?

I'm loading a remote webpage into an iOS webview which relies on js and css assets. To improve the performance particularly on 3G networks, I'm hoping to call these assets from files local to the iOS device.
The website backing the iOS app is also used by mobile phone browsers, not just the iOS app, so subclassing NSURLRequest to register my own URL prefix (myurl://) is not ideal.
I already have code that launches mobileSafari for URLs outside of my domain:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *hostname = [url host];
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
This method is called from the same controller implementation with code like this:
- (void)viewDidLoad {
[super viewDidLoad];
// ...
webView.delegate = self;
// ...
NSURL *url = [[NSURL alloc] initWithString:([path length] > 0 ? path : #"http://mysite.com/mobile/index")];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
// ...
}
I've reviewed several other questions ( How to use an iPhone webView with an external HTML that references local images? , Dynamically loading javascript files in UIWebView with local cache not working, iOS WebView remote html with local image files, Using local resources in an iPhone webview ) but they all seem to miss a key element to my problem.
The first link has the start of something promising:
if ([url isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
fileToLoad = [[NSBundle mainBundle] pathForResource:#"jquery-1.8.2.min" ofType:#"js"];
}
If that's a sensible approach, I'm stuck on how to get from passing that fileToLoad NSBundle into the webView's loadRequest, since that's expecting a URL.
I think I'm on the right path after realizing that I could use the output of stringByAppendingPathComponent as a URL, like so...
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
NSString *urlString = [url absoluteString];
if ([urlString isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
NSString *tempurl = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"js/jquery-1.8.2.min.js"];
[webView loadRequest:[NSMutableURLRequest requestWithURL:tempurl]];
} else {
[[UIApplication sharedApplication] openURL:url];
}
return NO;
}
return YES;
I don't have it working yet (it's still loading the remote URL) but I think I'm on the right path.

how does one check if UIWebView is empty or not

I need to check if a webview when completed loading has any content or not.
What I require is simple. Its a small webview strip at the bottom of my pages (like an advert)
I call
NSURLRequest *request=[NSURLRequest requestWithURL:adURL];
[gWebView loadRequest:request];
I get the callback
-(void)webViewDidFinishLoad:(UIWebView *)webView {
But in my scenario the webview shall return empty and sometime it shall have data.
I do not want to show the webview if my server php file returned nothing.
How can I verify that I received an empty page in the callback (or any other way)?
If you are loading a HTML page:
NSString *string = [myWebView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML"];
BOOL isEmpty = string==nil || [string length]==0;
Or you could load the content first, test if it is not empty, and then feed it to the webview. See UIWebView's loadHTMLString:baseURL: or loadData:MIMEType:textEncodingName:baseURL:.
This is based on Jano's approach but should perform better:
NSString *script = #"document.getElementsByTagName('body')[0].innerHTML.length";
NSString *length = [self.webView stringByEvaluatingJavaScriptFromString:script];
if (length.integerValue > 0) {
NSLog(#"not empty");
}
Just replying to an old post, but maybe new arrivals will find it useful. I struggled with the same problem and found this solution to work in my case:
if (webView.request.URL.absoluteURL == nil) {
NSLog(#"nil webby");
NSLog(#"url: %#", webView.request.URL.absoluteURL);
// Perform some task when the url is nil
} else {
NSLog(#"loaded webby");
NSLog(#"url: %#", webView.request.URL.absoluteURL);
// Perform some task when the url is loaded
}
You can call it from the webViewDidFinishLoad: method.
In my case, I was looking to detect if the PDF was malformed. I.e., the web view would be empty because the PDF could not be loaded. Since with iOS 7.1.1, I wasn't getting the didFailLoadWithError delegate callback, I needed a different way to do this. I ended up using the method below before attempting to load the PDF doc into the web view.
// See https://developer.apple.com/library/ios/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html
- (BOOL) isValidPDFDoc: (NSURL *) deviceLocalURL {
CFStringRef path;
CFURLRef url;
CGPDFDocumentRef document;
size_t count;
BOOL validDocument = YES;
// Must use path of URL not absoluteString here.
path = CFStringCreateWithCString (NULL, [[deviceLocalURL path] cStringUsingEncoding:NSASCIIStringEncoding],
kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath (NULL, path, // 1
kCFURLPOSIXPathStyle, 0);
CFRelease (path);
document = CGPDFDocumentCreateWithURL (url);// 2
if (!document) {
validDocument = NO;
}
CFRelease(url);
count = CGPDFDocumentGetNumberOfPages (document);// 3
if (count == 0) {
validDocument = NO;
}
CGPDFDocumentRelease (document);
return validDocument;
}

Resources