Building a Talk App in Swift Using Multipeer Connectivity Framework
When programming in iOS, there are certain aspects of the SDK that pull the developers' attention and interest a lot more than others, and one of them is the Multipeer Connectivity framework. As you know, the MPC framework is not fresh in iOS 8, instead it was first-introduced in the seventh (7th) version of it, about a year and a half ago. In the past, I'd written a duo of tutorials about it, and to tell the truth, I was astonished from the interest that people seemed to have about it. Now, some months later, I comeback with a fresh post regarding it, as I believe that there are still things that need to be explained.
You may wonder why I bring to the surface a topic a bit old, and not something fresh included in iOS 8. Well, I'm doing that for three reasons:
- Many readers have approached me through e-mail messages, asking how to perform various tasks in multipeer connectivity that were not mentioned in the previous two tutorials. By answering to all those messages, I found out that there's a need that I hadn't noticed earlier; People want more information about it, which is hard to find sometimes.
- The implementation I introduced in the last duo tutorials was based in the use of a default, pre-made view controller existing in the iOS SDK for inviting other peers and establishing a connection. I found out that people was asking for manual implementation, and that's something we are about to see here.
- I think that it will be fairly useful and educational to see how to implement MPC in Swift.
During the lifetime of the multipeer connectivity framework, it has been proved that the possibilities that it came to suggest gave birth to fresh ideas to a good number of developers. Connecting devices using such a ordinary way seems so attractive, and that's why programmers want to integrate it into their applications. However, if you haven't used the MPC framework yet, I must warn you: Sometimes it's not as reliable as you may expect, and that's something I've seen personally in my projects, and also other developers have reported to me. MPC uses both Bluetooth and WiFi to connect nearby devices, but even however it sounds too good and promising, sometimes the connection either fails or is to slow, leading to communication errors. That's significant in cases you need to transfer vital data. I would advice you to use a backup communication solution (such as a web service), so you make sure that there is an alternative and your application will proceed to work even if the MPC fails. However, despite to what I just said, I still believe that MPC if a good implement for all iOS developers, so it worths it one (last) more tutorial.
Getting into the details of MPC is not something I'm planning to do. If you want to get a taste of it, then simply pay a visit to this tutorial here. Instead, I'm going to give you a brief overview of the multipeer connectivity framework.
So, MPC contains four significant classes indicating the following concepts:
- Peer (MCPeerID): A peer is actually a device, programmatically represented. It's usually the very first thing needs to be set up, as an object of this class is used as a parameter upon the initialization of the next classes' instances. Also, it contains an significant property, named displayName. This is the device name appearing to the other, nearby peers.
- Session (MCSession class): It's the connection established inbetween two peers, after the very first one has invited the 2nd, and of course the invitation has been accepted. A session regards two devices only. A third device cannot be connected to an existing session, instead another one is used.
- Browser (MCNearbyServiceBrowser class): The methods of this class are used to find other nearby devices and invite them to join a session. As a prerequisite, the other devices must advertise themselves. In this tutorial we'll use this class to by hand invite other devices.
- Advertiser (MCNearbyServiceAdvertiser): This class is responsible for advertising a device, meaning making the device visible or not to others, and for accepting or not invitations from other peers for connecting to sessions.
The logic of the multipeer connectivity framework is elementary: A device (a peer) using its browser, searches for other devices around. As I said, a device must advertise itself so as to be discoverable. Once it finds one or more peers, it can send an invitation for connecting to a session. The invitation can be sent either automatically once a nearby peer is found, or after the user has determined to do so. Actually, this is totally up to the application that is being implemented, so there's not a standard recipe. You will be the one to determine when you'll send an invitation. In any case, once the invitation has been accepted, the session is established and then the two peers can send and receive data, resources, or rivulets.
My aim in this post is to display you how to programmatically browse, invite and connect to other peers. Note that what you'll see next, it's just a way of implementation. Obviously, you can use all the provided devices by the MPC in the way you want and perform your own implementation that suits to the application you build. What you'll see it's just a sample of how the MPC framework can be implemented and integrated purely programmatically from the beginning to the end, without using any pre-made view controller of the SDK. Hopefully, by the end of this tutorial, many of you may find some answers to what you seek.
Lastly, if you've never worked with the MPC framework before I encourage you to take a quick look at both the official documentation by Apple, and my previous tutorials, so you have an idea before you proceed. Having said that, let's don't waste any more time, and let's dive in some programming aspects of the multipeer connectivity.
About the Demo App
Let's talk now a bit about the demo application of this tutorial, which is going to be a talk application. Okay, I know that it might be a script too common and that we created a talk app in the very first multipeer connectivity tutorial, however let me justify myself by telling this: No matter how hard I attempted to find another, better example, the talk application was always the #1 in my list when I was thinking about the programming stuff I wished to present today. I believe this is something that you'll agree with too by the end of the tutorial, so let's stir forward.
As we have already done in many tutorials, we are not going to build the app from scrape. Instead, I'll give you a starter project which you can download here, and we'll keep working on that. The application will be called MPCRevisited, and I think that is the best title in this case. Please go and navigate yourself around the project once you download it, so you get familiarized with it and be able to work prompt in it.
As I said, we are going to build a talk application. This application will be parted by two view controllers, where the 2nd one will be modally displayed to the user. If you look to the Interface Builder in the project, you'll see that in the very first view controller's scene there's a tableview. In this tableview we are going to display all the nearby devices discovered by the multipeer connectivity framework, while the peers' list will be dynamically refreshed as existing peers will be lost, and fresh peers will show up near to the device. In the very first view controller you will also find a toolbar with a bar button item in it. Later on, we'll use this button item to turn on and off the discoverability of the device with aim to see how the advertising feature of the MPC works.
Once a listed peer is tapped, we'll ask the user at the other end if he wants to talk or not. If he declines, nothing will happen. But upon acceptance, the 2nd view controller named ChatViewController will be displayed on the screen, so the two devices can exchange text messages. In the 2nd view controller scene there is a textfield for writing the message, and a tableview where all the messages will be listed. Also, a toolbar at the top and with another bar button item will be used to end the talk. I believe its fully pointless to discuss any further details here, as we'll see everything fairly scrupulously upon implementation.
Before I present you a few screenshots of the final app, let me also say one last thing. Even tho’ we can connect a device with up to seven (7) more using the multipeer connectivity, in our example we are going to connect it to just one more peer, the one that we'll talk with each time. Let me clarify that connecting peers together using sessions is a downright different thing from discovering and listing all nearby peers, and now I'm referring to the very first case. Anyway, you'll see everything step by step beginning from the next part, but for now, just take a taste from the app:
A Custom-built Class
Knowing what our project is all about, let's get our arms dirty by creating a custom-made class. In this class we will deal with the multipeer connectivity by implementing all the necessary framework methods needed to function decently. Also, as you'll see by the end of this part, we will create a fresh protocol with ultimate objective to use the delegation pattern and pass that way messages to the calling class.
But, very first things very first. In Xcode, hit the Cmd-N key combination on your keyboard. In the guide that shows up, select to create a fresh Cocoa Touch Class as shown below:
In the 2nd step, make the fresh class subclass of the NSObject class, and name it MPCManager.
Proceed to get finished with the guide, and then make sure that you are working on the MPCManager.swift file.
As the very first line of code, we'll import the multipeer connectivity framework to the class. So, head to the top of the file and add the following: