I'm new to make iPhone App with Objective-c
I want to make the App which sends a notification when iPhone screen is locked(Pressed Lock button)
How can I make this app?
I'm trying to make it using "applicationWillSuspend", but
/*----------------------------------------*/
- (void)applicationWillSuspend
{
NSLog(#"WillSuspend");
}
/*----------------------------------------*/
This code doesn't work
I'm not sure when applicationWillSuspend is called
Please, give me some knowledge
#import "AppDelegate.h"
#import <notify.h>
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// iOS8 Notification permit
if ([UIApplication
instancesRespondToSelector:#selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication]
registerUserNotificationSettings:[UIUserNotificationSettings
settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil]];
}
return YES;
int notify_token;
notify_register_dispatch("com.apple.springboard.lockstate",
¬ify_token,
dispatch_get_main_queue(),
^(int token)
{
uint64_t state = UINT64_MAX;
notify_get_state(token, &state);
if(state == 0) {
NSLog(#"unlock device");
} else {
NSLog(#"lock device");
}
}
);
}
Import this in app delegate #import <notify.h>
Write this piece of code in didFinishLaunchingWithOptions
int notify_token;
notify_register_dispatch("com.apple.springboard.lockstate",
¬ify_token,
dispatch_get_main_queue(),
^(int token)
{
uint64_t state = UINT64_MAX;
notify_get_state(token, &state);
if(state == 0) {
NSLog(#"unlock device");
} else {
NSLog(#"lock device");
}
}
);
So once your iPhone gets locked, you will get "lock device" as log. So you can write your code in that block. This will help you.
You can't do that on the iPhone.
But through, Darwin notifications. You can detect the event when the device is locked by "com.apple.springboard.lockcomplete".
Have a look at these links too hopefully it may help you:
1) Lock Unlock events iphone
2) How can I detect screen lock/unlock events on the iPhone?
applicationWillSuspend method doesn't exist natively, but in the AppDelegate.m you can play with applicationWillResignActive and applicationWillResignActive these methods will be called when the user hits the home button and the app will go to the background (here you can keep your connection live, but you should read the apple documentation regarding background tasks because your connection cannot be live forever if the app remains in the background. There are other ways to keep your app up to date like update on push notification etc):
- (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.
}
and this method will be called when the app will get terminated (closed completely from multitasking).
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
You can handle your connections within these methods.
Related
I'm creating an app that displays monitors iBeacon regions, which means that when the device is locked and within range of a beacon, my app's icon is shown on the lock screen in the bottom left.
Is there any way that I can detect if my app is launched through this lock screen icon, and run some code?
When the icon appears, it indicates that a beacon region has been entered. The CLLocationManager delegate's didEnterRegion method will be called when the icon first appears.
You can put custom code there to set a flag indicating the icon appeared.
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
_iconShown = YES;
}
Then, when your app comes to the foreground, you can check this flag to see if it is set, and execute your custom logic:
- (void)applicationWillEnterForeground:(UIApplication *)application {
if (_iconShown) {
_iconShown = NO;
// Put custom logic here for launching from the icon
}
}
hmm, there is an alternative way, that you can handle it, just create an variable self.backgroundedToLockScreen like:
- (void)applicationWillEnterForeground:(UIApplication *)application {
if (self.backgroundedToLockScreen) {
... // app was backgrounded to lock screen
} else {
... // app was backgrounded on purpose by tapping the home button or switching apps.
}
self.backgroundedToLockScreen = NO;
}
and
- (void)applicationWillEnterForeground:(UIApplication *)application {
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (UIApplicationStateInactive == state || // detect if coming from locked screen (iOS 6)
self.backgroundedToLockScreen) // detect if backgrounded to the locked screen (iOS 7)
{
... // app is coming from or was backgrounded to lock screen
} else {
... // app was backgrounded on purpose by tapping the home button or switching apps
}
self.backgroundedToLockScreen = NO;
}
Hope this could be useful for you.
I have a problem during I developing application IOS and I used Parse Push Notification Framework for push remote notification. the problem is when the application is running and the same time the notification has been sent, the application is display modal alert box automatically. So, I don't want the modal alert display. I spent much times on it, and I do research on internet, read documents but no result found, I feel nobody knew about this. Please Help me!
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIImage *navBackgroundImage = [UIImage imageNamed:#"nav_bg_new"];
[[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
// ****************************************************************************
// Uncomment and fill in with your Parse credentials:
// [Parse setApplicationId:#"your_application_id" clientKey:#"your_client_key"];
// ****************************************************************************
[Parse setApplicationId:#"my_app_id" clientKey:#"my_client_key"];
// Override point for customization after application launch.
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];
return YES;
}
- (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)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
currentInstallation.channels = #[#"global"];
[currentInstallation saveInBackground];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
if (error.code == 3010) {
NSLog(#"Push notifications are not supported in the iOS Simulator.");
} else {
// show some alert or otherwise handle the failure to register. NSLog(#"application:didFailToRegisterForRemoteNotificationsWithError: %#", error);
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
}
Thanks so much in advance.
If you only want to make sure you DO NOT see notifications when the app is opening, set a BOOL isOpening to TRUE in your application:willFinishLaunchingWithOptions: and set it to FALSE during application:didFinishingLaunchingWithOptions:, then change the behavior of didReceiveRemoteNotification: and the call to PFPush handlePush: accordingly.
You can try this instead:
#property (nonatomic, assign) BOOL isLaunching;
- (void)applicationWillEnterForeground:(UIApplication *)application
{
isLaunching = TRUE;
}
- (void)applicationDidEnterForeground:(UIApplication *)application
{
isLaunching = FALSE;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (!isLaunching) {
//Only fire the push handler if the application isn't active
[PFPush handlePush:userInfo];
}
}
My application after 30 seconds of doing nothing should came to the background. If there's no activity after 30 seconds, I want to log the user out. It's application which contains user interface. When the user want to back he must write again his username and password. I put below my code:
Timer.m:
#define kApplicationTimeoutInMinutes 0.1
#define kApplicationDidTimeoutNotification #"AppTimeOut"
#interface Timer : UIApplication
{
NSTimer *myidleTimer;
}
-(void)resetIdleTimer;
Timer.h:
#implementation Timer
//here we are listening for any touch. If the screen receives touch, the timer is reset
-(void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if (!myidleTimer)
{
[self resetIdleTimer];
}
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0)
{
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan)
{
[self resetIdleTimer];
}
}
}
//as labeled...reset the timer
-(void)resetIdleTimer
{
if (myidleTimer)
{
[myidleTimer invalidate];
}
//convert the wait period into minutes rather than seconds
int timeout = kApplicationTimeoutInMinutes * 60;
myidleTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:#selector(idleTimerExceeded) userInfo:nil repeats:NO];
}
//if the timer reaches the limit as defined in kApplicationTimeoutInMinutes, post this notification
-(void)idleTimerExceeded
{
[[NSNotificationCenter defaultCenter] postNotificationName:kApplicationDidTimeoutNotification object:nil];
}
AppDelegate.m:
#implementation AppDelegate
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationDidTimeout:) name:kApplicationDidTimeoutNotification object:nil];
return YES;
}
-(void)applicationDidTimeout:(NSNotification *) notif
{
NSLog (#"time exceeded!!");
//This is where storyboarding vs xib files comes in. Whichever view controller you want to revert back to, on your storyboard, make sure it is given the identifier that matches the following code. In my case, "mainView". My storyboard file is called MainStoryboard.storyboard, so make sure your file name matches the storyboardWithName property.
UIViewController *viewController = [[UIStoryboard storyboardWithName:#"Main" bundle:NULL] instantiateViewControllerWithIdentifier:#"login"];
[(UINavigationController *)self.window.rootViewController pushViewController:viewController animated:YES];
}
//metoda, która informuje o przejsciu z aktywnego do nieaktywnego stanu
- (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.
}
//- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler
- (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)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (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.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
If I understand this correctly, you want a similar functionality to some password managers, which have a functionality of locking themselves after a certain period of time.
First, lets make clear that you cannot send the app to background on iOS. That is up to the user.
What you can do is lock the application after a certain period of time and display user and password prompt screen. To do this you need a timer (NSTimer), which gets restarted at every action by the user. If at any time timer gets to it's end - the 30 second interval passes, timer will execute your method, where you can display a modal view controller with user and password prompt. This way the app will stay locked until user enters username and password.
Detecting last action can also be done in multiple ways:
Detecting last user's touch
Adding few lines of code to all app actions
Swizzling navigation methods
...
I am creating an application where I am retrieving data from the server like below:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self retrievedatafromserver];
dispatch_async(dispatch_get_main_queue(), ^{
//UIUpdation, fetch the image/data from DB and update into your UI
});
});
How do I retrieve data from the server even if application goes to background?
Thanks & Regards
sumana
If Your scope of project is in only iOS 7 then you can use A new background mode which comes in the iOS 7 and onwards. You can fetch the data in background mode without any extra efforts of coding.
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
Now that your app already knows to initiate background fetch, let’s tell it what to do. The method -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler will assist in doing so. This method is called every time that a background fetch is performed, and should be included in the AppDelegate.m file. The complete version is provided below:
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
UINavigationController *navigationController = (UINavigationController*)self.window.rootViewController;
id topViewController = navigationController.topViewController;
if ([topViewController isKindOfClass:[ViewController class]]) {
[(ViewController*)topViewController insertNewObjectForFetchWithCompletionHandler:completionHandler];
} else {
NSLog(#"Not the right class %#.", [topViewController class]);
completionHandler(UIBackgroundFetchResultFailed);
}
}
Now in your controller. Do like that
- (void)insertNewObjectForFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(#"Update the tableview.");
self.numberOfnewPosts = [self getRandomNumberBetween:0 to:4];
NSLog(#"%d new fetched objects",self.numberOfnewPosts);
for(int i = 0; i < self.numberOfnewPosts; i++){
int addPost = [self getRandomNumberBetween:0 to:(int)([self.possibleTableData count]-1)];
[self insertObject:[self.possibleTableData objectAtIndex:addPost]];
}
/*
At the end of the fetch, invoke the completion handler.
*/
completionHandler(UIBackgroundFetchResultNewData);
}
Note :- If you have to give supportability on iOS 6 and below then avoid this approach. Because it's not available.
When your app enters background mode. you can access code for couple of seconds. Suppose the background queue is still performing and you entered background. then you might need to recall the method when app entered foreground. (take a bool variable and check whether the process is completed or not, if process is completed no issues. if not call the method again.).
If you want to make app run in background mode also then you need to request for background run mode in plist. See this link for reference only for these features we can active background run mode and you can active any of them according to you usage http://blogs.innovationm.com/support-for-applications-running-in-background-ios/
I am new to Objective-C and I'm making my first app, a single-view app. When I run my program ,the fullscreen ad that is supposed to appear (I'm using RevMob) appears. However, when I exit the ad I get a black screen with a blue status bar at the top.
I have tried many things, such as setting my main view controller as initial view controller, restarting my computer, changing/removing debugger, resetting the iOS simulator, etc.
My Xcode version is 4.6 and my OS is mac OSX 10.8.4
I don't want to delete Xcode and I also don't want to remove ads because that is my only source of income.
Here is my code:
Appdelegate.m
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
[RevMobAds startSessionWithAppID:#"myappid"];
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
[self.window makeKeyAndVisible];
return YES;
}
- (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)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
RevMobFullscreen *ad = [[RevMobAds session] fullscreen];
[ad loadWithSuccessHandler:^(RevMobFullscreen *fs) {
[fs showAd];
NSLog(#"Ad loaded");
} andLoadFailHandler:^(RevMobFullscreen *fs, NSError *error) {
NSLog(#"Ad error: %#",error);
} onClickHandler:^{
NSLog(#"Ad clicked");
} onCloseHandler:^{
NSLog(#"Ad closed");
}];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)dealloc
{
[_window release];
[super dealloc];
}
#end
Appdelegate.h:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic)UIWindow *window;
#end
There is nothing wrong with the ad code. What seems to be (not) happening is that your app has no content. I suspect that you haven't set up the rootViewController (initial view controller) for the app correctly.
This is what you need to do:
Get rid of all of the app ad code and just make an app that works. All it has to do is correctly show an initial view controller. You could just make a new project in XCode using the Single View Application template.
Add your app code as per this example. You will invoke the code from your initial view controller via a button.
Once that is working, you can add the code into - (void)applicationDidBecomeActive:(UIApplication *)application as per your question. When you dismiss the advert, you should see your initial view controller.