Create a UIImage by rendering UIWebView on a background thread - iPhone - iphone

Does someone know of a way, or has a creative idea as to how to obtain an UIImage that is rendered from a UIWebView? The catch is, that is must be on a background thread.
I'll elaborate:
I'm trying to obtain the image from multiple UIWebViews every second+-, and display it on screen (iPhone's of course). Because rendering a layer to a CGContext is a CPU consuming job, I wouldn't like to use the main thread, so not to hang the UI.
My attempts so far were:
I tried to use renderInContext on the webView's layer to the UIGraphicalContext, but the _WebTryThreadLock error crashed the webviews.
I tried creating a CGBitmapContext, and render the webview's layer to it, but got the same result.
I tried implementing a copy method (by adding a Category) to CALayer, that deep copied all of the public properties, and sublayers. Afterwards, I tried to renderInContext the layer I copied. I got a UIImage that was partially "correct" - meaning, not all of the layers were rendered, so for example, i would get only the website header (or footer, or body, or search bar, or just a some of the frames). The UIWebview's layer consists of all sort of subclassed CALayers, so this is probably why this approached didn't work.
I tried setting the kCATransactionDisableActions in a CATransaction, but it didn't appear to change this behavior (neither of them).
I'm pretty close to giving up.
Is there a savior among you people?

UIWebView hates, and I mean really hates, having anything done to it on a background thread. UIKit is not fully thread safe. Drawing to a graphics context is (this was added in iOS 4), but not creating UIViews on a secondary thread.
Are you creating your UIWebViews off the main thread? Do you perhaps have some code to share? I would suspect your issues are being caused by the fact you're trying to perform operations to a UIWebView on a secondary thread. The drawing operation to render the view's contents as an image can happen off the main thread, but creating the view itself can't.

I've been working on this, too.
In a thread I create a view hierarchy, loop until the web-view has finished loading content.
The webview I create is inside of a UIViewController's viewdidload-- I've tried doing
if ([NSThread isMainThread] == NO) {[self performselectorOnMainThread: #selector(viewDidLoad)return;)}
And I've done the same for dealloc'ing the webView.
But that didn't work.. I've only found that we avoid UIWebView exceptions UNTIL we hit the autorelease pool...
I'm using instruments to figure out why.
Here's my attack strategy...
I'm going to perform the render operation on the main thread with an off-screen view, having a separate thread running some sort of queue to manage them. I'm worried about UI lag, so it'll have to be fairly efficient.

Related

how to set high priority to the NSOperation that is drawing current pdf page in ipad?

I am developing a custom PDF reader for ipad.I have taken a UIScrollView and adding/removing UIViews to it on which the equivalent thumbnail of corresponding pdf page will be displayed.I am creating an NSOperation and adding to a NSOperationQueue as soon as a UIView is added to the scroll view to generate PDF thumbnail in background.At any point of time there will be 3 UIViews on the scroll view.The whole arrangement is working fine with the small PDF files as they renders fast but the problem is with large/complex PDF pages,when ever user leaves navigation at a particular page, as per my implementation,there will be 3 NSOperations simultaneously working in the background to generate 3 thumbnails(one for previous page,one for current page and other for next page)thus taking long time,as a whole, to display the current page.I tried to iterate through all live NSOperation objects and set high priority to the one which is suppose to render the current page thumbnail in scrollViewDidEndDecelerating: method but its not working and the resulting effect is still same.Please suggest me a way to over come my problem, thanks in advance.
If you have set your NSOperationQueue to work in the background (i.e. you have not called [NSOperationQueue mainQueue]. The tasks should be completed asynchronously, but will not update the view which is running on the main thread until much later. The priority level does not matter as it does not relate to the thread in which the action takes place. The solution would be to add:
-(void)main {
// ** load PDF image **
[self performSelectorOnMainThread:#selector(insertImageLoaded:)
withObject:img
waitUntilDone:YES];
}
Basically, what you must remember is that iOS creates a small thread pool which is much more visible when using GCD that NSOperations.

loading image asynchronously with spinner at the back

I see many apps which have an image frame that loads the image asynchronously and while the image is not loaded yet, it shows either a spinner at the back or a default image. Is there a library for doing that? If yes then what is it? And please no three20 (I've had a bad experience with it). If not then how do you create one.
The spinner is called UIActivityIndicatorView, which is a subclass of UIView, and as such, can be placed anywhere on the screen.
It has startAnimating and stopAnimating methods, which begin and end the "spin".
So create the UIActivityIndicatorView, place it with addSubview where you want, and call startAnimating (this, as UI activity, has to be done on the main thread). Then call the image loading code asynchronously, and when the image finishes loading, call stopAnimating on the spinner, put the loaded image on top of it, and then remove the spinner with removeFromSuperview.
AFAIK, there is no built-in Cocoa API to do this in a call or two (which sounds like what you want).
I personally set up a singleton image cache manager that uses the built-in NSURLConnection class to load the images, save them to the filesystem, then call delegate methods on the requesting class (which includes a little subclass of UIImageView) to hand it the loaded image data.
People on SO report success with ASIHTTPRequest as well, for similar tasks. Worth checking out, I imagine (though I don't use it).

(iphone) what shouldn't be done in background thread with respect to UIView?

I know and heard most UI related shouldn't be done in thread other than main.
I also know that you can update non-view related data member(that you added) of UIView derived class.
I wonder if the below operations are fine or not to do in background thread.
allocing UIView
init UIView with/without(CGRectZero or just init) frame info
modifying frame/image(UIImageView's) property of UIView
modifying image property of NSObject derived class. (treating UIImage as data)
accessing subviews with subviews method
etc.. Is there a well defined documentation on this issue?
Thank you
You shouldn't be doing anything view related in a background thread. All of the items you listed should not be done in a background thread. If you're breaking your app up correctly for MVC, the view should only contain items that dictate how it is displayed. So anything relating to one should only be in the main thread.
All of your data manipulation should be residing in your model. It can be threaded as needed for performance. Just be careful that you send any messages to update the UI for the data manipulation on the main thread. This includes notifications. They gets sent on the same thread they were created on. So it's easy to forget to switch into mainThread when sending one.

UIView takes too long to update

In an iPad app, I have a bunch of UIImageViews inside a bigger UIView. Each UIImageView contains a thumbnail that is generated in a separate thread (so as not to freeze the application). After thumbnail has been successfully generated I call setNeedsDisplay on main thread, however, it doesn't update the UIImageViews as the thumbs become available (I can see them in the log), rather it takes about 5 seconds and then displays all of them at once.
here's what I am doing when a thumbnail has been created in a separate thread:
[self performSelectorOnMainThread:#selector(setNeedsDisplay)
withObject:nil
waitUntilDone:NO];
any ideas?
What's your main thread up to? If your application waits until all the thumbnails are available before redrawing, then it sounds like maybe you are inadvertently blocking on your main thread until your thumbnailing queue has emptied. How are you setting up the threads?
The problem is that you can't tell cocoa that it have to redraw "now".
With setNeedsDisplay you can onely order a redraw, because drawing is ra rather expensive procces.
setNeedsDisplay
You can use this method or the
setNeedsDisplayInRect: to notify the
system that your view’s contents need
to be redrawn. This method makes a
note of the request and returns
immediately. The view is not actually
redrawn until the next drawing cycle,
at which point all invalidated views
are updated.
Mybe its a better and more performant solution to wait for all generated thumbnials?!
I would use NSNotification. Send a notification from your thread loading the images when an image is ready. Your view controller can observe these notifications and update the view as they arrive.

TTTableImageItem doesn't load the image until scroll

I'm using the three20 project for my iPhone app. I've narrowed my problem down and I'm now just trying to re-create the 'Web Images in Table' example that comes with the project. I've copied the code exactly as in the project, with the exception that I do not use the TTNavigator (which the example does) but I am adding my TTTableViewController manually to a tabBar.
The problem is as follows; the images in the table should load automatically from the web, like in the example. But they only load after I scroll the table up and down.
In the console it clearly says it is downloading the images, and you see the activity indicator spinning like forever.. And unless I scroll up and down once, the images will never appear.
Anyone? Thanks in advance.
P.S:
If I'm using this code in any random UIView, It also doesn't work (only shows a black square):
TTImageView* imageView = [[[TTImageView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)] autorelease];
imageView.autoresizesToImage = YES;
imageView.URL = #"http://webpimp.nl/logo.png";
[self.view addSubview:imageView];
If I put this code in my AppDelegate (right onto the window), it does work .. strange?
POSSIBLE SOLUTION:
Although I stopped using TTImageView for this purpose, I do think I found out what the problem was; threading (hence accepting the answer of Deniz Mert Edincik). If I started the asynchronous download (because basically that is all the TTImageView is, an asynchronous download) from anywhere BUT the main thread, it would not start. If I started the download on the main thread, it would start immediately..
Sounds like a threading problem to me, are you creating TTImageView in the main runloop?
I find one interesting thing. When I use combination TTTableViewController, TTTableViewDataSource and TTModel I have same problem with loading TTImageView. My problem was, that my implementation of Model methods 'isLoading' and 'isLoaded' don't return proper values after initialization of model. That forces me to call reload on model manualy in 'viewDidAppear' method and that causes image loading problem. So I repair my 'isLoading' and 'isLoaded' methods to both return 'NO' after Model init, and everything is fine.
When an image finishes loading try sending a reloadData message to the table view. This forces the table to recalculate the size of the rows and redraw the table. Just be careful that you don't start downloading the image again in response to this message.
I've written something similar to this where an image view will load its own image from the web.
Im my experience, when the image had loaded successfully but was not shown in its view, it was a case that the cell needed to be told to redraw.
When you scroll the table view, the cells are set to redraw when the come onscreen, which is why they appear when you scroll.
When the image loads, tell the cell that it is sitting in to redraw by sending it the message setNeedsDisplay.
That way, when the image finishes downloading, the cell its sitting in (and only that cell) will redraw itself to show the new image.
It's possible that you might not need to redraw the entire cell and might be able to get away with simply redrawing the image view using the same method call. In my experience, my table cells view hierarchy was flattened, so I had to redraw the whole cell.
I don't have an answer for what you want to do, but I will say that this is considered a feature, and the expected behavior. You use TTImageView in UITableView when you want to do lazy loading of images. TTImageView will only load the images whose frames are visible on the screen. That way, the device uses its network resources to download images that the user has in front of them, rather than a bunch of images that the user isn't even trying to look at.
Consider having a long list that may contain a couple hundred thumbnail images (like a list of friends). I know from experience that if you kick off 100+ image requests on older devices, the memory usage will go through the roof, and your app will likely crash. TTImageView solves this problem.
This is a thread problem. You can load the images by including the line:
[TTURLRequestQueue mainQueue].suspended = NO;
in - (void)didLoadModel:(BOOL)firstTime.