Is it possible to open running background app on in Objective c - ios

open my app from background running on a specific timing..
want to do somthing like this
- (void)applicationDidEnterBackground:(UIApplication *)application
{
timer = [NSTimer scheduledTimerWithTimeInterval:10
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:NO];
}
- (void)timerFired:(NSTimer*)timer
{
NSLog( #"yes it is running...");
PickUpCallViewController *call=[[PickUpCallViewController alloc]initWithNibName:#"PickUpCallViewController" bundle:nil];
navi=[[UINavigationController alloc]initWithRootViewController:call];
[[navi navigationController] setNavigationBarHidden:YES animated:YES];
window.rootViewController = navi;
[window makeKeyAndVisible];
}

It is not possible to open programmatically app when you application in to background Mode. But using URL-scheme you can open App from browser.
You just need to set URL scheme as following screenshot:-
First you need to open project-->Target-->info
After this click on info you found at Bottom like this screenshot:
Click on URL Type you got result like following screenshot:
click on (+) and setting URL-Schemes as following:
Save and minimized your application by tapping Home button and open your safari browser. and just type mytestApp:// that you are setting before save as following screenshot:-
That all process working fine like:-

i think its possible by using Remote notification(ios7 new background method) without showing uialertview interface.....

As per iOS limitation we can't able to open any app without user interaction. If you need to open any app then you either force the user to do buy sending push notification where user could able to see your notification and can click to view the app.
Also for opening the app from another app or from a link then you can follow the URL schema method like Nitin Gohel explained above.
If you need to fetch a certain data without user interaction then you can use silent push notification which is commonly called as background fetch. You need to enable the push notification in the background mode and use application:didReceiveRemoteNotification:fetchCompletionHandler: method to handle inside the app. Also we need to make few tweaks in the server side while sending the push notification
aps { content-available: 1 alert: {...} }
There is lot more stuff available in net regarding background fetch and you can able to understand how it is working in the this link.

Related

How to open a Swift App from same screen after phone settings configurations [duplicate]

Currently, when I change the camera permissions for my app in Settings, then navigate back to my app, the app will force a refresh and I will lose my place in the app. I follow these steps exactly:
Open an app that uses the camera permission.
Navigate to some screen within the app (so you can visibly see the refresh later)
Go to the Settings app, navigate to the app's settings, and toggle
the camera permission
Double click home and go back to the app.
After a few seconds, it will refresh, bringing you back to the
first screen
Note: I'm using an iPhone 6 running iOS 8.4
I've noticed this behavior on all apps that have the camera permission. My question is:
Is there some way to prevent the app from refreshing/restarting (on resume) after changing the camera permission? It doesn't seem to happen when you toggle location services, for example, and from a usability perspective this is horrible.
User scenario: If a user navigates deep into your app, then needs to change the camera permission (because say they accidentally clicked no last time), they will be forced to navigate back to that screen when they return. This is especially harmful for an app trying to sell you something, or sign you up for a new account. They might try to introduce a new feature where you can use the camera to take a profile picture or scan your credit card. Because the user didn't know about this feature, they might have previously denied camera access, but now want to enable it. After trying to reenable, they come back to your app to find they have to spend 5+ minutes signing up / making a purchase, again! After that, even I would probably give up.
I'm sure that there is no other ways to prevent restarting app. Actually you will get a SIGKILL message but no Crash log when toggling settings. See below links-
https://devforums.apple.com/message/715855
https://devforums.apple.com/message/714178
The only way to prevent this scenario is to save the previous state of you application while terminating.
Store app your current data into a json/plist/NSUserDefaults/archive user model at applicationWillTerminate: method and
restore saved data at applicationWillEnterForeground:
For example- #SignUpViewController register for UIApplicationWillTerminateNotification which will fire when the app is about to terminate. Store user information there.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name: UIApplicationWillTerminateNotification object:nil];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
// store your data here
}
Hope this will help you:)
The accepted answer is correct, however the workaround does not appear to work in the current version of iOS (9.2) - the application seems to terminate before UIApplicationWillTerminateNotification is fired. However by listening to UIApplicationDidEnterBackgroundNotification, the same can be achieved. e.g in Swift, put this in viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enteringBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
and have a function like this:
func enteringBackground(sender:AnyObject){
// Save application state here
}

How do I embed my app commands with siri or any other voice activation library

Basically, I want my app to be voice activated
If user asks my app to open then it should open
if the user says something it has to be typed in the textbox
if the user says to click on a button it has to be done
if the user wants to be voice read then it should read it out.
basically, I would like to read the user command sometimes if possible in the app and serve my user base the best
There is no much documentation available there,,, so I thought of asking the question here
This is not possible. You cannot use Siri with apps for anything else than what is implemented in the SiriKit framework and SiriKit does not provide any methods for just opening your app without actually handling an intent and custom commands are also not supported at the moment.
For dictation you can use the Speech framework and for the system to "read out" something from your UI, you need to support VoiceOver, which is part of Accessibility.
My purpose is to open secret screen (test screen) into my app. Best way is to display a normally hidden button, I use a fake messaging with Siri. App is ok for Siri request but no other special code is necessary, I just add appDelegate.m method with a postNotification, somewhere some code will append a button
- (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType {
if ([userActivityType isEqualToString:#"INSendMessageIntent"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"modeTest" object:nil];
}
return YES;
}
Now ask Siri "Send message with 'AppName' " a view from my IntentWiewController.m is display, you can abord process by touching screen, application is running now but Notification is send, some process can easily be done like adding any secret control. Next run will hide button.

How can I prevent iOS apps from resetting after changing Camera permissions?

Currently, when I change the camera permissions for my app in Settings, then navigate back to my app, the app will force a refresh and I will lose my place in the app. I follow these steps exactly:
Open an app that uses the camera permission.
Navigate to some screen within the app (so you can visibly see the refresh later)
Go to the Settings app, navigate to the app's settings, and toggle
the camera permission
Double click home and go back to the app.
After a few seconds, it will refresh, bringing you back to the
first screen
Note: I'm using an iPhone 6 running iOS 8.4
I've noticed this behavior on all apps that have the camera permission. My question is:
Is there some way to prevent the app from refreshing/restarting (on resume) after changing the camera permission? It doesn't seem to happen when you toggle location services, for example, and from a usability perspective this is horrible.
User scenario: If a user navigates deep into your app, then needs to change the camera permission (because say they accidentally clicked no last time), they will be forced to navigate back to that screen when they return. This is especially harmful for an app trying to sell you something, or sign you up for a new account. They might try to introduce a new feature where you can use the camera to take a profile picture or scan your credit card. Because the user didn't know about this feature, they might have previously denied camera access, but now want to enable it. After trying to reenable, they come back to your app to find they have to spend 5+ minutes signing up / making a purchase, again! After that, even I would probably give up.
I'm sure that there is no other ways to prevent restarting app. Actually you will get a SIGKILL message but no Crash log when toggling settings. See below links-
https://devforums.apple.com/message/715855
https://devforums.apple.com/message/714178
The only way to prevent this scenario is to save the previous state of you application while terminating.
Store app your current data into a json/plist/NSUserDefaults/archive user model at applicationWillTerminate: method and
restore saved data at applicationWillEnterForeground:
For example- #SignUpViewController register for UIApplicationWillTerminateNotification which will fire when the app is about to terminate. Store user information there.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name: UIApplicationWillTerminateNotification object:nil];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
// store your data here
}
Hope this will help you:)
The accepted answer is correct, however the workaround does not appear to work in the current version of iOS (9.2) - the application seems to terminate before UIApplicationWillTerminateNotification is fired. However by listening to UIApplicationDidEnterBackgroundNotification, the same can be achieved. e.g in Swift, put this in viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enteringBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
and have a function like this:
func enteringBackground(sender:AnyObject){
// Save application state here
}

How programmatically restart an iPhone app in iOS

How programmatically restart an iPhone app in iOS?
I find this way http://writeitstudios.com/david/?p=54
But may be something simple.
The only way I know to do this is not ideal, but it works.
First, your app has to opt out of background execution (multitasking) The app has to quit when exited, not run as a background task. This is done with the plist key UIApplicationExitsOnSuspend.
Second, your app needs to register a custom URL scheme that can be used to launch the app.
Third, you need a web page hosted somewhere that when loaded will redirect to your app's custom URL scheme.
Forth, the user needs an active Internet connection.
To exit and restart, call UIApplication openURL on your hosted redirecting web page. Your app will exit and safari will launch and load your page. The page will redirect Safari to your custom URL scheme, prompting Safari to internally call openURL, causing iOS to launch your app.
my post that you linked to is referring to a Cocoa Application, not the iOS. On the iOS, you can quit an application (but Apple doesn't like this) by using exit(0); but I don't recommend that. You cannot restart iPhone apps though.
Unless you're developing for jailbroken devices, Apple won't even allow you to programatically terminate your app. So restarting the device is out of the question.
Your AppDelegate instance has a method
(void)applicationDidBecomeActive:(UIApplication *)application
{
}
In here, you can put logic to figure out if the app should restart, or continue doing whatever it was doing. For example you can have a BOOL variable appMustRestart that is false at first but gets triggered as true whenever something happens in your app that you'd like the next time to be a fresh relaunch.
if (appMustRestart)
{
[self resetVars]; // call a method that resets all your vars to initial settings
// INSERT CODE HERE TO TRANSFER FOCUS TO INITIAL VIEWCONTROLLER
}

Proper way to exit iPhone application?

I am programming an iPhone app, and I need to force it to exit due to certain user actions. After cleaning up memory the app allocated, what's the appropriate method to call to terminate the application?
On the iPhone there is no concept of quitting an app. The only action that should cause an app to quit is touching the Home button on the phone, and that's not something developers have access to.
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
Have you tried exit(0)?
Alternatively, [[NSThread mainThread] exit], although I have not tried that it seems like the more appropriate solution.
exit(0) appears to a user as crashes, so show a confirmation message to user. After confirmation suspend(home button press programmatically) and wait 2 seconds while app is going background with animation then exit behind user's view
-(IBAction)doExit
{
//show confirmation message to user
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Confirmation"
message:#"Do you want to exit?"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != 0) // 0 == the cancel button
{
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}
}
Check the Q&A here: https://developer.apple.com/library/content/qa/qa1561/_index.html
Q: How do I programmatically quit my iOS application?
There is no API provided for gracefully terminating an iOS application.
In iOS, the user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion.
WARNING: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen.
Additionally, data may not be saved, because -applicationWillTerminate: and similar UIApplicationDelegate methods will not be invoked if you call exit.
If during development or testing it is necessary to terminate your application, the abort function, or assert macro is recommended
Its not really a way to quit the program, but a way to force people to quit.
UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:#"Hit Home Button to Exit" message:#"Tell em why they're quiting" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[anAlert show];
Go to your info.plist and check the key "Application does not run in background". This time when the user clicks the home button, the application exits completely.
Add UIApplicationExitsOnSuspend property on application-info.plist to true.
After some tests, I can say the following:
using the private interface : [UIApplication sharedApplication] will cause the app looking like it crashed, BUT it will call - (void)applicationWillTerminate:(UIApplication *)application before doing so;
using exit(0); will also terminate the application, but it will look "normal" (the springboard's icons appears like expected, with the zoom out effect), BUT it won't call the - (void)applicationWillTerminate:(UIApplication *)application delegate method.
My advice:
Manually call the - (void)applicationWillTerminate:(UIApplication *)application on the delegate.
Call exit(0);.
Your ApplicationDelegate gets notified of intentional quitting by the user:
- (void)applicationWillResignActive:(UIApplication *)application {
When I get this notification I just call
exit(0);
Which does all the work. And the best thing is, it is the useres intent to quit, which is why this should not be a problem calling it there.
On my Audio-App it was necessary to quit the app after people were syncing their device while the music was still playing. As soon as the syncing is complete I get a notification. But quitting the app right after that would actually look like a crash.
So instead I set a flag to REALLY quit the app on the next backgrounding action. Which is okay for refreshing the app after a sync.
My App has been rejected recently bc I've used an undocumented method. Literally:
"Unfortunately it cannot be added to the App Store because it is using a private API. Use of non-public APIs, which as outlined in the iPhone Developer Program License Agreement section 3.3.1 is prohibited:
"3.3.1 Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs."
The non-public API that is included in your application is terminateWithSuccess"
Apple say:
"Warning: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen."
I think that this is a bad assumption. If the user tap a quit button and a message appears that say something like: "The application will now quit.", it doesn't appear to be crashed. Apple should provide a valid way to quit an application (not exit(0)).
You should not directly call the function exit(0) as it will quit the application immediately and will look like your app is crashed. So better to show users a confirmation alert and let them do this themselves.
Swift 4.2
func askForQuit(_ completion:#escaping (_ canQuit: Bool) -> Void) {
let alert = UIAlertController(title: "Confirmation!", message: "Do you want to quit the application", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
completion(true)
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
completion(false)
}))
self.present(alert, animated: true, completion: nil)
}
/// Will quit the application with animation
func quit() {
UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
/// Sleep for a while to let the app goes in background
sleep(2)
exit(0)
}
Usage:
self.askForQuit { (canQuit) in
if canQuit {
self.quit()
}
}
This has gotten a good answer but decided to expand a bit:
You can't get your application accepted to AppStore without reading Apple's iOS Human Interface Guidelines well. (they retain the right to reject you for doing anything against them) The section "Don't Quit Programmatically" http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html
is an exact guideline in how you should treat in this case.
If you ever have a problem with Apple platform you can't easily find a solution for, consult HIG. It's possible Apple simply doesn't want you to do it and they usually (I'm not Apple so I can't guarantee always) do say so in their documentation.
Hm, you may 'have to' quit the application if, say, your application requires an internet connection. You could display an alert and then do something like this:
if ([[UIApplication sharedApplication] respondsToSelector:#selector(terminate)]) {
[[UIApplication sharedApplication] performSelector:#selector(terminate)];
} else {
kill(getpid(), SIGINT);
}
We can not quit app using exit(0), abort() functions, as Apple strongly discourage the use of these functions. Though you can use this functions for development or testing purpose.
If during development or testing it is necessary to terminate your
application, the abort function, or assert macro is recommended
Please find this Apple Q&A thread to get more information.
As use of this function create impression like application is crashing. So i got some suggestion like we can display Alert with termination message to aware user about closing the app, due to unavailability of certain functionality.
But iOS Human Interface Guideline for Starting And Stopping App, suggesting that Never use Quit or Close button to terminate Application. Rather then that they are suggesting to display proper message to explain situation.
An iOS app never displays a Close or Quit option. People stop using an
app when they switch to another app, return to the Home screen, or put
their devices in sleep mode.
Never quit an iOS app programmatically. People tend to interpret this
as a crash. If something prevents your app from functioning as
intended, you need to tell users about the situation and explain what
they can do about it.
In addition to the above, good, answer I just wanted to add, think about cleaning up your memory.
After your application exits, the iPhone OS will automatically clean up anything your application left behind, so freeing all memory manually can just increase the amount of time it takes your application to exit.
- (IBAction)logOutButton:(id)sender
{
//show confirmation message to user
CustomAlert* alert = [[CustomAlert alloc] initWithTitle:#"Confirmation" message:#"Do you want to exit?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
alert.style = AlertStyleWhite;
[alert setFontName:#"Helvetica" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != 0) // 0 == the cancel button
{
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
NSLog(#"exit(0)");
exit(0);
}
}
I used the [[NSMutableArray new] addObject:nil] approach mentioned above to force-quit (crash) the app without making a tell-tale exit(0) function call.
Why? Because my app uses certificate pinning on all network API calls to prevent man-in-the-middle attacks. These include the initialization calls my financial app makes on startup.
If certificate authentication fails, all of my initialization calls error out and leave my app in an indeterminate state. Letting the user go home and then back into the app doesn't help, as unless the app has been purged by the OS it's still uninitialized and untrustworthy.
So, in this one case, we deemed it best to pop an alert informing the user that the app is operating in an insecure environment and then, when they hit "Close", force quit the app using the aforementioned method.
[[UIApplication sharedApplication] terminateWithSuccess];
It worked fine and automatically calls
- (void)applicationWillTerminateUIApplication *)application delegate.
to remove compile time warning add this code
#interface UIApplication(MyExtras)
- (void)terminateWithSuccess;
#end
The user should decide when an app exits.
I don't think it is a good user interaction when an app quits. Therefore there is no nice API for it, only the home button has one.
If there is an error: Implement it better or Notify the user.
If there have to be a restart: Implement it better of Notify the user.
It sounds dumb, but it's bad practice to exit the app without letting the user decide and not notifying him. And since there is a home button for the user interaction, Apple states, there should not be 2 things for the same function (exiting an app).
Exit an app other way than the home button is really non-iOS-esque approach.
I did this helper, though, that use no private stuff:
void crash()
{ [[NSMutableArray new] addObject:NSStringFromClass(nil)]; }
But still not meant for production in my case. It is for testing crash reportings, or to fast restart after a Core Data reset. Just made it safe not to be rejected if function left in the production code.
It may be appropriate to exit an app if it is a long lived app that also executes in the background, for example to get location updates (using the location updates background capability for that).
For example, let's say the user logs out of your location based app, and pushes the app to the background using the home button. In this case your app may keep running, but it could make sense to completely exit it. It would be good for the user (releases memory and other resources that don't need to be used), and good for app stability (i.e. making sure the app is periodically restarted when possible is a safety net against memory leaks and other low memory issues).
This could (though probably shouldn't, see below :-) be achieved with something like:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (/* logged out */) {
exit(0);
} else {
// normal handling.
}
}
Since the app would then exit out of the background it will not look wrong to the user, and will not resemble a crash, providing the user interface is restored the next time they run the app. In other words, to the user it would not look any different to a system initiated termination of the app when the app is in the background.
Still, it would be preferable to use a more standard approach to let the system know that the app can be terminated. For example in this case, by making sure the GPS is not in use by stopping requesting location updates, including turning off show current location on a map view if present. That way the system will take care of terminating the app a few minutes (i.e. [[UIApplication sharedApplication] backgroundTimeRemaining]) after the app enters the background. This would get all the same benefits without having to use code to terminate the app.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (/* logged out */) {
// stop requesting location updates if not already done so
// tidy up as app will soon be terminated (run a background task using beginBackgroundTaskWithExpirationHandler if needed).
} else {
// normal handling.
}
}
And of course, using exit(0) would never be appropriate for the average production app that runs in the foreground, as per other answers that reference http://developer.apple.com/iphone/library/qa/qa2008/qa1561.html
Swift 4.2 (or older)
Library called Darvin can be used.
import Darwin
exit(0) // Here you go
NB: This is not recomanded in iOS applications.
Doing this will get you crash log.
In iPadOS 13 you can now close all scene sessions like this:
for session in UIApplication.shared.openSessions {
UIApplication.shared.requestSceneSessionDestruction(session, options: nil, errorHandler: nil)
}
This will call applicationWillTerminate(_ application: UIApplication) on your app delegate and terminate the app in the end.
But beware of two things:
This is certainly not meant to be used for closing all scenes. (see https://developer.apple.com/design/human-interface-guidelines/ios/system-capabilities/multiple-windows/)
It compiles and runs fine on iOS 13 on an iPhone, but seems to do nothing.
More info about scenes in iOS/iPadOS 13: https://developer.apple.com/documentation/uikit/app_and_environment/scenes

Resources