I have an UIWebView that loads a embedded XHTML like this:
body = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
body.scalesPageToFit = YES;
body.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
body.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:body];
[body loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"article16" ofType:#"xhtml"]isDirectory:NO]]];
This XHTML have a lot of images, and when I rotate the device I got some memory warnings, and sometimes the app crashes.
If I remove the autoresizing mask, specifically the UIViewAutoresizingFlexibleWidth (I have tryed with only UIViewAutoresizingFlexibleLeftMargin and UIViewAutoresizingFlexibleRightMargin with no problems), the memory warning stops, and the app does not crash anymore.
If I remove all autoresizing mask, and set the new webView frame in didRotate or willRotate, I got the same warnings as using the UIViewAutoresizingFlexibleWidth.
There's a app, called Atomic Web that could open the same XHTML and rotate with no memory warnings, and safari can open it as well, but if I create a project with only that UIWebView, the app sometimes crashes.
Someone knows what this may be? Can I set the webview frame in other way? Why can't I use the autoresizing mask?
Thanks for your attention.
I was seeing memory issues as well, but in a slightly different capacity with a UIScrollView. It appears that the [UIColor scrollViewTexturedBackgroundColor] property consumes a very significant amount of memory when your UIScrollView subclass, including UIWebView, applies it as the background color.
I would recommend changing it to just a plain color like gray. I noticed a 7 MB reduction in memory as reported by the activity monitor instrument by just making that simple change.
Try:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"WebKitCacheModelPreferenceKey"];
}
From http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest
Related
I've been searching all over the internet over the past couple of days to no avail. Unfortunately, the apple documentation about this specific issue is vague and no sample code is available (at least thats what I found out). What seems to be the issue you may ask...
I'm trying to set a uiview's layer as the contents of the material that is used to render an iPhone model's screen (Yep, trippy :P ). The iPhone's screen's UV mapping is set from 0 to 1 so that no issue persists in mapping the texture/layer onto the texels.
So, instead of getting this layer to appear rendered on the iPhone, same as left image, Instead, I get this rendered onto the iPhone like right image
Correct Render Incorrect Render
Also note, that when I set a breakpoint and debug the actual iPhone node and view it in Xcode, a completely different render is shown and the layer gets half-fixed when I continue execution:
Now then... HOW do I fix this issue??? I've tried playing with the diffuse's contents transform matrix but nothing gets fixed. I've also tried resizing the UIView to 256x256 (since the UV seems to be 256x256 as shown in blender - the 3d modelling package), but that doesn't fix anything.
Here is the code for the layer:
UIView *screen = [[UIView alloc] initWithFrame:self.view.bounds];
screen.backgroundColor = [UIColor redColor];
UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen.bounds.size.width, 60)];
temp.backgroundColor = [UIColor colorWithRed:0 green:(112.f/255.f) blue:(235.f/255.f) alpha:1];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(temp.bounds, 40, 0)];
label.frame = CGRectOffset(label.frame, 40, 0);
label.textColor = [UIColor colorWithRed:0 green:(48.f/255.f) blue:(84.f/255.f) alpha:1];
label.text = #"Select Track";
label.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:30];
label.minimumScaleFactor = 0.001;
label.adjustsFontSizeToFitWidth = YES;
label.lineBreakMode = NSLineBreakByClipping;
[temp addSubview:label];
UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, temp.bounds.size.height - 2, temp.bounds.size.width, 2)];
separator.backgroundColor = [UIColor colorWithRed:0 green:(48.f/255.f) blue:(84.f/255.f) alpha:1];
[temp addSubview:separator];
[screen addSubview:temp];
screen.layer.contentsGravity = kCAGravityCenter;
Edit
What's even weirder is that if I capture a UIImage of the view using:
- (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
and use that as the diffuse's content... everything works out perfectly fine?! It's really weird and frustrating since the image's size is exactly the same as the uiview's...
Edit 2
I ended up just using an image of the view as the texture, which makes things much more static than I needed. I won't set this as the answer because I'll still be waiting for a correct fix to this issue even if it in a long time. So, if you have an answer and this topic has been opened for a long time, please bump it if you can. The documentation on this section is just so poor.
New post on an old thread, but this day-in-age, it's possible to set the UIView itself as SCNMaterialProperty (diffuse) contents. Intention to support this feature is communicated directly from SceneKit engineering at Apple, though the documentation has not yet been updated to reflect it.
To tied back to the original post, do not set a UIView.layer as material property contents; instead set contents to the UIView itself.
[Update: according to Lance's comment below, support for views may be getting worse rather than getting better.]
The SceneKit docs pretty strongly suggest that, while there are cases where you can use animated CALayers as material content, that doesn't include UIView layers:
SceneKit cannot use a layer that is already being displayed elsewhere (for example, the backing layer of a UIView object).
That suggests that if you want to make animated content for your material, you're better off with either Core Animation used entirely on its own or SpriteKit.
I got the following code in a VC in an old project (no storyboard, pure code) :
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView = [[MKMapView alloc] initWithFrame:CGRectInset(self.view.frame, 10, 10) ];
[self.view addSubview:self.mapView];
self.view.backgroundColor = [UIColor redColor];
self.mapView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.view.translatesAutoresizingMaskIntoConstraints = NO; // <--- this line
}
If I comment the last line, a rotation from portrait to landscape or the other way is about 3 seconds under ios8 !! Also, occasionally at random times Unable to allocate render buffer storage! errors appear.
If I don't comment it, it's almost instantaneous (0.7seconds).
It seems it is only related to mapviews, the other views/VCs rotate just fine.
Under ios7 the rotation is fast in any case with that line commented or not.
Why ? And why is only the mapview affected ?
Edit: It seems clearly the autoresizingmask is wrong. If in viewDidLoad I set its value to none and manually change the frame in willRotate, it works fast.
I had the same problem when the application came back from the background. It froze a few seconds and then it worked again. I used a .xib file without Autolayout.
When I updated the .xib file and added the Autolayout option the problem was gone. I came up with this idea because you wrote that autoresizing was the problem in your solution.
I have the following sample code (using ARC) which adds a UIWebView as a subview and subsequently removes it (toggled by a tap gesture on the screen):
- (void)toggleWebViewLoading:(UITapGestureRecognizer *)sender
{
if (webView == nil)
{
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 100.0f)];
[webView loadRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:#"http://www.google.ca"]]];
[self.view addSubview:webView];
}
else
{
[webView removeFromSuperview];
webView = nil;
}
}
When the app initially loads with a blank UIView, it consumes approximately 1.29 MB (live bytes reading from Instruments.app). Tapping on the blank UIView causes the toggleWebViewLoading: function to fire which in turn creates a new UIWebView, loads Google, and adds it as a subview. Once this sequence of operations have been completed, the memory usage is approximately 3.61 MB. Tapping again executes the second part of toggleWebViewLoading: which removes the UIWebView from its superview and sets it to nil. At this point the memory consumption has dropped to 3.38 MB.
My question is, how can I completely reclaim the memory from UIWebView (i.e. have the memory consumption return to its initial value of 1.29 MB or something similar after the the UIWebView has been removed and set to nil)?
Other Relevant Information
Before someone asks why I care so much about ~2 MB of memory savings, I have I much more complicated situation using Xamarin/MonoTouch where 10+ UIWebView's are consuming 200 MB+ of memory and I can't ever seem to reclaim all of the memory when it is no longer needed. I think the answer boils down to this simple question.
I would suggest monitoring how many threads you have active. UIWebView spawns several threads for itself. I expect they are not cleaned up properly once the UIWebView is deallocated, but it's just a hunch.
The iPad app I'm working on is a book. To jump to a specific page, the user can press a button that overlays a view top of the current view, displaying images of thumbnails of each page in the book.
When the user goes through the book sequentially and displays this thumbnails menu, the scrolling animation is smooth and fine if the user showed the menu . The problem happens if the user calls showBookmarkMenu after having loaded about fifteen pages, the scrollview animation is very very slow, and the scrollview doesn't catch touches anymore.
I noticed that scrollViewDidEndDecelerating gets called when the scrolling animation is normal and smooth (shortly after loading the app), but it doesn't get called after the user has gone through several pages. So one hypothesis is that the CPU is struggling with the animation of the positioning of the scrollview's content. I ran the app using Instruments' Activity Monitor, but there are times when the app uses 97% and more of the CPU and the scrollview scrolls fine...
Any thoughts on this issue? I've posted my code below.
MainClass.m
//Called when user presses the open/close bookmark menu button
-(IBAction)toggleBookmarksMenu{
if([bookMarkMenu isHidden]){
[currentPage.view addSubview:bookMarkMenu];
[bookMarkMenu showBookmarkMenu];
}
else{
[bookMarkMenu hideBookmarksMenu];
}
}
ScrollViewClass.h
#interface BookmarkManager : UIView<UIScrollViewDelegate>{
UIScrollView *thumbnailScrollView;
}
#property (strong, nonatomic) UIScrollView *thumbnailScrollView;
#property (strong) id <BookmarkManagerDelegate> bookmarkManagerDelegate;
-(void)showBookmarkMenu;
-(void)hideBookmarksMenu;
#end
ScrollViewClass.m
-(void)showBookmarkMenu{
[self setHidden:NO];
[UIView animateWithDuration:0.5
animations:^{
self.center = CGPointMake(512, 384);
}
];
}
-(void)hideBookmarksMenu{
[UIView animateWithDuration:1
animations:^{
self.center = CGPointMake(512, -120);
}
completion:^(BOOL finished){
[self setHidden:YES];
[self removeFromSuperview];
}
];
}
-(id)init{
self = [super initWithFrame:CGRectMake(0, 0, 1024, 768)];
if(self){
[self setBackgroundColor:[UIColor clearColor]];
self.center = CGPointMake(512, 0);
thumbnailScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 1024, 120)];
[thumbnailScrollView setBackgroundColor:[UIColor clearColor]];
thumbnailScrollView.showsHorizontalScrollIndicator = NO;
//Add the UIButtons with images of the thumbnails
for(int i = 0; i < totalPages; i++){
UIButton *pageThumbnail = [UIButton buttonWithType:UIButtonTypeCustom];
pageThumbnail.frame = CGRectMake(0, 0, 125, 95);
[pageThumbnail setBackgroundImage:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/p%d_thumb.png", [[NSBundle mainBundle] resourcePath], i]] forState:UIControlStateNormal];
[thumbnailScrollView addSubview:pageThumbnail];
[pageThumbnail addTarget:self action:#selector(thumbnailTapped:) forControlEvents:UIControlEventTouchDown];
}
[self addSubview:thumbnailScrollView];
[thumbnailScrollView setContentSize:CGSizeMake(totalPages * 125 + (20*(totalPages+1)), 120)];
[thumbnailScrollView setDelegate:self];
[self setHidden:YES];
}
return self;
}
I have to go with possible low memory issue.
A possible alternative to using a slew of buttons is using UITableView. The way your code is currently working, it loads up ALL the buttons with images. For a large book this could be painful.
Using UITableView you only use as much memory as you see (about). And, since each image is loaded dynamically, your memory usage is only as much as is displayed. That would be how I would go about it (actually, I'm doing that now, just not with a book).
A shot in the dark, based on your observation that the scrolling becomes slow after loading 15 pages or so: possibly your device is busy handling a low memory condition. In such cases, as you possibly know, a system wide notification is sent to a considerable number of apps/objects for them to recover as much memory as possible.
Could you check if at more or less the same time when the scrolling becomes slow your app is executing didReceiveMemoryWarning?
If you confirm that the issue could be related to memory saturation/reclaiming, then I would suggest implementing a lazy loading scheme for your images:
you only load images when you are required to display them;
you only keep in memory 3-5 images total, to ensure a smooth scrolling.
The basic step requires id providing your delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
implementation. Here you will preload images:
knowing your position, you know your current image (say, image number N);
unload images N-2, N+2;
load images N-1, N+1.
The images to load/unload I provided are fine if you just want one "buffer" image.
In any case, if you google "iso scroll view lazy loading" you will find plenty of info.
Turns out it wasn't a low memory issue, but an overly busy CPU issue.
It is the CPU that does the calculations required for the scrollview's scrolling animations, and when the scrolling becomes this slow I thought I'd try to figure out why I was using 97% of the CPU in the first place. Turns out that past page 15, I had CPU-intensive recursive functions (calculating UIBezierPaths for another part of the app) caught in an infinite loop. The app was calculating hundreds of UIBezierPaths a second, and there reached a point where the CPU just couldn't keep up with the calculations for the scrollview's animation.
Once I made sure the recursive functions stopped calling themselves when they were not needed, CPU usage remained under 20% throughout the app, and the scrollview performed perfectly well.
I'm working on an app that is ideally targeted all the way down to iOS 3.2. Still, I am developing it on Lion and with the latest 5 sdk. As far as I know, I am not using any sdk 5 specific features. But:
on any devices with iOS 5 or the simulator (set to v.5), the app works just fine.
on any devices with iOS 4.3 or below (and the same goes for the simulator set to v. 4.3), several things that have to do with view frames get misaligned.
For instance, here's 2 examples:
An activity indicator inside an alert view. Here's the code:
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:fileRequest delegate:self];
if(urlConnection)
{
uistatusDialog = [[UIAlertView alloc] initWithTitle:(description ? NSLocalizedString(description, nil) : NSLocalizedString(#"Downloading", nil))
message:nil
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);
[indicator startAnimating];
[uistatusDialog addSubview: indicator];
[uistatusDialog show];
[indicator release];
And here are screenshots for both simulators:iOS 5: correct
iOS 4.3: misaligned
Similar things are happening with labels for which I set frames through [UILabel alloc]initWithFrame:CGRectMake(...].
This code, for instance:
UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:reuseIndentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
UILabel* mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(70, 0, 0, 20)] autorelease];
mainLabel.font = [UIFont boldSystemFontOfSize:(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 18 : 12)];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.backgroundColor = [UIColor clearColor];
mainLabel.autoresizingMask = (UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleRightMargin);
//mainLabel.adjustsFontSizeToFitWidth = YES;
mainLabel.tag = MAINLABEL_TAG;
Aligns just fine in iOS5, both for the simulators and devices. But in 4.3 it doesn't.
I can only think that the local coordinate frame changed from one SDK to the next?
Any help is greatly appreciated!
EDIT: Just to pull it off for now, I did end up replacing all instances of CGRectMake(x,y,w,h) with something along the lines of (assuming x,y,w,h are the ones I would have used for CGRectMake):
CGrect refFrame = superview.frame;
refFrame.origin.x += x;
refFrame.origin.y += y;
refFrame.size.w = w;
refFrame.size.h = h;
theObjInQuestion.frame = refFrame;
So essentially, looks like a different frame of reference is being used between SDK 5 and 4.3 at least...
I had a similar issue with one UIImageView in our app being displaced downwards about 100pts on screen, appearing to be displaced by other content that should have been floating on top of the UIImageView (though that may have been a coincidence).
The 'solution' I found in our case was to disable auto-sizing for the top positioning attribute for the UIImageView in IB, by clicking on the red I in the Autosizing display on the Size Inspector in Interface Builder. I call this a 'solution' rather than a solution because it remains unclear to me why this was a problem at all, and why this only occurred for this one view and only in iOS 5.
I also found that repositioning this view up, or down, prevented it from being displaced. It was only when it was aligned with the top edge of its parent view that the issue occurred.
My conclusion was it was probably a bug in iOS 5, rather than a new intended or more strict behavior, but I remain uncertain.
There are some major differences between 4 and 5, though I've only begun to figure them out. Something has changed in the coordinate systems, but precisely what I don't know.
I kinda suspect that the best/safest thing to do is to have two entirely different paths for calculating layout, until someone can figure out all of the "gotchas". That way the two versions can be "tuned" separately.