Correct syntax for writing NativeScript plugin

68 Views Asked by At

I'm learning about NativeScript plugins and am trying to get the PubNub iOS SDK working. So far (with the TypeScript below), I am able to successfully configure, subscribe to channels, and publish messages. I'm trying to receive messages as well by converting the "// Handle new message..." section to TypeScript as well, but haven't been able to get it working. How would I write this?

Objective-C:

// Initialize and configure PubNub client instance
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" subscribeKey:@"demo"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];

// Subscribe to demo channel with presence observation
[self.client subscribeToChannels: @[@"my_channel"] withPresence:YES];

// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
    NSLog(@"Received message");
}

// Publish message
[self.client publish: @{@"message": @"this is my message"} 
           toChannel: @"my_channel" withCompletion:^(PNPublishStatus *status) {
}];

Typescript:

// Initialize and configure PubNub client instance
this.config = PNConfiguration.configurationWithPublishKeySubscribeKey("demo", "demo");
this.client = PubNub.clientWithConfiguration(this.config);
this.client.addListener();

// Subscribe to demo channel with presence observation
this.client.subscribeToChannelsWithPresence(channels, true);

// Handle new message from one of channels on which client has been subscribed. 
   ?

// Publish message
this.client.publishToChannelWithCompletion(msgObj, channel, function(publishStatus) {
  console.log(publishStatus.data)
})
1

There are 1 best solutions below

1
On BEST ANSWER

Looks like you are missing the PNObjectEventListener delegate here. You should implement the delegate and pass it's instance to addListener function for the didReceiveMessage callback to be invoked upon a new message.

For example here you can see how the core framework implements UITextViewDelegate for TextView so it could be notified upon changes and other events.

Since you are using TypeScript, take advantage of typings for your PubNub library so it may be easy for you to get find the right syntax.