Nirav
Nirav

Reputation: 157

How to add custom notification in iOS Custom Keyboard?

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.

Upvotes: 4

Views: 1276

Answers (2)

kb920
kb920

Reputation: 3089

Create App Group from developer.apple.com

enter image description here

Group name must be like group.XXXXX

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

enter image description here

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

Go to Target and mention group name which you have created

enter image description here

Go to Keyboard extension and mention same group name

enter image description here

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!

Upvotes: 2

Duncan C
Duncan C

Reputation: 131418

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];

Upvotes: 0

Related Questions