We need to set up our Collection View so that, when the user taps on a cell, it will add the reservation to the conversation in iMessages. When creating a message to send, we can set the following things:
We will use everything but Trailing Caption and Trailing Subcaption.
- Open MessagesViewController in the MessageApp folder in the Navigator panel.
- In your main class declaration, add the following method after the setupCollectionView() method in the private extension:
func createMessage(with restaurant:RestaurantItem) {
if let conversation = activeConversation {
let layout = MSMessageTemplateLayout()
layout.image = UIImage(named: "restaurant-detail")
layout.caption = "Table for 7, tonight at 10:00 PM"
layout.imageTitle = restaurant.name
layout.imageSubtitle = restaurant.cuisine
let message = MSMessage()
message.layout = layout
message.url = URL(string: "emptyURL")
conversation.insert(message, completionHandler: { (error: Error?) in
if error != nil {
print("there was an error (error)")
}
else {
self.requestPresentationStyle(.compact)
}
})
}
}
In this method, we are setting up MSMessage. We'll check for an active conversation first. If true, we'll then set up our layout. Here, we are just using an image from our assets to create an image background (we could have also used a video, for example). Also, we set the caption to Table for 7, tonight at 10:00PM. This allows the receiver to see all of the relevant information for the reservation. Next, we set the restaurant name as the image title and the restaurant's cuisine as the image subtitle. Then, we create an instance of MSMessage, pass it the layout we created, and give it a URL (which, in our case, is just an empty string, since we don't have a URL). Finally, we insert the message into the conversation. We need to make sure that, when we want to send a message, we are in compact mode; otherwise, the user will think that the app does not work.
Lastly, we just need to add the code that calls our createMessage() method. Add the following method in your extension, before the last curly bracket:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedRestaurant = manager.restaurantItem(at: indexPath)
guard let restaurant = selectedRestaurant else { return }
createMessage(with: restaurant)
}
Here, we are checking for when the user taps a cell; then, we get selectedRestaurant and pass it to our createMessage() method.
Let's build and run the project by hitting the Play button (or by using command + R). Select a restaurant and you will now see a message with the selected restaurant in the message area:
You can see that, with a little bit of work, you can add a nice iMessages app to your app.