Send and Receive Images

Overview

This guide covers sending and receiving images within a conversation.

Before you begin, make sure you added the SDK to your app and you are able to create a simple conversation.

NOTE: A step-by-step tutorial to building a web-based chat application is also available for JavaScript and iOS.

This guide will make use of the following concepts:

  • Conversation Events - image events that fire on a Conversation, after you are a Member

Send an Image

Given a conversation you are already a member of:

const fileInput = document.getElementById('fileInput');
conversation.sendImage(fileInput.files[0]).then((imageRequest) => {
  ...
}).catch(errorLogger)
let image = UIImage(named: "file.png")
guard let imageData = image?.pngData() else { return }

conversation.sendAttachment(with: NXMAttachmentType.image,
                            name: "File name",
                            data: imageData,
                            completionHandler: { (error) in
    if let error = error {
        NSLog("Error sending image: \(error.localizedDescription)")
        return
    }
    NSLog("Image sent")
})
[conversation sendAttachmentWithType:NXMAttachmentTypeImage 
                                name:@"File name"
                                data:[NSData dataWithContentsOfFile:@"file.png"]
                   completionHandler:^(NSError * _Nullable error) {
    NSLog(@"Image sent");
}];

Receive an Image

A image conversation event will be received when a member sends an image to a conversation:

conversation.on('image', (sender, event) => {
  console.log('*** Image received', sender, event);
});

Add NXMConversationDelegate as an extension to a ViewController or similar, and implement conversation(_ conversation: NXMConversation, didReceive event: NXMImageEvent):

Note: The first method below is required when implementing NXMConversationDelegate:

extension ViewController: NXMConversationDelegate {
    func conversation(_ conversation: NXMConversation, didReceive error: Error) {
        NSLog("Conversation error: \(error.localizedDescription)")
    }
    func conversation(_ conversation: NXMConversation, didReceive event: NXMImageEvent) {
        NSLog("Received image event: \(event.originalImage)")
    }
}

Have a ViewController, or similar, conform to NXMConversationDelegate and implement conversation:didReceiveImageEvent::

Note: The first method below is required when implementing NXMConversationDelegate:

- (void)conversation:(NXMConversation *)conversation didReceive:(NSError *)error {
    NSLog(@"Conversation error: %@", error.localizedDescription);
}
- (void)conversation:(NXMConversation *)conversation didReceiveImageEvent:(NXMImageEvent *)event {
    NSLog(@"Received image event: %@", event.originalImage);
}