How to add custom notification in iOS Custom Keybo

2019-02-18 06:02发布

问题:

I have added Custom Keyboard extension inside my app and running perfect.

I have added NSNotification in my keyboard extension class like this:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKeyboardColor) name:@"keyboard_color"  object:nil];

Now I am calling this notification from my view controller class like this:

[[NSNotificationCenter defaultCenter] postNotificationName:@"keyboard_color" object:self];

Now I have added my notification selector method in my keyboard extension class like this:

-(void)changeKeyboardColor{
}

But it is not working. I am testing in simulator and I don't know How to test keyboard extension in simulator.

Thanks.

回答1:

Create App Group from developer.apple.com

Group name must be like group.XXXXX

Enable App Group if it's disable for both app id and extension app id.

Update to existing provisioning profiles if it's look Invalid!

Go to Target and mention group name which you have created

Go to Keyboard extension and mention same group name

Now you done with all required settings.

In your project store value in NSUserDefaults

 let userd: NSUserDefaults = NSUserDefaults(suiteName: "group.XXXXX")!
 userd.setObject("test11", forKey: "key")
 userd.synchronize()

//Objective-C

NSUserDefaults *userd = [[NSUserDefaults alloc]initWithSuiteName:@"group.XXXXX"];
[userd setObject:@"test11" forKey:@"key"];//set the object you want to share
[userd synchronize];

For retrieving NSUserDefaults value in Extension class

 let userd: NSUserDefaults = NSUserDefaults(suiteName: "group.XXXXX")!
 print(userd.objectForKey("key"))

// Objective-C

NSUserDefaults *userd = [[NSUserDefaults alloc]initWithSuiteName:@"group.XXXXX"];
NSLog(@"%@",[userd objectForKey:@"key"]);

Happy Coding!



回答2:

The method for a notification should take a single parameter, the triggering notification:

-(void)changeKeyboardColorNotice: (NSNotification *) theNotice
{
  NSLog(@"In %s", __PRETTY_FUNCTION__);
}

And you need to add a colon to the selector:

[[NSNotificationCenter defaultCenter] addObserver:self
  selector: @selector(changeKeyboardColorNotice:) 
  name: @"keyboard_color"  
  object: nil];