iPhone screen shifts when entering foreground - iphone

I've noticed that when my iPhone app enters the foreground after being suspended on an iPad2 (iOS version 4.3.3), the iPhone screen seems to shift up by a small amount after a split second. My understanding is that iOS takes a snapshot of the screen before suspending the app so it can quickly bring it back up when resuming, but it's not clear to me why it would be shifted. The status bar placeholder and iPhone image don't shift up, only the rest of the iPhone screen does. I don't see this problem in the 5.0 simulator.
Any ideas what's going on or how to fix this? Thanks

When the app loads, it displays the default.png file that you have in your app bundle. If you have this image the same as whatever the first screen of your app is (which apple suggests that you should do) then it is displaying this image, and then the actual screen once the app is done initializing. You can edit the png file by shifting up a pixel or two (you'll just have to guess and check to see exactly what you need).
The other possibility is that your default.png isnt the right size, so it is being resized when the app actually starts. Check that the dimensions are correct for the device you are testing on.

Setting the status bat to initially hidden caused this for me.
Status bar is initially hidden YES
This fixed it
- (void) setStatusBarVisible: (NSTimer *)timer
{
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:#selector(setStatusBarVisible:) userInfo:nil repeats:NO];
}
It appears that setting then reseting (after a short delay) the status bar addresses this issue.
This fixes it but it shouldn't happen in the first place.

yes it happens when you come again to foreground. it happens with me & i have solved this issue by using
(void)layoutSubviews
that means i draws the things in layoutSubviews method which shifts & it works fine.
for more information on this check my problem & solution

Related

How to know if a task is executing in background

In my app I'm downloading lots of images on a method.
I'm using a
downloadTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:downloadTask];
downloadTask = UIBackgroundTaskInvalid;
}];
This is working fine, if I press the home or sleep button, the images continue downloading.
I'm showing the progress in a UIProgressView inside an UIAlertView, and when the percent is 100% the alertView is dissmised and I change the viewController to other where I show the donwloaded images.
But I only want this to happen if the app is really active at the moment the download finish.
I have been looking at the app state and while it's downloading with the screen off.
[UIApplication sharedApplication].applicationState
the state is UIApplicationStateActive during all the donwload
How can I can know if the downloading is happening with the screen off or on?
EDITED AFTER ACCEPTING THE ANSWER:
I just discovered, if I tap the home button, the app enters in UIApplicationStateBackground, if I tap the wake/sleep it enters in UIApplicationStateInactive
Following the approach of the correct answer, my app contines donwloading in both cases.
The screen is off in two states (apart from when the app has not been even opened):
suspended : in this case you don't have to worry because the download won't procede until the app gets active again; It will enter this state on
background : it's in this state for a limited amount of time before going in suspend, and the screen is already off in this moment. Here you may want to check then whether to do all the things you said or not, because in this state code can be still executed. In this state the app status is UIApplicationStateBackground, so you could just perform a check like this:
You probably want to check whether the app is in background execution in order to achieve the result. Just like this:
if([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
// Do stuff
}
If it's in background, so the screen is off.
UPDATE: after few test, what I figured out is that the behaviour you are expieriencing is probably due to the execution of the download on the main thread.
You should send the download on (for instance) the global queue. This way the application will enter the background state as expected:
....
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.bti];
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doBackgroundStuff];
});
....
This way, if the app is put on background while the download is in progress, the application state will turn into UIApplicationStateBackground, and then you can check it as I wrote initially. If you are doing UI updates during the progress remember to send them back to the main thread (because the download is now on a different one).
You can check whether your app is running in the background or not by setting a flag in the designated application delegate methodsapplicationDidEnterBackground: and applicationWillEnterForeground:. Example:
- (void)applicationDidEnterBackground:(UIApplication *)application
_applicationRunsInForeground = NO;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
_applicationRunsInForeground = YES;
}
If you don't want to have this _applicationRunsInForeground flag inside your application delegate, you could observe the delegate's NSNotifications in your viewcontroller class instead (UIApplicationWillEnterForegroundNotification and UIApplicationDidEnterBackgroundNotification).

How do I detect orientation on app launch for splash screen animation on iPad!

Hi I have an app and I have two *.pngs for default splash screen:
Default-Landscape.png
Default-Portrait.png
What I want is to animate this default splash screen away when my app is loaded and ready to go.
To achieve this I would normally present an UIImageView with either default-landscape or default-portrait (depending on the device orientation), keep it on screen for a certain time and then animate it away.
My problem is that if I call [[UIDevice currentDevice] orientation] in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
The answer is always that the device is in portrait orientation even if I clearly have it in landscape. I tried this in simulator and on the device as well and the behaviour is the same.
Does anyone know a fix for this or maybe some other approach?
Thanks!
I had troubles with this and I solved it by making one image 1024x1024 and setting the contentMode of the UIImageView to UIViewContentModeTop, then using left and right margin autoresizing. So long as your portrait and landscape default images are the same layout then this will work fine.
Just to clarify here's what I used:
bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:SplashImage]];
bgView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
bgView.contentMode = UIViewContentModeTop;
To get around this problem I installed the splash image view inside of a view controller that allowed both orientations. Even though the device reported the wrong orientation at startup, the view controller seems to get the right one.
You can use UIApplication statusBarOrientation as follows:
if ( UIDeviceOrientationIsLandscape( [[UIApplication sharedApplication] statusBarOrientation] ))
{
// landscape code
}
else
{
// portrait code
}
Maybe you could show a blank view with black background at start time and place [[UIDevice currentDevice] orientation] into this view's viewDidAppear and start your splash screen from there?
Another solution would be to read the accelerometer data and determine the orientation yourself.
To know at start what is the orientation (UIDevice orientation don't work until user have rotate the device) intercept shouldAutorotateToInterfaceOrientation of your View Controller, it is called at start, and you know your device orientation.
There are certainly times when you want to transition from the loading image to something else before the user gets control of your app. Unless your app is really simple, going from loading image to landing page probably won't be sufficient without making the app experience really suck. If you ever develop a large app, you'll definitely want to do that to show progress during setup, loading xibs, etc. If an app takes several seconds to prepare with no feedback, users will hate it. IMO, there's nothing wrong with a nice transition effect either. Almost nobody uses loading screens the way Apple suggests to. I don't know which apps you looked at that showed the "empty UI" type loading screens they suggest. Heck, even Apple doesn't do that except in their sample code and none of my clients would find that acceptable. It's a lame design.
Only the first view added to the window is rotated by the OS. So if you want your splash screen to automatically rotate AND your main view is rotatable then just add it as a child of that view.
Here is my code for fading out the appropriate splash screen image:
// Determine which launch image file
NSString * launchImageName = #"Default.png";
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
launchImageName = #"Default-Portrait.png";
} else {
launchImageName = #"Default-Landscape.png";
}
}
// Create a fade out effect
UIImageView* whiteoutView = [[[UIImageView alloc] initWithFrame:self.window.frame] autorelease];
whiteoutView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
whiteoutView.autoresizesSubviews = YES;
whiteoutView.image = [UIImage imageNamed:launchImageName];
[[[self.window subviews] objectAtIndex:0] addSubview:whiteoutView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
whiteoutView.alpha = 0.0;
[UIView commitAnimations];
Note: You'll have to update it to support hi-res screens.
It sounds like you're not using the launch image the way Apple recommends in the iOS HIG. It specifically calls out that you should not use it as a splash screen, but rather as a skeleton version of your actual UI. The net effect is that your app appears to be ready just that much faster.
The suggestions that you could draw a splash screen yourself after the app has launching in viewDidAppear or similar also are missing the basic purpose of a launch image. It's not a splash screen. If your app is ready, let the user interact with it, don't waste their time drawing a splash screen.
From my five minute survey of Apple apps and third-party apps, everyone showed a portrait launch image, loaded the portrait version of the UI, and then rotated to landscape. It's been a while since programming on iOS, but I think this mirrors the order of the method calls -- first your app gets launched, then it is told to rotate to a particular orientation.
It might be a nice enhancement request to file with Apple though :)

Dynamically calculate application load time

How can I run a clock that allows me to measure the time to load until appDidFinishLaunching ?
I want to set a sleep call that extends the Defaul.png show time to 3 seconds regardless the speed of the underlying hardware.
First off, you should know that Springboard in iPhone OS is kinda picky about load times. You should never make a sleep call somewhere in the loading process of you application. If Springboard detects that your application is taking too long to launch, your application will be terminated with "failed to launch in time" in the crash log.
Secondly, there is no, as far as I know, way of measuring the time your application took to launch. There are several thing happening when the user taps the Application icon on the springboard, and the iPhone OS provides no good information to your application.
One solution could be to make sure your applicationDidFinishLaunching: is very lightweight, and creating a "fake" Default.png overlay. By trimming down your applicationDidFinishLaunching: method to do only the most essential stuff, and the performing any time consuming tasks in the background, you can ensure that your Default.png overlay is displayed roughly the same time on different hardware.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create the image view posing with default.png on top of the application
UIImageView *defaultPNG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Default.png"]];
// Add the image view top-most in the window
[window addSubview:defaultPNG];
[window makeKeyAndVisible];
// Begin doing the time consuming stuff in the background
[self performSelectorInBackground:#selector(loadStuff) withObject:nil];
// Remove the default.png after 3 seconds
[self performSelector:#selector(removeDefaultPNG:) withObject:defaultPNG afterDelay:3.0f];
}
- (void)removeDefaultPNG:(UIImageView *)defaultPNG {
// We're now assuming that the application is loaded underneath the defaultPNG overlay
// This might not be the case, so you can also check here to see if it's ok to remove the overlay
[defaultPNG removeFromSuperview];
[defaultPNG release];
}
If you add more views (your view controllers etc) in the loadStuff method, you should insert them below the defaultPNG overlay. You should also be aware of problems that could occur by doing these things from another thread. You could use performSelectorOnMainThread:withObject:waitUntilDone: if you encounter problems.

How to stop MPMusicPlayerController from enabling screen locking

I have an application that requires the iPhone screen to remain active (or not, depending on user choice). I've done this by disabling the application idle timer, which works fine and dandy until I start playing media via the MPMusicPlayerController. Due to a bug in the SDK, this then reenables the idle timer with no apparent way to disable it again.
My app flow is:
App starts
Screen stays on
<...time passes...>
Play audio file
Idle timer kicks in
Screen turns off
I have an empty audio file playing in the background to stop the phone going into deep sleep, but I'd really like to keep the screen unlocked too.
Has anyone managed to figure out a workaround for this?
I had a similiar problem, and found a fix for it. The fix might work for you too:
I call a method periodically (every 10 seconds), which sets idleTimerDisabled first to NO, then to YES.
- (void)calledEveryTenSeconds
{
[UIApplication sharedApplication].idleTimerDisabled = NO;
[UIApplication sharedApplication].idleTimerDisabled = YES;
}
Only setting to YES alone does not fix the problem. It seems the property has to change first to be recognized by UIApplication.
My problem was, that the screen kept turning dark as soon as I switched music tracks on the iPod player via the headphone remote. My guess is, that this is the same issue as you are experiencing.
You should simply turn off the idle timer. What I usually do in a viewcontroller that needs to stay 'awake' is this:
- (void) viewWillAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
}
- (void) viewWillDisappear: (BOOL) animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled: NO];
}
This will make sure the screen will not get locked due to user inactivity.
I found a solution to this problem. Invoke a method that disables the idleTimer in about 5 seconds after you start playing the music. It's a bit of a hack, but it is a workaround.
[[SoundEngine mainEngine] playMusic];
[self performSelector:#selector(setIdleTimeDisabled) withObject:nil afterDelay:5.0];
- (void) setIdleTimeDisabled {
[UIApplication sharedApplication].idleTimerDisabled = YES;
NSLog(#"Setting idleTimer to TRUE");}
let player = MPMusicPlayerController.applicationMusicPlayer()
player.setQueueWithStoreIDs(["some id"])
player.play()
player.pause()

How to delay Default.png?

How can I delay the app loading to show the splash screen for longer?
You should let the app start as usual then make the first view that appears have the identical image on it as the splash screen. Start a timer and then replace that view with your real application root view after a few seconds.
Deliberately delaying the actual application launch is a big no-no.
UPDATE: No seriously, DON'T do this!
Or us the C function
sleep(9);
Putting this in applicationDidFinishLaunching: will cause you program to pause for 9 seconds, any other integer may be entered as well.
EDIT: I've learned a lot in the past year. Don't do this. The reason being that the springboard will automatically stop the app launching if it takes too long. That timing is poorly documented so even one second can result in the app failing.
This question is similar: splash screen like tap tap revenge 3
Basically, in your applicationDidFinishLaunching:, add an image view on top of other views containing your Default.png.
See the above discussion of why you probably should not delay your app load in this way. But if you happen to have a scenario where sleeping for short duration would be preferable to the overhead of switching out a view, use NSThread's sleepForTimeIntervale instead of sleep(). It's more framework friendly and you have more granular control over the sleep time:
[NSThread sleepForTimeInterval:0.75]
I had a situation where the client had to demo the launch image. So, this was my solution..
- (void)applicationDidBecomeActive:(UIApplication *)application
{
UIImageView *defaultImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Default#2x.png"]];
[self.window addSubview:defaultImageView];
sleep(2);
[defaultImageView removeFromSuperview];
[defaultImageView release];
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
You can use it sleep method to get this result "
sleepForTimeInterval
", If you want to get it launch time, do like :
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
[NSThread sleepForTimeInterval:8.0];
}
It will delay the launch by 8 seconds
Warning : But it is not recommended by apple, as it will the watchdod about long time for your app loading, It can kill your app.
But incase if you need it to get some specific screenshot or for some in-house use, you can use to solve for purpose but never in app submission.