'Can't get Orientation notification on iPhone without UIViewController
I am trying to develop an iPhone app using xcode13 with iPhone 11 simulator. I used Xcode template to create a basic app. Now I created a new class (not derived from UIViewController) and tried to get orientation notifications, but I am getting nothing. I tried to add the same code on class that derived from UIViewController and it worked. why ? why ?
- Why it is only working from the UIViewController's derived class?
- Can I make it work from a class that isn't derived from UIViewController ?
here is my code that is not working :
main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Orientation/Orientation.h"
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
NSLog(@"Hello world !");
OrientationService * os = [[OrientationService alloc] init];
[os onStart];
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
Orientation/Orientation.h
#ifndef Orientation_h
#define Orientation_h
@interface OrientationService : NSObject {
NSInteger * orientation_state;
}
- (void) onStart;
- (void) orientationStateDidChange:(NSNotification*) notification;
@end
Orientation/Orientation.m
#endif /* Orientation_h */
#import <Foundation/Foundation.h>
#import "Orientation.h"
#import <UIKit/Uikit.h>
@implementation OrientationService
-(void) orientationStateDidChange:(NSNotification*) notification {
NSLog(@"got notified");
}
-(instancetype)init{
self = [super init];
NSLog(@"OrientationService alloc");
return self;
}
-(void)onStart{
NSLog(@"starting orientation service");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationStateDidChange:) name:(UIDeviceOrientationDidChangeNotification) object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
}
@end
Solution 1:[1]
I spent so long on this but it just hit me! It's because os in main() isn't being retained in memory. Instead, either implement the functionality in the App Delegate, or retain an instance of your OrientationService object in the App Delegate. For example:
AppDelegate.h
#import <UIKit/UIKit.h>
#include "Orientation.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) OrientationService *os;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize os;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
os = [[OrientationService alloc] init];
[os onStart];
return YES;
}
@end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ramkaz99 |
