Search code examples
iosobjective-cframeworksobserver-pattern

[ios]add observer to Target Application from the Framework or custom static library


I have developed an ios lib/framework where i record user login and connect to the server and fetch data from server real time. In the same library/framework I would like to add observer to my application so that I come to know when the app went in background or became active again.

Something similar to what we usually do in the application code itself....(my test application code below. An observer functionality that i want to move to the common lib/framework)

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MyAppWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];

But even though i have defined the method as

void MyAppWillResignActive(id self, SEL _cmd, id application) {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

Solution

  • Pay attention to the signature of the method to be invoked in your selector MyAppWillResignActive.

    EDIT: Moved registration to library initialization as suggested in iosDeveloper09 comment.


    Class level

    • Register during initialize

      + (void)initialize {
          [[NSNotificationCenter defaultCenter]
           addObserver:self
           selector:@selector(applicationWillResignActive:)
           name:UIApplicationWillResignActiveNotification
           object:nil];
      }
      
    • Class handler +

      + (void)applicationWillResignActive:(NSNotification *)notification
      

    Instance level

    • Register during init

      - (instancetype)init
      {
          self = [super init];
          if (self) {
              [[NSNotificationCenter defaultCenter]
               addObserver:self
               selector:@selector(applicationWillResignActive:)
               name:UIApplicationWillResignActiveNotification
               object:nil];
          }
          return self;
      }
      
    • Instance handler -

      - (void)applicationWillResignActive:(NSNotification *)notification
      

    Host

    @property (nonatomic, retain) SO_41526719Library * lib;
    
    // Keep an instance around
    self.lib = [[SO_41526719Library alloc] init];
    

    At runtime

    applicationWillResignActive NSConcreteNotification 0x6000000545e0 {name = UIApplicationWillResignActiveNotification; object = }