UIImagePickerController: ignoring request to take picture; camera is not yet ready - ios4

I am using camera in my application.
I want to take picture after 3 seconds automatically.
The code is working absolutely fine accept for one case..
If application goes into background while camera tick is going on by any ways like if call comes in-between or user presses home key...then when the application is resumed it does not continue the camera tick and in console it gives this warning
UIImagePickerController: ignoring request to take picture; camera is not yet ready.
I want to restart the camera when such thing happens
what should i do?

we can use these app delegate functions
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 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.
}

What i did to solve this issue:
- (void)viewDidAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(cameraIsReady:)
name:AVCaptureSessionDidStartRunningNotification object:nil];
self.ready = NO;
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// There is not a camera on this device, so don't show the camera button.
[self showImagePickerForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
} else {
[self showImagePickerForSourceType:UIImagePickerControllerSourceTypeCamera];
}
}
- (void)cameraIsReady:(NSNotification *)notification {
self.ready = YES;
}
- (IBAction)takePhoto:(id)sender {
if (self.ready) {
[self.imagePickerController takePicture];
}
self.ready = NO;
}

Related

How to handle watchOS CoreData background save correctly?

My watchOS app uses core data for local storage. Saving the managed context is done in background:
var backgroundContext = persistentContainer.newBackgroundContext()
//…
backgroundContext.perform {
//…
let saveError = self.saveManagedContext(managedContext: self.backgroundContext)
completion(saveError)
}
//…
func saveManagedContext(managedContext: NSManagedObjectContext) -> Error? {
if !managedContext.hasChanges { return nil }
do {
try managedContext.save()
return nil
} catch let error as NSError {
return error
}
}
Very rarely, my context is not saved. One reason I can think of is the following:
After my data are changed, I initiate a background core data context save operation.
But before the background task starts, the watch extension is put by the user into background, and is then terminated by watchOS.
This probably also prevents the core data background save to execute.
My questions are:
- Is this scenario possible?
- If so, what would be the correct handling of a core data background context save?
PS: On the iOS side, I do the same, but here it is possible to request additional background processing time using
var bgTask: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: {
//…
application.endBackgroundTask(bgTask)
}
By now, I think I can answer my question:
If the watch extension is put by the user into background, the extension delegate calls applicationDidEnterBackground(). The docs say:
The system typically suspends your app shortly after this method
returns; therefore, you should not call any asynchronous methods from
your applicationDidEnterBackground() implementation. Asynchronous
methods may not be able to complete before the app is suspended.
I think this also applies to background tasks that have been initiated before, so it is actually possible that a core data background save does not complete.
Thus, the core data save should be done on the main thread. My current solution is the following:
My background context is no longer set up using persistentContainer.newBackgroundContext(), since such a context is connected directly to the persistentContainer, and when this context is saved, changes are written to the persistent store, which may take relatively long. Instead, I now set up the background context by
var backgroundContext = NSManagedObjectContext.init(concurrencyType: .privateQueueConcurrencyType)
and set its parent property as
backgroundContext.parent = container.viewContext
where container is the persistent container. Now, when the background context is saved, it is not written to the persistent store, but to its parent, the view content that is handled by the main thread. Since this saving is only done in memory, it is pretty fast.
Additionally, in applicationDidEnterBackground() of the extension delegate, I save the view context. Since this is done on the main thread, The docs say:
The applicationDidEnterBackground() method is your last chance to
perform any cleanup before the app is terminated.
In normal circumstances, enough time should be provided by watchOS. If not, other docs say:
If needed, you can request additional background execution time by
calling the ProcessInfo class’s
performExpiringActivity(withReason:using:) method.
This is probably equivalent to setting up a background task in iOS as shown in my question.
Hope this helps somebody!

What is the proper way to do GameCenter authentication?

I have seen in posts around stack overflow that shows snippets of handling GameCenter authentication. However, none of these solutions address any of the problems that real world use cases cover. Namely, the [GKLocalPlayer localPlayer].authenticateHandler is just a call back of the status, and not much else. It provides a view controller, but there are massive inconsistencies in .authenticated, and error states.
There are a few things I am trying to do:
1. Not pop up the game center login until a feature uses it
2. Try to authenticate silently on app launch
3. Provide some info to the user why GameCenter features are not working
4. Provide a recovery mechanism
Namely if there is an error reported how can I show the login dialog anyways?
I get this error with no viewController:
Case 1:
Error in GameCenterManager::authenticateLocalPlayer [The Internet connection appears to be offline.]
Despite its error message, the device is completely online, as safari loads cnn.com just fine.
Case 2:
Someone closes the login screen because they are not ready, in which case .authenticated comes back as true, viewController remains at nil, yet all game center calls will fail. Why is the [GKLocalPlayer localPlayer].authenticated set to true when it isn't?
Case 3:
Error in GameCenterManager::authenticateLocalPlayer [The operation
couldn’t be completed. (NSURLErrorDomain error -1009.)]
This keeps occurring yet there is nothing the app can do for the user. In this case what should the messaging be? Switch apps to Game Center and login there?
Case 4:
Error in GameCenterManager::authenticateLocalPlayer [The requested
operation has been canceled or disabled by the user.]
This happens if the user cancels the viewController the app was told to present by apple. Yet, there is also no recovery or detecting this state.
Case 5:
Error in GameCenterManager::createMatch [The requested operation could
not be completed because local player has not been authenticated.]
This happens if the user was logged in, but for whatever reason logs out of GameCenter then returns to the app. The app will be told the user is still authenticated when it is clearly not, yet there are no calls I can make to bring up another login.
So essentially, if GameCenter doesn't just silently work, what are we to do as app designers? Alert view and tell them to go login using the game center app and restart the app?
Here is my authentication code:
//******************************************************
// Authenticate
//******************************************************
-(void)authenticateLocalPlayer:(bool)showLogin
{
if( showLogin && self.loginScreen != nil )
{ [[WordlingsViewController instance] presentViewController:self.loginScreen animated:YES completion:nil]; }
if( [GKLocalPlayer localPlayer].isAuthenticated )
{
NSDLog(NSDLOG_GAME_CENTER,#"GameCenterManager::authenticateLocalPlayer LocalPlayer authenticated");
}
__weak GameCenterManager* weakSelf = self;
[GKLocalPlayer localPlayer].authenticateHandler = ^(UIViewController *viewController, NSError *error)
{
if (error != nil)
{
NSDLog(NSDLOG_GAME_CENTER,#"Error in GameCenterManager::authenticateLocalPlayer [%#]", [error localizedDescription]);
}
else
{
if (viewController != nil)
{
NSDLog(NSDLOG_GAME_CENTER,#"GameCenter: No authentication error, but we need to login");
weakSelf.loginScreen = viewController;
}
else
{
if ( [GKLocalPlayer localPlayer].authenticated )
{
NSDLog(NSDLOG_GAME_CENTER,#"GameCenter localPlayer authenticated");
weakSelf.gameCenterAvailable = YES;
weakSelf.localPlayer = [GKLocalPlayer localPlayer];
[weakSelf retrieveFriends];
[weakSelf loadPlayerPhoto:weakSelf.localPlayer];
for ( id<GameCenterDelegate> listener in weakSelf.listeners )
{ [listener onPlayerAuthenticated]; }
}
else
{
weakSelf.gameCenterAvailable = NO;
}
}
}
};
}
This function is called twice: once at app startup to hopefully create a valid login state, and 2nd if the user is not authenticated and they try to use an app feature that requires game center. In this app, it is creating a turn based match or viewing friends
You're encountering many of the same complaints I have about the Game Center API. I've been trying to achieve the same 4 things you are. The TL;DR version: Game Center simply doesn't support it. >< But there are some things you can do to reduce the pain.
One general thing that helped me: make sure to check both the NSError as well as it's .underlyingError property. I've seen several cases where the NSError is too vague to be helpful, but the underlying error has more specific details.
Case 1: Can you share the error domain and error code for the both the NSError and the underlyingError?
Case 2: I have an open bug with Apple on this, for a looooong time. There are several cases, including being in Airplane mode, where the authentication fails but .authenticated returns true. When I wrote a bug on this, Apple closed it saying this was "by design" so players could continue to play the game using any previously cached data. So, I appended the bug with several scenarios where cached data causes significant problems. My bug was re-opened and has sat there ever since. The design philosophy seems to be: "well, just keep going and maybe it will all work out in the end." But it doesn't work out in the end, the user gets stuck, unable to play and they blame my game, not Apple.
The only mitigation I have found is exactly what you're already doing: Always always always check the NSError first in the authentication handler. The view controller and .authenticated are totally unreliable if an error has been set.
If there is an error, I pass it to one dedicated error handler that displays alerts to users and tells them what they need to do to recover.
Case 3: I have hit -1009 as well. From what I can discern it happens when I have network connection, but Game Center never replied. That could come from any disruption anywhere between my router up-to-and-including Game Center servers not responding. I used to see this a lot when using the GC Test Servers. Not so much now that the test servers were merged into the prod environment.
Case 4: You are 100% correct. there is no in-game recovery. If the user cancels the authentication, that's the end of the line. The only way to recover is to kill the game (not just leave and re-enter) and restart it. Then, and only then, you can present another login view controller.
There are some things you can do to mitigate this, though. It will directly break your #1 goal of delaying login until needed, but I haven't found anything better:
Disable the "start game" button (or whatever you have in your game) until you've confirmed the login succeeded with no errors AND you can successfully download a sample leaderboard from GC. This proves end-to-end connectivity.
If the user cancels the login, your authentication handler will receive an NSError of domain = GKErrorDomain and code = GKErrorCanceled. WHen I see that combo, I put up a warning to the user that they cannot play network games until they've successfully logged in and to login they will have to stop and restart the game.
Users were confused why the "start" button was disabled, so I added an alert there too. I show a button that looks disabled but is really enabled. And when they try to click it, I again present an alert telling them they have to login in to game center to play a network game.
It sucks, but at least the user isn't stuck.
Case 5: This is one of the examples I cited in my bug referred to in case 2. By letting the user think they're logged in when they really aren't, they try to do things they really can't do, and eventually something bad will happen.
The best mitigation I have found for this is the same as Case 4: don't let the user start a session until you see the authentication handler fire with no errors AND you can successfully download a sample leaderboard to prove the network connection.
In fact, doing a search through all of my code bases, I never use .authenticated for any decisions anymore.
Having said all of that, here's my authentication handler. I won't say it's pretty, but thus far, users don't get stuck in unrecoverable situations. I guess it's a case of desperate times (working with a crap API) requires desperate measures (kludgy work arounds).
[localPlayer setAuthenticateHandler:^(UIViewController *loginViewController, NSError *error)
{
//this handler is called once when you call setAuthenticated, and again when the user completes the login screen (if necessary)
VLOGS (LOWLOG, SYMBOL_FUNC_START, #"setAuthenticateHandler completion handler");
//did we get an error? Could be the result of either the initial call, or the result of the login attempt
if (error)
{
//Here's a fun fact... even if you're in airplane mode and can't communicate to the server,
//when this call back fires with an error code, localPlayer.authenticated is set to YES despite the total failure. ><
//error.code == -1009 -> authenticated = YES
//error.code == 2 -> authenticated = NO
//error.code == 3 -> authenticated = YES
if ([GKLocalPlayer localPlayer].authenticated == YES)
{
//Game center blatantly lies!
VLOGS(LOWLOG, SYMBOL_ERROR, #"error.code = %ld but localPlayer.authenticated = %d", (long)error.code, [GKLocalPlayer localPlayer].authenticated);
}
//show the user an appropriate alert
[self processError:error file:__FILE__ func:__func__ line:__LINE__];
//disable the start button, if it's not already disabled
[[NSNotificationCenter defaultCenter] postNotificationName:EVENT_ENABLEBUTTONS_NONETWORK object:self ];
return;
}
//if we received a loginViewContoller, then the user needs to log in.
if (loginViewController)
{
//the user isn't logged in, so show the login screen.
[appDelegate presentViewController:loginViewController animated:NO completion:^
{
VLOGS(LOWLOG, SYMBOL_FUNC_START, #"presentViewController completion handler");
//was the login successful?
if ([GKLocalPlayer localPlayer].authenticated)
{
//Possibly. Can't trust .authenticated alone. Let's validate that the player actually has some meaningful data in it, instead.
NSString *alias = [GKLocalPlayer localPlayer].alias;
NSString *name = [GKLocalPlayer localPlayer].displayName;
if (alias && name)
{
//Load our matches from the server. If this succeeds, it will enable the network game button
[gameKitHelper loadMatches];
}
}
}];
}
//if there was not loginViewController and no error, then the user is already logged in
else
{
//the user is already logged in, so load matches and enable the network game button
[gameKitHelper loadMatches];
}
}];

Notification sound not playing in J2ME

I am working on a J2ME application.
I am using Nokia 6131 NFC phone. I am using NetBeans IDE.
I have 4 forms and I am playing some notification sounds for the user while filling the form.
The problem is sound goes off suddenly after 3 to 4 min and the only solution is to exit the application and again open it.
My Code
public void playSoundOK()
{
try
{
InputStream is = getClass().getResourceAsStream("/OK.wav");
Player player = Manager.createPlayer(is,"audio/X-wav");
player.realize();
player.prefetch();
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Exception
at com.nokia.mid.impl.isa.mmedia.audio.AudioOutImpl.openSession(AudioOutImpl.java:206)
at com.nokia.mid.impl.isa.mmedia.MediaOut.openDataSession(MediaOut.java:282)
at com.nokia.mid.impl.isa.mmedia.MediaPlayer.doPrefetch(MediaPlayer.java:155)
at com.nokia.mid.impl.isa.amms.audio.AdvancedSampledPlayer.doPrefetch(+4)
at com.nokia.mid.impl.isa.mmedia.BasicPlayer.prefetch(BasicPlayer.java:409)
at org.ird.epi.ui.UtilityClass.playSoundOK(UtilityClass.java:139)
at org.ird.epi.ui.EnrollmentForm.targetDetected(+695)
at javax.microedition.contactless.DiscoveryManager.notifyTargetListeners(DiscoveryManager.java : 700)
at javax.microedition.contactless.DiscoveryManager.access$1200(DiscoveryManager.java:103)
at javax.microedition.contactless.DiscoveryManager$Discoverer.notifyIndication(DiscoveryManager.java:882)
at com.nokia.mid.impl.isa.io.protocol.external.nfc.isi.NFCConnectionHandler$IndicationNotifier.run(+67) javax.microedition.media.MediaException: AUD
I would advise you to split NFC and audio playback into 2 different threads.
It is typically a bad idea to call a method that should take some time to complete (like prefetch) from inside an API callback (like targetDetected) because it makes you rely on a particularly robust kind of internal threading model that may not actually exist in your phone's implementation of MIDP.
You should have one thread whose sole purpose is to play the sounds that your application can emit. Use the NFC callback to send a non-blocking command to play a sound (typically using synchronized access to a queue of commands). The audio playback thread can decide to ignore commands if they were issued at a time when it was busy playing a sound (no point in notifying the users of multiple simultaneous NFC contacts)
You should close your player. Add the following code to your method:
PlayerListener listener = new PlayerListener() {
public void playerUpdate(Player player, String event, Object eventData) {
if (PlayerListener.END_OF_MEDIA.equals(event)) {
player.close();
}
}
};
player.addPlayerListener(listener);

Notification on background thread updates NSView

There is a task needs to draw N images on a NSView.
But at the beginning I do not know the amount of images, so I set it works in a thread of background.
[NSThread detachNewThreadSelector:#selector(workInBackgroundThread:) toTarget:self withObject:nil];
when it get the amount of images, it will send a notification
- (void)workInBackgroundThread:(id)unusedObject {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//get image amount....
[[NSNotificationCenter defaultCenter] postNotificationName:#"gotImageAmount" object:nil];
//...
//continue to load images
}
I try to resize the NSView depends on the amount of images in the notification function
-(void)processGotImagesAmount:(NSNotification*)notification
{
//others codes
[myNSView setFrame:CGRectMake(0, 0, calculateNewWidth, caculatedNewHeight)];//line A
//others codes
}
but when the app executes the line A, it freezes,
[myNSView setFrame:CGRectMake(0, 0, calculateNewWidth, caculatedNewHeight)];
itself has no problem, if I click a bottun to call it, it works!
but it looks like it does not work in a notification function
Welcome any comment
You're posting the notification from the background thread.
From the NSNotificationCenter docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html
In a multithreaded application, notifications are always delivered in
the thread in which the notification was posted
In your notification handling code you're updating ui which you must do from the main thread. Try moving that code to another method and then in the notification handling code, call it with performSelectorOnMainThread.
Another option is GCD without notifications. I posted a sample in this S.O. answer:
GCD, Threads, Program Flow and UI Updating

How to clean up AVCaptureSession in applicationDidEnterBackground?

I have an app that uses AVCaptureSession to process video. I like to write with zero memory leaks, and proper handling of all objects.
That's why this post - How to properly release an AVCaptureSession - was tremendously helpful - Since [session stopRunning] is asynchronous, you can't just stop the session and continue to release the holding object.
So that's solved. This is the code:
// Releases the object - used for late session cleanup
static void capture_cleanup(void* p)
{
CaptureScreenController* csc = (CaptureScreenController*)p;
[csc release]; // releases capture session if dealloc is called
}
// Stops the capture - this stops the capture, and upon stopping completion releases self.
- (void)stopCapture {
// Retain self, it will be released in capture_cleanup. This is to ensure cleanup is done properly,
// without the object being released in the middle of it.
[self retain];
// Stop the session
[session stopRunning];
// Add cleanup code when dispatch queue end
dispatch_queue_t queue = dispatch_queue_create("capture_screen", NULL);
dispatch_set_context(queue, self);
dispatch_set_finalizer_f(queue, capture_cleanup);
[dataOutput setSampleBufferDelegate: self queue: queue];
dispatch_release(queue);
}
Now I come to support app interruptions as a phone call, or pressing the home button. In case application enters background, I'd like to stop capturing, and pop my view controller.
I can't seem to do it at the applicationDidEnterBackground context. dealloc is never called, my object remains alive, and when I reopen the app the frames just start coming in automatically.
I tried using beginBackgroundTaskWithExpirationHandler but to no avail. It didn't change much.
Any suggestions?
Thanks!
I don't have an answer to your question.
But I also read the thread you mentioned and I'm trying to implement it.
I'm surprised you have this code in the stopCapture function:
// Add cleanup code when dispatch queue end
dispatch_queue_t queue = dispatch_queue_create("capture_screen", NULL);
dispatch_set_context(queue, self);
dispatch_set_finalizer_f(queue, capture_cleanup);
[dataOutput setSampleBufferDelegate: self queue: queue];
dispatch_release(queue);
I thought that code was required as part of the session initialization. Does this work for you?
Does your capture_cleanup function get called? mine isn't getting called and I'm trying to figure out why.

Resources