SUSI provided exciting features in the chat screen. The user can ask a different type of queries and SUSI respond according to the user query. If the user wants to get news, the user can just ask news and SUSI respond with the news. Like news, SUSI can respond to so many queries. Even user can ask SUSI for the image of anything. In response, SUSI displays the image that the user asked. Exciting? Let’s see how displaying images in the chat screen of SUSI iOS is implemented.
Getting image URL from server side –
When we ask susi for the image of anything, it returns the URL of image source in response with
answer action type. We get the URL of the image in the
expression key of
actions object as below:
Implementation in App –
In the app, we check if the response coming from server is image URL or not by following two methods.
One – Check if the expression is a valid URL:
The method above return boolean value if the expression is valid or not.
Two – Check if the expression contains image source in URL:
The method above returns the boolean value if the URL string is image source of not by checking its extension.
If both the methods return true, the expression is a valid URL and contain image source, then we consider it as an Image and proceed further.
In collectionView of the chat screen, we register
ImageCell and present the cell if the response is the image as below.
Registering the Cell –
register(_:forCellWithReuseIdentifier:) method registers a class for use in creating new collection view cells.
Presenting the Cell using
cellForItemAt method of UICollectionView –
The implementation of
cellForItemAt method is responsible for creating, configuring, and returning the appropriate cell for the given item. We do this by calling the
dequeueReusableCell(withReuseIdentifier:for:) method of the collection view and passing the reuse identifier that corresponds to the cell type we want. That method always returns a valid cell object. Upon receiving the cell, we set any properties that correspond to the data of the corresponding item, perform any additional needed configuration, and return the cell.
ImageCell, we present a
UIImageView that display the image. When cell the message var, it call downloadImage method to catch and display image from server URL using Kingfisher method.
In method below –
- Get image URL string and check if it is image URL
- Convert image string to image URL
- Set image to the imageView
We have added a tap gesture to the
imageView so that when the user taps the image, it opens the full image in the browser by using the method below:
Final Output –
- Apple’s Documentations on collectionView(_:cellForItemAt:) method
- Apple’s Documentations on register(_:forCellWithReuseIdentifier:) method
- SUSI iOS Link: https://github.com/fossasia/susi_iOS
- SUSI API Link: http://api.susi.ai/
- Kingfisher – A lightweight, pure-Swift library for downloading and caching images from the web